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 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_Invalid:
559   case Sema::TDK_InstantiationDepth:
560   case Sema::TDK_TooManyArguments:
561   case Sema::TDK_TooFewArguments:
562     break;
563 
564   case Sema::TDK_Incomplete:
565   case Sema::TDK_InvalidExplicitArguments:
566     Result.Data = Info.Param.getOpaqueValue();
567     break;
568 
569   case Sema::TDK_Inconsistent:
570   case Sema::TDK_Underqualified: {
571     // FIXME: Should allocate from normal heap so that we can free this later.
572     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
573     Saved->Param = Info.Param;
574     Saved->FirstArg = Info.FirstArg;
575     Saved->SecondArg = Info.SecondArg;
576     Result.Data = Saved;
577     break;
578   }
579 
580   case Sema::TDK_SubstitutionFailure:
581     Result.Data = Info.take();
582     if (Info.hasSFINAEDiagnostic()) {
583       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
584           SourceLocation(), PartialDiagnostic::NullDiagnostic());
585       Info.takeSFINAEDiagnostic(*Diag);
586       Result.HasDiagnostic = true;
587     }
588     break;
589 
590   case Sema::TDK_NonDeducedMismatch:
591   case Sema::TDK_FailedOverloadResolution:
592     break;
593   }
594 
595   return Result;
596 }
597 
598 void OverloadCandidate::DeductionFailureInfo::Destroy() {
599   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
600   case Sema::TDK_Success:
601   case Sema::TDK_Invalid:
602   case Sema::TDK_InstantiationDepth:
603   case Sema::TDK_Incomplete:
604   case Sema::TDK_TooManyArguments:
605   case Sema::TDK_TooFewArguments:
606   case Sema::TDK_InvalidExplicitArguments:
607     break;
608 
609   case Sema::TDK_Inconsistent:
610   case Sema::TDK_Underqualified:
611     // FIXME: Destroy the data?
612     Data = 0;
613     break;
614 
615   case Sema::TDK_SubstitutionFailure:
616     // FIXME: Destroy the template argument list?
617     Data = 0;
618     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
619       Diag->~PartialDiagnosticAt();
620       HasDiagnostic = false;
621     }
622     break;
623 
624   // Unhandled
625   case Sema::TDK_NonDeducedMismatch:
626   case Sema::TDK_FailedOverloadResolution:
627     break;
628   }
629 }
630 
631 PartialDiagnosticAt *
632 OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
633   if (HasDiagnostic)
634     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
635   return 0;
636 }
637 
638 TemplateParameter
639 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
640   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
641   case Sema::TDK_Success:
642   case Sema::TDK_Invalid:
643   case Sema::TDK_InstantiationDepth:
644   case Sema::TDK_TooManyArguments:
645   case Sema::TDK_TooFewArguments:
646   case Sema::TDK_SubstitutionFailure:
647     return TemplateParameter();
648 
649   case Sema::TDK_Incomplete:
650   case Sema::TDK_InvalidExplicitArguments:
651     return TemplateParameter::getFromOpaqueValue(Data);
652 
653   case Sema::TDK_Inconsistent:
654   case Sema::TDK_Underqualified:
655     return static_cast<DFIParamWithArguments*>(Data)->Param;
656 
657   // Unhandled
658   case Sema::TDK_NonDeducedMismatch:
659   case Sema::TDK_FailedOverloadResolution:
660     break;
661   }
662 
663   return TemplateParameter();
664 }
665 
666 TemplateArgumentList *
667 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
668   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
669     case Sema::TDK_Success:
670     case Sema::TDK_Invalid:
671     case Sema::TDK_InstantiationDepth:
672     case Sema::TDK_TooManyArguments:
673     case Sema::TDK_TooFewArguments:
674     case Sema::TDK_Incomplete:
675     case Sema::TDK_InvalidExplicitArguments:
676     case Sema::TDK_Inconsistent:
677     case Sema::TDK_Underqualified:
678       return 0;
679 
680     case Sema::TDK_SubstitutionFailure:
681       return static_cast<TemplateArgumentList*>(Data);
682 
683     // Unhandled
684     case Sema::TDK_NonDeducedMismatch:
685     case Sema::TDK_FailedOverloadResolution:
686       break;
687   }
688 
689   return 0;
690 }
691 
692 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
693   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
694   case Sema::TDK_Success:
695   case Sema::TDK_Invalid:
696   case Sema::TDK_InstantiationDepth:
697   case Sema::TDK_Incomplete:
698   case Sema::TDK_TooManyArguments:
699   case Sema::TDK_TooFewArguments:
700   case Sema::TDK_InvalidExplicitArguments:
701   case Sema::TDK_SubstitutionFailure:
702     return 0;
703 
704   case Sema::TDK_Inconsistent:
705   case Sema::TDK_Underqualified:
706     return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
707 
708   // Unhandled
709   case Sema::TDK_NonDeducedMismatch:
710   case Sema::TDK_FailedOverloadResolution:
711     break;
712   }
713 
714   return 0;
715 }
716 
717 const TemplateArgument *
718 OverloadCandidate::DeductionFailureInfo::getSecondArg() {
719   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
720   case Sema::TDK_Success:
721   case Sema::TDK_Invalid:
722   case Sema::TDK_InstantiationDepth:
723   case Sema::TDK_Incomplete:
724   case Sema::TDK_TooManyArguments:
725   case Sema::TDK_TooFewArguments:
726   case Sema::TDK_InvalidExplicitArguments:
727   case Sema::TDK_SubstitutionFailure:
728     return 0;
729 
730   case Sema::TDK_Inconsistent:
731   case Sema::TDK_Underqualified:
732     return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
733 
734   // Unhandled
735   case Sema::TDK_NonDeducedMismatch:
736   case Sema::TDK_FailedOverloadResolution:
737     break;
738   }
739 
740   return 0;
741 }
742 
743 void OverloadCandidateSet::clear() {
744   for (iterator i = begin(), e = end(); i != e; ++i) {
745     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
746       i->Conversions[ii].~ImplicitConversionSequence();
747     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
748       i->DeductionFailure.Destroy();
749   }
750   NumInlineSequences = 0;
751   Candidates.clear();
752   Functions.clear();
753 }
754 
755 namespace {
756   class UnbridgedCastsSet {
757     struct Entry {
758       Expr **Addr;
759       Expr *Saved;
760     };
761     SmallVector<Entry, 2> Entries;
762 
763   public:
764     void save(Sema &S, Expr *&E) {
765       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
766       Entry entry = { &E, E };
767       Entries.push_back(entry);
768       E = S.stripARCUnbridgedCast(E);
769     }
770 
771     void restore() {
772       for (SmallVectorImpl<Entry>::iterator
773              i = Entries.begin(), e = Entries.end(); i != e; ++i)
774         *i->Addr = i->Saved;
775     }
776   };
777 }
778 
779 /// checkPlaceholderForOverload - Do any interesting placeholder-like
780 /// preprocessing on the given expression.
781 ///
782 /// \param unbridgedCasts a collection to which to add unbridged casts;
783 ///   without this, they will be immediately diagnosed as errors
784 ///
785 /// Return true on unrecoverable error.
786 static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
787                                         UnbridgedCastsSet *unbridgedCasts = 0) {
788   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
789     // We can't handle overloaded expressions here because overload
790     // resolution might reasonably tweak them.
791     if (placeholder->getKind() == BuiltinType::Overload) return false;
792 
793     // If the context potentially accepts unbridged ARC casts, strip
794     // the unbridged cast and add it to the collection for later restoration.
795     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
796         unbridgedCasts) {
797       unbridgedCasts->save(S, E);
798       return false;
799     }
800 
801     // Go ahead and check everything else.
802     ExprResult result = S.CheckPlaceholderExpr(E);
803     if (result.isInvalid())
804       return true;
805 
806     E = result.take();
807     return false;
808   }
809 
810   // Nothing to do.
811   return false;
812 }
813 
814 /// checkArgPlaceholdersForOverload - Check a set of call operands for
815 /// placeholders.
816 static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
817                                             unsigned numArgs,
818                                             UnbridgedCastsSet &unbridged) {
819   for (unsigned i = 0; i != numArgs; ++i)
820     if (checkPlaceholderForOverload(S, args[i], &unbridged))
821       return true;
822 
823   return false;
824 }
825 
826 // IsOverload - Determine whether the given New declaration is an
827 // overload of the declarations in Old. This routine returns false if
828 // New and Old cannot be overloaded, e.g., if New has the same
829 // signature as some function in Old (C++ 1.3.10) or if the Old
830 // declarations aren't functions (or function templates) at all. When
831 // it does return false, MatchedDecl will point to the decl that New
832 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
833 // top of the underlying declaration.
834 //
835 // Example: Given the following input:
836 //
837 //   void f(int, float); // #1
838 //   void f(int, int); // #2
839 //   int f(int, int); // #3
840 //
841 // When we process #1, there is no previous declaration of "f",
842 // so IsOverload will not be used.
843 //
844 // When we process #2, Old contains only the FunctionDecl for #1.  By
845 // comparing the parameter types, we see that #1 and #2 are overloaded
846 // (since they have different signatures), so this routine returns
847 // false; MatchedDecl is unchanged.
848 //
849 // When we process #3, Old is an overload set containing #1 and #2. We
850 // compare the signatures of #3 to #1 (they're overloaded, so we do
851 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
852 // identical (return types of functions are not part of the
853 // signature), IsOverload returns false and MatchedDecl will be set to
854 // point to the FunctionDecl for #2.
855 //
856 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
857 // into a class by a using declaration.  The rules for whether to hide
858 // shadow declarations ignore some properties which otherwise figure
859 // into a function template's signature.
860 Sema::OverloadKind
861 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
862                     NamedDecl *&Match, bool NewIsUsingDecl) {
863   for (LookupResult::iterator I = Old.begin(), E = Old.end();
864          I != E; ++I) {
865     NamedDecl *OldD = *I;
866 
867     bool OldIsUsingDecl = false;
868     if (isa<UsingShadowDecl>(OldD)) {
869       OldIsUsingDecl = true;
870 
871       // We can always introduce two using declarations into the same
872       // context, even if they have identical signatures.
873       if (NewIsUsingDecl) continue;
874 
875       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
876     }
877 
878     // If either declaration was introduced by a using declaration,
879     // we'll need to use slightly different rules for matching.
880     // Essentially, these rules are the normal rules, except that
881     // function templates hide function templates with different
882     // return types or template parameter lists.
883     bool UseMemberUsingDeclRules =
884       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
885 
886     if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
887       if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
888         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
889           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
890           continue;
891         }
892 
893         Match = *I;
894         return Ovl_Match;
895       }
896     } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
897       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
898         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
899           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
900           continue;
901         }
902 
903         Match = *I;
904         return Ovl_Match;
905       }
906     } else if (isa<UsingDecl>(OldD)) {
907       // We can overload with these, which can show up when doing
908       // redeclaration checks for UsingDecls.
909       assert(Old.getLookupKind() == LookupUsingDeclName);
910     } else if (isa<TagDecl>(OldD)) {
911       // We can always overload with tags by hiding them.
912     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
913       // Optimistically assume that an unresolved using decl will
914       // overload; if it doesn't, we'll have to diagnose during
915       // template instantiation.
916     } else {
917       // (C++ 13p1):
918       //   Only function declarations can be overloaded; object and type
919       //   declarations cannot be overloaded.
920       Match = *I;
921       return Ovl_NonFunction;
922     }
923   }
924 
925   return Ovl_Overload;
926 }
927 
928 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
929                       bool UseUsingDeclRules) {
930   // If both of the functions are extern "C", then they are not
931   // overloads.
932   if (Old->isExternC() && New->isExternC())
933     return false;
934 
935   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
936   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
937 
938   // C++ [temp.fct]p2:
939   //   A function template can be overloaded with other function templates
940   //   and with normal (non-template) functions.
941   if ((OldTemplate == 0) != (NewTemplate == 0))
942     return true;
943 
944   // Is the function New an overload of the function Old?
945   QualType OldQType = Context.getCanonicalType(Old->getType());
946   QualType NewQType = Context.getCanonicalType(New->getType());
947 
948   // Compare the signatures (C++ 1.3.10) of the two functions to
949   // determine whether they are overloads. If we find any mismatch
950   // in the signature, they are overloads.
951 
952   // If either of these functions is a K&R-style function (no
953   // prototype), then we consider them to have matching signatures.
954   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
955       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
956     return false;
957 
958   const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
959   const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
960 
961   // The signature of a function includes the types of its
962   // parameters (C++ 1.3.10), which includes the presence or absence
963   // of the ellipsis; see C++ DR 357).
964   if (OldQType != NewQType &&
965       (OldType->getNumArgs() != NewType->getNumArgs() ||
966        OldType->isVariadic() != NewType->isVariadic() ||
967        !FunctionArgTypesAreEqual(OldType, NewType)))
968     return true;
969 
970   // C++ [temp.over.link]p4:
971   //   The signature of a function template consists of its function
972   //   signature, its return type and its template parameter list. The names
973   //   of the template parameters are significant only for establishing the
974   //   relationship between the template parameters and the rest of the
975   //   signature.
976   //
977   // We check the return type and template parameter lists for function
978   // templates first; the remaining checks follow.
979   //
980   // However, we don't consider either of these when deciding whether
981   // a member introduced by a shadow declaration is hidden.
982   if (!UseUsingDeclRules && NewTemplate &&
983       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
984                                        OldTemplate->getTemplateParameters(),
985                                        false, TPL_TemplateMatch) ||
986        OldType->getResultType() != NewType->getResultType()))
987     return true;
988 
989   // If the function is a class member, its signature includes the
990   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
991   //
992   // As part of this, also check whether one of the member functions
993   // is static, in which case they are not overloads (C++
994   // 13.1p2). While not part of the definition of the signature,
995   // this check is important to determine whether these functions
996   // can be overloaded.
997   CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
998   CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
999   if (OldMethod && NewMethod &&
1000       !OldMethod->isStatic() && !NewMethod->isStatic() &&
1001       (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
1002        OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
1003     if (!UseUsingDeclRules &&
1004         OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
1005         (OldMethod->getRefQualifier() == RQ_None ||
1006          NewMethod->getRefQualifier() == RQ_None)) {
1007       // C++0x [over.load]p2:
1008       //   - Member function declarations with the same name and the same
1009       //     parameter-type-list as well as member function template
1010       //     declarations with the same name, the same parameter-type-list, and
1011       //     the same template parameter lists cannot be overloaded if any of
1012       //     them, but not all, have a ref-qualifier (8.3.5).
1013       Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1014         << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1015       Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1016     }
1017 
1018     return true;
1019   }
1020 
1021   // The signatures match; this is not an overload.
1022   return false;
1023 }
1024 
1025 /// \brief Checks availability of the function depending on the current
1026 /// function context. Inside an unavailable function, unavailability is ignored.
1027 ///
1028 /// \returns true if \arg FD is unavailable and current context is inside
1029 /// an available function, false otherwise.
1030 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1031   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1032 }
1033 
1034 /// \brief Tries a user-defined conversion from From to ToType.
1035 ///
1036 /// Produces an implicit conversion sequence for when a standard conversion
1037 /// is not an option. See TryImplicitConversion for more information.
1038 static ImplicitConversionSequence
1039 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1040                          bool SuppressUserConversions,
1041                          bool AllowExplicit,
1042                          bool InOverloadResolution,
1043                          bool CStyle,
1044                          bool AllowObjCWritebackConversion) {
1045   ImplicitConversionSequence ICS;
1046 
1047   if (SuppressUserConversions) {
1048     // We're not in the case above, so there is no conversion that
1049     // we can perform.
1050     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1051     return ICS;
1052   }
1053 
1054   // Attempt user-defined conversion.
1055   OverloadCandidateSet Conversions(From->getExprLoc());
1056   OverloadingResult UserDefResult
1057     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1058                               AllowExplicit);
1059 
1060   if (UserDefResult == OR_Success) {
1061     ICS.setUserDefined();
1062     // C++ [over.ics.user]p4:
1063     //   A conversion of an expression of class type to the same class
1064     //   type is given Exact Match rank, and a conversion of an
1065     //   expression of class type to a base class of that type is
1066     //   given Conversion rank, in spite of the fact that a copy
1067     //   constructor (i.e., a user-defined conversion function) is
1068     //   called for those cases.
1069     if (CXXConstructorDecl *Constructor
1070           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1071       QualType FromCanon
1072         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1073       QualType ToCanon
1074         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1075       if (Constructor->isCopyConstructor() &&
1076           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1077         // Turn this into a "standard" conversion sequence, so that it
1078         // gets ranked with standard conversion sequences.
1079         ICS.setStandard();
1080         ICS.Standard.setAsIdentityConversion();
1081         ICS.Standard.setFromType(From->getType());
1082         ICS.Standard.setAllToTypes(ToType);
1083         ICS.Standard.CopyConstructor = Constructor;
1084         if (ToCanon != FromCanon)
1085           ICS.Standard.Second = ICK_Derived_To_Base;
1086       }
1087     }
1088 
1089     // C++ [over.best.ics]p4:
1090     //   However, when considering the argument of a user-defined
1091     //   conversion function that is a candidate by 13.3.1.3 when
1092     //   invoked for the copying of the temporary in the second step
1093     //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1094     //   13.3.1.6 in all cases, only standard conversion sequences and
1095     //   ellipsis conversion sequences are allowed.
1096     if (SuppressUserConversions && ICS.isUserDefined()) {
1097       ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1098     }
1099   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1100     ICS.setAmbiguous();
1101     ICS.Ambiguous.setFromType(From->getType());
1102     ICS.Ambiguous.setToType(ToType);
1103     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1104          Cand != Conversions.end(); ++Cand)
1105       if (Cand->Viable)
1106         ICS.Ambiguous.addConversion(Cand->Function);
1107   } else {
1108     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1109   }
1110 
1111   return ICS;
1112 }
1113 
1114 /// TryImplicitConversion - Attempt to perform an implicit conversion
1115 /// from the given expression (Expr) to the given type (ToType). This
1116 /// function returns an implicit conversion sequence that can be used
1117 /// to perform the initialization. Given
1118 ///
1119 ///   void f(float f);
1120 ///   void g(int i) { f(i); }
1121 ///
1122 /// this routine would produce an implicit conversion sequence to
1123 /// describe the initialization of f from i, which will be a standard
1124 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1125 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1126 //
1127 /// Note that this routine only determines how the conversion can be
1128 /// performed; it does not actually perform the conversion. As such,
1129 /// it will not produce any diagnostics if no conversion is available,
1130 /// but will instead return an implicit conversion sequence of kind
1131 /// "BadConversion".
1132 ///
1133 /// If @p SuppressUserConversions, then user-defined conversions are
1134 /// not permitted.
1135 /// If @p AllowExplicit, then explicit user-defined conversions are
1136 /// permitted.
1137 ///
1138 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1139 /// writeback conversion, which allows __autoreleasing id* parameters to
1140 /// be initialized with __strong id* or __weak id* arguments.
1141 static ImplicitConversionSequence
1142 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1143                       bool SuppressUserConversions,
1144                       bool AllowExplicit,
1145                       bool InOverloadResolution,
1146                       bool CStyle,
1147                       bool AllowObjCWritebackConversion) {
1148   ImplicitConversionSequence ICS;
1149   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1150                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1151     ICS.setStandard();
1152     return ICS;
1153   }
1154 
1155   if (!S.getLangOpts().CPlusPlus) {
1156     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1157     return ICS;
1158   }
1159 
1160   // C++ [over.ics.user]p4:
1161   //   A conversion of an expression of class type to the same class
1162   //   type is given Exact Match rank, and a conversion of an
1163   //   expression of class type to a base class of that type is
1164   //   given Conversion rank, in spite of the fact that a copy/move
1165   //   constructor (i.e., a user-defined conversion function) is
1166   //   called for those cases.
1167   QualType FromType = From->getType();
1168   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1169       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1170        S.IsDerivedFrom(FromType, ToType))) {
1171     ICS.setStandard();
1172     ICS.Standard.setAsIdentityConversion();
1173     ICS.Standard.setFromType(FromType);
1174     ICS.Standard.setAllToTypes(ToType);
1175 
1176     // We don't actually check at this point whether there is a valid
1177     // copy/move constructor, since overloading just assumes that it
1178     // exists. When we actually perform initialization, we'll find the
1179     // appropriate constructor to copy the returned object, if needed.
1180     ICS.Standard.CopyConstructor = 0;
1181 
1182     // Determine whether this is considered a derived-to-base conversion.
1183     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1184       ICS.Standard.Second = ICK_Derived_To_Base;
1185 
1186     return ICS;
1187   }
1188 
1189   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1190                                   AllowExplicit, InOverloadResolution, CStyle,
1191                                   AllowObjCWritebackConversion);
1192 }
1193 
1194 ImplicitConversionSequence
1195 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1196                             bool SuppressUserConversions,
1197                             bool AllowExplicit,
1198                             bool InOverloadResolution,
1199                             bool CStyle,
1200                             bool AllowObjCWritebackConversion) {
1201   return clang::TryImplicitConversion(*this, From, ToType,
1202                                       SuppressUserConversions, AllowExplicit,
1203                                       InOverloadResolution, CStyle,
1204                                       AllowObjCWritebackConversion);
1205 }
1206 
1207 /// PerformImplicitConversion - Perform an implicit conversion of the
1208 /// expression From to the type ToType. Returns the
1209 /// converted expression. Flavor is the kind of conversion we're
1210 /// performing, used in the error message. If @p AllowExplicit,
1211 /// explicit user-defined conversions are permitted.
1212 ExprResult
1213 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1214                                 AssignmentAction Action, bool AllowExplicit) {
1215   ImplicitConversionSequence ICS;
1216   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1217 }
1218 
1219 ExprResult
1220 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1221                                 AssignmentAction Action, bool AllowExplicit,
1222                                 ImplicitConversionSequence& ICS) {
1223   if (checkPlaceholderForOverload(*this, From))
1224     return ExprError();
1225 
1226   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1227   bool AllowObjCWritebackConversion
1228     = getLangOpts().ObjCAutoRefCount &&
1229       (Action == AA_Passing || Action == AA_Sending);
1230 
1231   ICS = clang::TryImplicitConversion(*this, From, ToType,
1232                                      /*SuppressUserConversions=*/false,
1233                                      AllowExplicit,
1234                                      /*InOverloadResolution=*/false,
1235                                      /*CStyle=*/false,
1236                                      AllowObjCWritebackConversion);
1237   return PerformImplicitConversion(From, ToType, ICS, Action);
1238 }
1239 
1240 /// \brief Determine whether the conversion from FromType to ToType is a valid
1241 /// conversion that strips "noreturn" off the nested function type.
1242 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1243                                 QualType &ResultTy) {
1244   if (Context.hasSameUnqualifiedType(FromType, ToType))
1245     return false;
1246 
1247   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1248   // where F adds one of the following at most once:
1249   //   - a pointer
1250   //   - a member pointer
1251   //   - a block pointer
1252   CanQualType CanTo = Context.getCanonicalType(ToType);
1253   CanQualType CanFrom = Context.getCanonicalType(FromType);
1254   Type::TypeClass TyClass = CanTo->getTypeClass();
1255   if (TyClass != CanFrom->getTypeClass()) return false;
1256   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1257     if (TyClass == Type::Pointer) {
1258       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1259       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1260     } else if (TyClass == Type::BlockPointer) {
1261       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1262       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1263     } else if (TyClass == Type::MemberPointer) {
1264       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1265       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1266     } else {
1267       return false;
1268     }
1269 
1270     TyClass = CanTo->getTypeClass();
1271     if (TyClass != CanFrom->getTypeClass()) return false;
1272     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1273       return false;
1274   }
1275 
1276   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1277   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1278   if (!EInfo.getNoReturn()) return false;
1279 
1280   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1281   assert(QualType(FromFn, 0).isCanonical());
1282   if (QualType(FromFn, 0) != CanTo) return false;
1283 
1284   ResultTy = ToType;
1285   return true;
1286 }
1287 
1288 /// \brief Determine whether the conversion from FromType to ToType is a valid
1289 /// vector conversion.
1290 ///
1291 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1292 /// conversion.
1293 static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1294                                QualType ToType, ImplicitConversionKind &ICK) {
1295   // We need at least one of these types to be a vector type to have a vector
1296   // conversion.
1297   if (!ToType->isVectorType() && !FromType->isVectorType())
1298     return false;
1299 
1300   // Identical types require no conversions.
1301   if (Context.hasSameUnqualifiedType(FromType, ToType))
1302     return false;
1303 
1304   // There are no conversions between extended vector types, only identity.
1305   if (ToType->isExtVectorType()) {
1306     // There are no conversions between extended vector types other than the
1307     // identity conversion.
1308     if (FromType->isExtVectorType())
1309       return false;
1310 
1311     // Vector splat from any arithmetic type to a vector.
1312     if (FromType->isArithmeticType()) {
1313       ICK = ICK_Vector_Splat;
1314       return true;
1315     }
1316   }
1317 
1318   // We can perform the conversion between vector types in the following cases:
1319   // 1)vector types are equivalent AltiVec and GCC vector types
1320   // 2)lax vector conversions are permitted and the vector types are of the
1321   //   same size
1322   if (ToType->isVectorType() && FromType->isVectorType()) {
1323     if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1324         (Context.getLangOpts().LaxVectorConversions &&
1325          (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1326       ICK = ICK_Vector_Conversion;
1327       return true;
1328     }
1329   }
1330 
1331   return false;
1332 }
1333 
1334 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1335                                 bool InOverloadResolution,
1336                                 StandardConversionSequence &SCS,
1337                                 bool CStyle);
1338 
1339 /// IsStandardConversion - Determines whether there is a standard
1340 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1341 /// expression From to the type ToType. Standard conversion sequences
1342 /// only consider non-class types; for conversions that involve class
1343 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1344 /// contain the standard conversion sequence required to perform this
1345 /// conversion and this routine will return true. Otherwise, this
1346 /// routine will return false and the value of SCS is unspecified.
1347 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1348                                  bool InOverloadResolution,
1349                                  StandardConversionSequence &SCS,
1350                                  bool CStyle,
1351                                  bool AllowObjCWritebackConversion) {
1352   QualType FromType = From->getType();
1353 
1354   // Standard conversions (C++ [conv])
1355   SCS.setAsIdentityConversion();
1356   SCS.DeprecatedStringLiteralToCharPtr = false;
1357   SCS.IncompatibleObjC = false;
1358   SCS.setFromType(FromType);
1359   SCS.CopyConstructor = 0;
1360 
1361   // There are no standard conversions for class types in C++, so
1362   // abort early. When overloading in C, however, we do permit
1363   if (FromType->isRecordType() || ToType->isRecordType()) {
1364     if (S.getLangOpts().CPlusPlus)
1365       return false;
1366 
1367     // When we're overloading in C, we allow, as standard conversions,
1368   }
1369 
1370   // The first conversion can be an lvalue-to-rvalue conversion,
1371   // array-to-pointer conversion, or function-to-pointer conversion
1372   // (C++ 4p1).
1373 
1374   if (FromType == S.Context.OverloadTy) {
1375     DeclAccessPair AccessPair;
1376     if (FunctionDecl *Fn
1377           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1378                                                  AccessPair)) {
1379       // We were able to resolve the address of the overloaded function,
1380       // so we can convert to the type of that function.
1381       FromType = Fn->getType();
1382 
1383       // we can sometimes resolve &foo<int> regardless of ToType, so check
1384       // if the type matches (identity) or we are converting to bool
1385       if (!S.Context.hasSameUnqualifiedType(
1386                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1387         QualType resultTy;
1388         // if the function type matches except for [[noreturn]], it's ok
1389         if (!S.IsNoReturnConversion(FromType,
1390               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1391           // otherwise, only a boolean conversion is standard
1392           if (!ToType->isBooleanType())
1393             return false;
1394       }
1395 
1396       // Check if the "from" expression is taking the address of an overloaded
1397       // function and recompute the FromType accordingly. Take advantage of the
1398       // fact that non-static member functions *must* have such an address-of
1399       // expression.
1400       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1401       if (Method && !Method->isStatic()) {
1402         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1403                "Non-unary operator on non-static member address");
1404         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1405                == UO_AddrOf &&
1406                "Non-address-of operator on non-static member address");
1407         const Type *ClassType
1408           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1409         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1410       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1411         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1412                UO_AddrOf &&
1413                "Non-address-of operator for overloaded function expression");
1414         FromType = S.Context.getPointerType(FromType);
1415       }
1416 
1417       // Check that we've computed the proper type after overload resolution.
1418       assert(S.Context.hasSameType(
1419         FromType,
1420         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1421     } else {
1422       return false;
1423     }
1424   }
1425   // Lvalue-to-rvalue conversion (C++11 4.1):
1426   //   A glvalue (3.10) of a non-function, non-array type T can
1427   //   be converted to a prvalue.
1428   bool argIsLValue = From->isGLValue();
1429   if (argIsLValue &&
1430       !FromType->isFunctionType() && !FromType->isArrayType() &&
1431       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1432     SCS.First = ICK_Lvalue_To_Rvalue;
1433 
1434     // C11 6.3.2.1p2:
1435     //   ... if the lvalue has atomic type, the value has the non-atomic version
1436     //   of the type of the lvalue ...
1437     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1438       FromType = Atomic->getValueType();
1439 
1440     // If T is a non-class type, the type of the rvalue is the
1441     // cv-unqualified version of T. Otherwise, the type of the rvalue
1442     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1443     // just strip the qualifiers because they don't matter.
1444     FromType = FromType.getUnqualifiedType();
1445   } else if (FromType->isArrayType()) {
1446     // Array-to-pointer conversion (C++ 4.2)
1447     SCS.First = ICK_Array_To_Pointer;
1448 
1449     // An lvalue or rvalue of type "array of N T" or "array of unknown
1450     // bound of T" can be converted to an rvalue of type "pointer to
1451     // T" (C++ 4.2p1).
1452     FromType = S.Context.getArrayDecayedType(FromType);
1453 
1454     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1455       // This conversion is deprecated. (C++ D.4).
1456       SCS.DeprecatedStringLiteralToCharPtr = true;
1457 
1458       // For the purpose of ranking in overload resolution
1459       // (13.3.3.1.1), this conversion is considered an
1460       // array-to-pointer conversion followed by a qualification
1461       // conversion (4.4). (C++ 4.2p2)
1462       SCS.Second = ICK_Identity;
1463       SCS.Third = ICK_Qualification;
1464       SCS.QualificationIncludesObjCLifetime = false;
1465       SCS.setAllToTypes(FromType);
1466       return true;
1467     }
1468   } else if (FromType->isFunctionType() && argIsLValue) {
1469     // Function-to-pointer conversion (C++ 4.3).
1470     SCS.First = ICK_Function_To_Pointer;
1471 
1472     // An lvalue of function type T can be converted to an rvalue of
1473     // type "pointer to T." The result is a pointer to the
1474     // function. (C++ 4.3p1).
1475     FromType = S.Context.getPointerType(FromType);
1476   } else {
1477     // We don't require any conversions for the first step.
1478     SCS.First = ICK_Identity;
1479   }
1480   SCS.setToType(0, FromType);
1481 
1482   // The second conversion can be an integral promotion, floating
1483   // point promotion, integral conversion, floating point conversion,
1484   // floating-integral conversion, pointer conversion,
1485   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1486   // For overloading in C, this can also be a "compatible-type"
1487   // conversion.
1488   bool IncompatibleObjC = false;
1489   ImplicitConversionKind SecondICK = ICK_Identity;
1490   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1491     // The unqualified versions of the types are the same: there's no
1492     // conversion to do.
1493     SCS.Second = ICK_Identity;
1494   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1495     // Integral promotion (C++ 4.5).
1496     SCS.Second = ICK_Integral_Promotion;
1497     FromType = ToType.getUnqualifiedType();
1498   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1499     // Floating point promotion (C++ 4.6).
1500     SCS.Second = ICK_Floating_Promotion;
1501     FromType = ToType.getUnqualifiedType();
1502   } else if (S.IsComplexPromotion(FromType, ToType)) {
1503     // Complex promotion (Clang extension)
1504     SCS.Second = ICK_Complex_Promotion;
1505     FromType = ToType.getUnqualifiedType();
1506   } else if (ToType->isBooleanType() &&
1507              (FromType->isArithmeticType() ||
1508               FromType->isAnyPointerType() ||
1509               FromType->isBlockPointerType() ||
1510               FromType->isMemberPointerType() ||
1511               FromType->isNullPtrType())) {
1512     // Boolean conversions (C++ 4.12).
1513     SCS.Second = ICK_Boolean_Conversion;
1514     FromType = S.Context.BoolTy;
1515   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1516              ToType->isIntegralType(S.Context)) {
1517     // Integral conversions (C++ 4.7).
1518     SCS.Second = ICK_Integral_Conversion;
1519     FromType = ToType.getUnqualifiedType();
1520   } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1521     // Complex conversions (C99 6.3.1.6)
1522     SCS.Second = ICK_Complex_Conversion;
1523     FromType = ToType.getUnqualifiedType();
1524   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1525              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1526     // Complex-real conversions (C99 6.3.1.7)
1527     SCS.Second = ICK_Complex_Real;
1528     FromType = ToType.getUnqualifiedType();
1529   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1530     // Floating point conversions (C++ 4.8).
1531     SCS.Second = ICK_Floating_Conversion;
1532     FromType = ToType.getUnqualifiedType();
1533   } else if ((FromType->isRealFloatingType() &&
1534               ToType->isIntegralType(S.Context)) ||
1535              (FromType->isIntegralOrUnscopedEnumerationType() &&
1536               ToType->isRealFloatingType())) {
1537     // Floating-integral conversions (C++ 4.9).
1538     SCS.Second = ICK_Floating_Integral;
1539     FromType = ToType.getUnqualifiedType();
1540   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1541     SCS.Second = ICK_Block_Pointer_Conversion;
1542   } else if (AllowObjCWritebackConversion &&
1543              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1544     SCS.Second = ICK_Writeback_Conversion;
1545   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1546                                    FromType, IncompatibleObjC)) {
1547     // Pointer conversions (C++ 4.10).
1548     SCS.Second = ICK_Pointer_Conversion;
1549     SCS.IncompatibleObjC = IncompatibleObjC;
1550     FromType = FromType.getUnqualifiedType();
1551   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1552                                          InOverloadResolution, FromType)) {
1553     // Pointer to member conversions (4.11).
1554     SCS.Second = ICK_Pointer_Member;
1555   } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1556     SCS.Second = SecondICK;
1557     FromType = ToType.getUnqualifiedType();
1558   } else if (!S.getLangOpts().CPlusPlus &&
1559              S.Context.typesAreCompatible(ToType, FromType)) {
1560     // Compatible conversions (Clang extension for C function overloading)
1561     SCS.Second = ICK_Compatible_Conversion;
1562     FromType = ToType.getUnqualifiedType();
1563   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1564     // Treat a conversion that strips "noreturn" as an identity conversion.
1565     SCS.Second = ICK_NoReturn_Adjustment;
1566   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1567                                              InOverloadResolution,
1568                                              SCS, CStyle)) {
1569     SCS.Second = ICK_TransparentUnionConversion;
1570     FromType = ToType;
1571   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1572                                  CStyle)) {
1573     // tryAtomicConversion has updated the standard conversion sequence
1574     // appropriately.
1575     return true;
1576   } else {
1577     // No second conversion required.
1578     SCS.Second = ICK_Identity;
1579   }
1580   SCS.setToType(1, FromType);
1581 
1582   QualType CanonFrom;
1583   QualType CanonTo;
1584   // The third conversion can be a qualification conversion (C++ 4p1).
1585   bool ObjCLifetimeConversion;
1586   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1587                                   ObjCLifetimeConversion)) {
1588     SCS.Third = ICK_Qualification;
1589     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1590     FromType = ToType;
1591     CanonFrom = S.Context.getCanonicalType(FromType);
1592     CanonTo = S.Context.getCanonicalType(ToType);
1593   } else {
1594     // No conversion required
1595     SCS.Third = ICK_Identity;
1596 
1597     // C++ [over.best.ics]p6:
1598     //   [...] Any difference in top-level cv-qualification is
1599     //   subsumed by the initialization itself and does not constitute
1600     //   a conversion. [...]
1601     CanonFrom = S.Context.getCanonicalType(FromType);
1602     CanonTo = S.Context.getCanonicalType(ToType);
1603     if (CanonFrom.getLocalUnqualifiedType()
1604                                        == CanonTo.getLocalUnqualifiedType() &&
1605         (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1606          || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1607          || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
1608       FromType = ToType;
1609       CanonFrom = CanonTo;
1610     }
1611   }
1612   SCS.setToType(2, FromType);
1613 
1614   // If we have not converted the argument type to the parameter type,
1615   // this is a bad conversion sequence.
1616   if (CanonFrom != CanonTo)
1617     return false;
1618 
1619   return true;
1620 }
1621 
1622 static bool
1623 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1624                                      QualType &ToType,
1625                                      bool InOverloadResolution,
1626                                      StandardConversionSequence &SCS,
1627                                      bool CStyle) {
1628 
1629   const RecordType *UT = ToType->getAsUnionType();
1630   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1631     return false;
1632   // The field to initialize within the transparent union.
1633   RecordDecl *UD = UT->getDecl();
1634   // It's compatible if the expression matches any of the fields.
1635   for (RecordDecl::field_iterator it = UD->field_begin(),
1636        itend = UD->field_end();
1637        it != itend; ++it) {
1638     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1639                              CStyle, /*ObjCWritebackConversion=*/false)) {
1640       ToType = it->getType();
1641       return true;
1642     }
1643   }
1644   return false;
1645 }
1646 
1647 /// IsIntegralPromotion - Determines whether the conversion from the
1648 /// expression From (whose potentially-adjusted type is FromType) to
1649 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1650 /// sets PromotedType to the promoted type.
1651 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1652   const BuiltinType *To = ToType->getAs<BuiltinType>();
1653   // All integers are built-in.
1654   if (!To) {
1655     return false;
1656   }
1657 
1658   // An rvalue of type char, signed char, unsigned char, short int, or
1659   // unsigned short int can be converted to an rvalue of type int if
1660   // int can represent all the values of the source type; otherwise,
1661   // the source rvalue can be converted to an rvalue of type unsigned
1662   // int (C++ 4.5p1).
1663   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1664       !FromType->isEnumeralType()) {
1665     if (// We can promote any signed, promotable integer type to an int
1666         (FromType->isSignedIntegerType() ||
1667          // We can promote any unsigned integer type whose size is
1668          // less than int to an int.
1669          (!FromType->isSignedIntegerType() &&
1670           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1671       return To->getKind() == BuiltinType::Int;
1672     }
1673 
1674     return To->getKind() == BuiltinType::UInt;
1675   }
1676 
1677   // C++11 [conv.prom]p3:
1678   //   A prvalue of an unscoped enumeration type whose underlying type is not
1679   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1680   //   following types that can represent all the values of the enumeration
1681   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1682   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1683   //   long long int. If none of the types in that list can represent all the
1684   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1685   //   type can be converted to an rvalue a prvalue of the extended integer type
1686   //   with lowest integer conversion rank (4.13) greater than the rank of long
1687   //   long in which all the values of the enumeration can be represented. If
1688   //   there are two such extended types, the signed one is chosen.
1689   // C++11 [conv.prom]p4:
1690   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1691   //   can be converted to a prvalue of its underlying type. Moreover, if
1692   //   integral promotion can be applied to its underlying type, a prvalue of an
1693   //   unscoped enumeration type whose underlying type is fixed can also be
1694   //   converted to a prvalue of the promoted underlying type.
1695   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1696     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1697     // provided for a scoped enumeration.
1698     if (FromEnumType->getDecl()->isScoped())
1699       return false;
1700 
1701     // We can perform an integral promotion to the underlying type of the enum,
1702     // even if that's not the promoted type.
1703     if (FromEnumType->getDecl()->isFixed()) {
1704       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1705       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1706              IsIntegralPromotion(From, Underlying, ToType);
1707     }
1708 
1709     // We have already pre-calculated the promotion type, so this is trivial.
1710     if (ToType->isIntegerType() &&
1711         !RequireCompleteType(From->getLocStart(), FromType, 0))
1712       return Context.hasSameUnqualifiedType(ToType,
1713                                 FromEnumType->getDecl()->getPromotionType());
1714   }
1715 
1716   // C++0x [conv.prom]p2:
1717   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1718   //   to an rvalue a prvalue of the first of the following types that can
1719   //   represent all the values of its underlying type: int, unsigned int,
1720   //   long int, unsigned long int, long long int, or unsigned long long int.
1721   //   If none of the types in that list can represent all the values of its
1722   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1723   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1724   //   type.
1725   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1726       ToType->isIntegerType()) {
1727     // Determine whether the type we're converting from is signed or
1728     // unsigned.
1729     bool FromIsSigned = FromType->isSignedIntegerType();
1730     uint64_t FromSize = Context.getTypeSize(FromType);
1731 
1732     // The types we'll try to promote to, in the appropriate
1733     // order. Try each of these types.
1734     QualType PromoteTypes[6] = {
1735       Context.IntTy, Context.UnsignedIntTy,
1736       Context.LongTy, Context.UnsignedLongTy ,
1737       Context.LongLongTy, Context.UnsignedLongLongTy
1738     };
1739     for (int Idx = 0; Idx < 6; ++Idx) {
1740       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1741       if (FromSize < ToSize ||
1742           (FromSize == ToSize &&
1743            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1744         // We found the type that we can promote to. If this is the
1745         // type we wanted, we have a promotion. Otherwise, no
1746         // promotion.
1747         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1748       }
1749     }
1750   }
1751 
1752   // An rvalue for an integral bit-field (9.6) can be converted to an
1753   // rvalue of type int if int can represent all the values of the
1754   // bit-field; otherwise, it can be converted to unsigned int if
1755   // unsigned int can represent all the values of the bit-field. If
1756   // the bit-field is larger yet, no integral promotion applies to
1757   // it. If the bit-field has an enumerated type, it is treated as any
1758   // other value of that type for promotion purposes (C++ 4.5p3).
1759   // FIXME: We should delay checking of bit-fields until we actually perform the
1760   // conversion.
1761   using llvm::APSInt;
1762   if (From)
1763     if (FieldDecl *MemberDecl = From->getBitField()) {
1764       APSInt BitWidth;
1765       if (FromType->isIntegralType(Context) &&
1766           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1767         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1768         ToSize = Context.getTypeSize(ToType);
1769 
1770         // Are we promoting to an int from a bitfield that fits in an int?
1771         if (BitWidth < ToSize ||
1772             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1773           return To->getKind() == BuiltinType::Int;
1774         }
1775 
1776         // Are we promoting to an unsigned int from an unsigned bitfield
1777         // that fits into an unsigned int?
1778         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1779           return To->getKind() == BuiltinType::UInt;
1780         }
1781 
1782         return false;
1783       }
1784     }
1785 
1786   // An rvalue of type bool can be converted to an rvalue of type int,
1787   // with false becoming zero and true becoming one (C++ 4.5p4).
1788   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1789     return true;
1790   }
1791 
1792   return false;
1793 }
1794 
1795 /// IsFloatingPointPromotion - Determines whether the conversion from
1796 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1797 /// returns true and sets PromotedType to the promoted type.
1798 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1799   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1800     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1801       /// An rvalue of type float can be converted to an rvalue of type
1802       /// double. (C++ 4.6p1).
1803       if (FromBuiltin->getKind() == BuiltinType::Float &&
1804           ToBuiltin->getKind() == BuiltinType::Double)
1805         return true;
1806 
1807       // C99 6.3.1.5p1:
1808       //   When a float is promoted to double or long double, or a
1809       //   double is promoted to long double [...].
1810       if (!getLangOpts().CPlusPlus &&
1811           (FromBuiltin->getKind() == BuiltinType::Float ||
1812            FromBuiltin->getKind() == BuiltinType::Double) &&
1813           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1814         return true;
1815 
1816       // Half can be promoted to float.
1817       if (FromBuiltin->getKind() == BuiltinType::Half &&
1818           ToBuiltin->getKind() == BuiltinType::Float)
1819         return true;
1820     }
1821 
1822   return false;
1823 }
1824 
1825 /// \brief Determine if a conversion is a complex promotion.
1826 ///
1827 /// A complex promotion is defined as a complex -> complex conversion
1828 /// where the conversion between the underlying real types is a
1829 /// floating-point or integral promotion.
1830 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1831   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1832   if (!FromComplex)
1833     return false;
1834 
1835   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1836   if (!ToComplex)
1837     return false;
1838 
1839   return IsFloatingPointPromotion(FromComplex->getElementType(),
1840                                   ToComplex->getElementType()) ||
1841     IsIntegralPromotion(0, FromComplex->getElementType(),
1842                         ToComplex->getElementType());
1843 }
1844 
1845 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1846 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1847 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1848 /// if non-empty, will be a pointer to ToType that may or may not have
1849 /// the right set of qualifiers on its pointee.
1850 ///
1851 static QualType
1852 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1853                                    QualType ToPointee, QualType ToType,
1854                                    ASTContext &Context,
1855                                    bool StripObjCLifetime = false) {
1856   assert((FromPtr->getTypeClass() == Type::Pointer ||
1857           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1858          "Invalid similarly-qualified pointer type");
1859 
1860   /// Conversions to 'id' subsume cv-qualifier conversions.
1861   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1862     return ToType.getUnqualifiedType();
1863 
1864   QualType CanonFromPointee
1865     = Context.getCanonicalType(FromPtr->getPointeeType());
1866   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1867   Qualifiers Quals = CanonFromPointee.getQualifiers();
1868 
1869   if (StripObjCLifetime)
1870     Quals.removeObjCLifetime();
1871 
1872   // Exact qualifier match -> return the pointer type we're converting to.
1873   if (CanonToPointee.getLocalQualifiers() == Quals) {
1874     // ToType is exactly what we need. Return it.
1875     if (!ToType.isNull())
1876       return ToType.getUnqualifiedType();
1877 
1878     // Build a pointer to ToPointee. It has the right qualifiers
1879     // already.
1880     if (isa<ObjCObjectPointerType>(ToType))
1881       return Context.getObjCObjectPointerType(ToPointee);
1882     return Context.getPointerType(ToPointee);
1883   }
1884 
1885   // Just build a canonical type that has the right qualifiers.
1886   QualType QualifiedCanonToPointee
1887     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1888 
1889   if (isa<ObjCObjectPointerType>(ToType))
1890     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1891   return Context.getPointerType(QualifiedCanonToPointee);
1892 }
1893 
1894 static bool isNullPointerConstantForConversion(Expr *Expr,
1895                                                bool InOverloadResolution,
1896                                                ASTContext &Context) {
1897   // Handle value-dependent integral null pointer constants correctly.
1898   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1899   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1900       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1901     return !InOverloadResolution;
1902 
1903   return Expr->isNullPointerConstant(Context,
1904                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1905                                         : Expr::NPC_ValueDependentIsNull);
1906 }
1907 
1908 /// IsPointerConversion - Determines whether the conversion of the
1909 /// expression From, which has the (possibly adjusted) type FromType,
1910 /// can be converted to the type ToType via a pointer conversion (C++
1911 /// 4.10). If so, returns true and places the converted type (that
1912 /// might differ from ToType in its cv-qualifiers at some level) into
1913 /// ConvertedType.
1914 ///
1915 /// This routine also supports conversions to and from block pointers
1916 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1917 /// pointers to interfaces. FIXME: Once we've determined the
1918 /// appropriate overloading rules for Objective-C, we may want to
1919 /// split the Objective-C checks into a different routine; however,
1920 /// GCC seems to consider all of these conversions to be pointer
1921 /// conversions, so for now they live here. IncompatibleObjC will be
1922 /// set if the conversion is an allowed Objective-C conversion that
1923 /// should result in a warning.
1924 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1925                                bool InOverloadResolution,
1926                                QualType& ConvertedType,
1927                                bool &IncompatibleObjC) {
1928   IncompatibleObjC = false;
1929   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1930                               IncompatibleObjC))
1931     return true;
1932 
1933   // Conversion from a null pointer constant to any Objective-C pointer type.
1934   if (ToType->isObjCObjectPointerType() &&
1935       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1936     ConvertedType = ToType;
1937     return true;
1938   }
1939 
1940   // Blocks: Block pointers can be converted to void*.
1941   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1942       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1943     ConvertedType = ToType;
1944     return true;
1945   }
1946   // Blocks: A null pointer constant can be converted to a block
1947   // pointer type.
1948   if (ToType->isBlockPointerType() &&
1949       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1950     ConvertedType = ToType;
1951     return true;
1952   }
1953 
1954   // If the left-hand-side is nullptr_t, the right side can be a null
1955   // pointer constant.
1956   if (ToType->isNullPtrType() &&
1957       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1958     ConvertedType = ToType;
1959     return true;
1960   }
1961 
1962   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1963   if (!ToTypePtr)
1964     return false;
1965 
1966   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1967   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1968     ConvertedType = ToType;
1969     return true;
1970   }
1971 
1972   // Beyond this point, both types need to be pointers
1973   // , including objective-c pointers.
1974   QualType ToPointeeType = ToTypePtr->getPointeeType();
1975   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1976       !getLangOpts().ObjCAutoRefCount) {
1977     ConvertedType = BuildSimilarlyQualifiedPointerType(
1978                                       FromType->getAs<ObjCObjectPointerType>(),
1979                                                        ToPointeeType,
1980                                                        ToType, Context);
1981     return true;
1982   }
1983   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1984   if (!FromTypePtr)
1985     return false;
1986 
1987   QualType FromPointeeType = FromTypePtr->getPointeeType();
1988 
1989   // If the unqualified pointee types are the same, this can't be a
1990   // pointer conversion, so don't do all of the work below.
1991   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1992     return false;
1993 
1994   // An rvalue of type "pointer to cv T," where T is an object type,
1995   // can be converted to an rvalue of type "pointer to cv void" (C++
1996   // 4.10p2).
1997   if (FromPointeeType->isIncompleteOrObjectType() &&
1998       ToPointeeType->isVoidType()) {
1999     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2000                                                        ToPointeeType,
2001                                                        ToType, Context,
2002                                                    /*StripObjCLifetime=*/true);
2003     return true;
2004   }
2005 
2006   // MSVC allows implicit function to void* type conversion.
2007   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2008       ToPointeeType->isVoidType()) {
2009     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2010                                                        ToPointeeType,
2011                                                        ToType, Context);
2012     return true;
2013   }
2014 
2015   // When we're overloading in C, we allow a special kind of pointer
2016   // conversion for compatible-but-not-identical pointee types.
2017   if (!getLangOpts().CPlusPlus &&
2018       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2019     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2020                                                        ToPointeeType,
2021                                                        ToType, Context);
2022     return true;
2023   }
2024 
2025   // C++ [conv.ptr]p3:
2026   //
2027   //   An rvalue of type "pointer to cv D," where D is a class type,
2028   //   can be converted to an rvalue of type "pointer to cv B," where
2029   //   B is a base class (clause 10) of D. If B is an inaccessible
2030   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2031   //   necessitates this conversion is ill-formed. The result of the
2032   //   conversion is a pointer to the base class sub-object of the
2033   //   derived class object. The null pointer value is converted to
2034   //   the null pointer value of the destination type.
2035   //
2036   // Note that we do not check for ambiguity or inaccessibility
2037   // here. That is handled by CheckPointerConversion.
2038   if (getLangOpts().CPlusPlus &&
2039       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2040       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2041       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2042       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2043     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2044                                                        ToPointeeType,
2045                                                        ToType, Context);
2046     return true;
2047   }
2048 
2049   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2050       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2051     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2052                                                        ToPointeeType,
2053                                                        ToType, Context);
2054     return true;
2055   }
2056 
2057   return false;
2058 }
2059 
2060 /// \brief Adopt the given qualifiers for the given type.
2061 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2062   Qualifiers TQs = T.getQualifiers();
2063 
2064   // Check whether qualifiers already match.
2065   if (TQs == Qs)
2066     return T;
2067 
2068   if (Qs.compatiblyIncludes(TQs))
2069     return Context.getQualifiedType(T, Qs);
2070 
2071   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2072 }
2073 
2074 /// isObjCPointerConversion - Determines whether this is an
2075 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2076 /// with the same arguments and return values.
2077 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2078                                    QualType& ConvertedType,
2079                                    bool &IncompatibleObjC) {
2080   if (!getLangOpts().ObjC1)
2081     return false;
2082 
2083   // The set of qualifiers on the type we're converting from.
2084   Qualifiers FromQualifiers = FromType.getQualifiers();
2085 
2086   // First, we handle all conversions on ObjC object pointer types.
2087   const ObjCObjectPointerType* ToObjCPtr =
2088     ToType->getAs<ObjCObjectPointerType>();
2089   const ObjCObjectPointerType *FromObjCPtr =
2090     FromType->getAs<ObjCObjectPointerType>();
2091 
2092   if (ToObjCPtr && FromObjCPtr) {
2093     // If the pointee types are the same (ignoring qualifications),
2094     // then this is not a pointer conversion.
2095     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2096                                        FromObjCPtr->getPointeeType()))
2097       return false;
2098 
2099     // Check for compatible
2100     // Objective C++: We're able to convert between "id" or "Class" and a
2101     // pointer to any interface (in both directions).
2102     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2103       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2104       return true;
2105     }
2106     // Conversions with Objective-C's id<...>.
2107     if ((FromObjCPtr->isObjCQualifiedIdType() ||
2108          ToObjCPtr->isObjCQualifiedIdType()) &&
2109         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2110                                                   /*compare=*/false)) {
2111       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2112       return true;
2113     }
2114     // Objective C++: We're able to convert from a pointer to an
2115     // interface to a pointer to a different interface.
2116     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2117       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2118       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2119       if (getLangOpts().CPlusPlus && LHS && RHS &&
2120           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2121                                                 FromObjCPtr->getPointeeType()))
2122         return false;
2123       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2124                                                    ToObjCPtr->getPointeeType(),
2125                                                          ToType, Context);
2126       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2127       return true;
2128     }
2129 
2130     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2131       // Okay: this is some kind of implicit downcast of Objective-C
2132       // interfaces, which is permitted. However, we're going to
2133       // complain about it.
2134       IncompatibleObjC = true;
2135       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2136                                                    ToObjCPtr->getPointeeType(),
2137                                                          ToType, Context);
2138       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2139       return true;
2140     }
2141   }
2142   // Beyond this point, both types need to be C pointers or block pointers.
2143   QualType ToPointeeType;
2144   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2145     ToPointeeType = ToCPtr->getPointeeType();
2146   else if (const BlockPointerType *ToBlockPtr =
2147             ToType->getAs<BlockPointerType>()) {
2148     // Objective C++: We're able to convert from a pointer to any object
2149     // to a block pointer type.
2150     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2151       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2152       return true;
2153     }
2154     ToPointeeType = ToBlockPtr->getPointeeType();
2155   }
2156   else if (FromType->getAs<BlockPointerType>() &&
2157            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2158     // Objective C++: We're able to convert from a block pointer type to a
2159     // pointer to any object.
2160     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2161     return true;
2162   }
2163   else
2164     return false;
2165 
2166   QualType FromPointeeType;
2167   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2168     FromPointeeType = FromCPtr->getPointeeType();
2169   else if (const BlockPointerType *FromBlockPtr =
2170            FromType->getAs<BlockPointerType>())
2171     FromPointeeType = FromBlockPtr->getPointeeType();
2172   else
2173     return false;
2174 
2175   // If we have pointers to pointers, recursively check whether this
2176   // is an Objective-C conversion.
2177   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2178       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2179                               IncompatibleObjC)) {
2180     // We always complain about this conversion.
2181     IncompatibleObjC = true;
2182     ConvertedType = Context.getPointerType(ConvertedType);
2183     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2184     return true;
2185   }
2186   // Allow conversion of pointee being objective-c pointer to another one;
2187   // as in I* to id.
2188   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2189       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2190       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2191                               IncompatibleObjC)) {
2192 
2193     ConvertedType = Context.getPointerType(ConvertedType);
2194     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2195     return true;
2196   }
2197 
2198   // If we have pointers to functions or blocks, check whether the only
2199   // differences in the argument and result types are in Objective-C
2200   // pointer conversions. If so, we permit the conversion (but
2201   // complain about it).
2202   const FunctionProtoType *FromFunctionType
2203     = FromPointeeType->getAs<FunctionProtoType>();
2204   const FunctionProtoType *ToFunctionType
2205     = ToPointeeType->getAs<FunctionProtoType>();
2206   if (FromFunctionType && ToFunctionType) {
2207     // If the function types are exactly the same, this isn't an
2208     // Objective-C pointer conversion.
2209     if (Context.getCanonicalType(FromPointeeType)
2210           == Context.getCanonicalType(ToPointeeType))
2211       return false;
2212 
2213     // Perform the quick checks that will tell us whether these
2214     // function types are obviously different.
2215     if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2216         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2217         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2218       return false;
2219 
2220     bool HasObjCConversion = false;
2221     if (Context.getCanonicalType(FromFunctionType->getResultType())
2222           == Context.getCanonicalType(ToFunctionType->getResultType())) {
2223       // Okay, the types match exactly. Nothing to do.
2224     } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2225                                        ToFunctionType->getResultType(),
2226                                        ConvertedType, IncompatibleObjC)) {
2227       // Okay, we have an Objective-C pointer conversion.
2228       HasObjCConversion = true;
2229     } else {
2230       // Function types are too different. Abort.
2231       return false;
2232     }
2233 
2234     // Check argument types.
2235     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2236          ArgIdx != NumArgs; ++ArgIdx) {
2237       QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2238       QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2239       if (Context.getCanonicalType(FromArgType)
2240             == Context.getCanonicalType(ToArgType)) {
2241         // Okay, the types match exactly. Nothing to do.
2242       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2243                                          ConvertedType, IncompatibleObjC)) {
2244         // Okay, we have an Objective-C pointer conversion.
2245         HasObjCConversion = true;
2246       } else {
2247         // Argument types are too different. Abort.
2248         return false;
2249       }
2250     }
2251 
2252     if (HasObjCConversion) {
2253       // We had an Objective-C conversion. Allow this pointer
2254       // conversion, but complain about it.
2255       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2256       IncompatibleObjC = true;
2257       return true;
2258     }
2259   }
2260 
2261   return false;
2262 }
2263 
2264 /// \brief Determine whether this is an Objective-C writeback conversion,
2265 /// used for parameter passing when performing automatic reference counting.
2266 ///
2267 /// \param FromType The type we're converting form.
2268 ///
2269 /// \param ToType The type we're converting to.
2270 ///
2271 /// \param ConvertedType The type that will be produced after applying
2272 /// this conversion.
2273 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2274                                      QualType &ConvertedType) {
2275   if (!getLangOpts().ObjCAutoRefCount ||
2276       Context.hasSameUnqualifiedType(FromType, ToType))
2277     return false;
2278 
2279   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2280   QualType ToPointee;
2281   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2282     ToPointee = ToPointer->getPointeeType();
2283   else
2284     return false;
2285 
2286   Qualifiers ToQuals = ToPointee.getQualifiers();
2287   if (!ToPointee->isObjCLifetimeType() ||
2288       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2289       !ToQuals.withoutObjCLifetime().empty())
2290     return false;
2291 
2292   // Argument must be a pointer to __strong to __weak.
2293   QualType FromPointee;
2294   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2295     FromPointee = FromPointer->getPointeeType();
2296   else
2297     return false;
2298 
2299   Qualifiers FromQuals = FromPointee.getQualifiers();
2300   if (!FromPointee->isObjCLifetimeType() ||
2301       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2302        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2303     return false;
2304 
2305   // Make sure that we have compatible qualifiers.
2306   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2307   if (!ToQuals.compatiblyIncludes(FromQuals))
2308     return false;
2309 
2310   // Remove qualifiers from the pointee type we're converting from; they
2311   // aren't used in the compatibility check belong, and we'll be adding back
2312   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2313   FromPointee = FromPointee.getUnqualifiedType();
2314 
2315   // The unqualified form of the pointee types must be compatible.
2316   ToPointee = ToPointee.getUnqualifiedType();
2317   bool IncompatibleObjC;
2318   if (Context.typesAreCompatible(FromPointee, ToPointee))
2319     FromPointee = ToPointee;
2320   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2321                                     IncompatibleObjC))
2322     return false;
2323 
2324   /// \brief Construct the type we're converting to, which is a pointer to
2325   /// __autoreleasing pointee.
2326   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2327   ConvertedType = Context.getPointerType(FromPointee);
2328   return true;
2329 }
2330 
2331 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2332                                     QualType& ConvertedType) {
2333   QualType ToPointeeType;
2334   if (const BlockPointerType *ToBlockPtr =
2335         ToType->getAs<BlockPointerType>())
2336     ToPointeeType = ToBlockPtr->getPointeeType();
2337   else
2338     return false;
2339 
2340   QualType FromPointeeType;
2341   if (const BlockPointerType *FromBlockPtr =
2342       FromType->getAs<BlockPointerType>())
2343     FromPointeeType = FromBlockPtr->getPointeeType();
2344   else
2345     return false;
2346   // We have pointer to blocks, check whether the only
2347   // differences in the argument and result types are in Objective-C
2348   // pointer conversions. If so, we permit the conversion.
2349 
2350   const FunctionProtoType *FromFunctionType
2351     = FromPointeeType->getAs<FunctionProtoType>();
2352   const FunctionProtoType *ToFunctionType
2353     = ToPointeeType->getAs<FunctionProtoType>();
2354 
2355   if (!FromFunctionType || !ToFunctionType)
2356     return false;
2357 
2358   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2359     return true;
2360 
2361   // Perform the quick checks that will tell us whether these
2362   // function types are obviously different.
2363   if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2364       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2365     return false;
2366 
2367   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2368   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2369   if (FromEInfo != ToEInfo)
2370     return false;
2371 
2372   bool IncompatibleObjC = false;
2373   if (Context.hasSameType(FromFunctionType->getResultType(),
2374                           ToFunctionType->getResultType())) {
2375     // Okay, the types match exactly. Nothing to do.
2376   } else {
2377     QualType RHS = FromFunctionType->getResultType();
2378     QualType LHS = ToFunctionType->getResultType();
2379     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2380         !RHS.hasQualifiers() && LHS.hasQualifiers())
2381        LHS = LHS.getUnqualifiedType();
2382 
2383      if (Context.hasSameType(RHS,LHS)) {
2384        // OK exact match.
2385      } else if (isObjCPointerConversion(RHS, LHS,
2386                                         ConvertedType, IncompatibleObjC)) {
2387      if (IncompatibleObjC)
2388        return false;
2389      // Okay, we have an Objective-C pointer conversion.
2390      }
2391      else
2392        return false;
2393    }
2394 
2395    // Check argument types.
2396    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2397         ArgIdx != NumArgs; ++ArgIdx) {
2398      IncompatibleObjC = false;
2399      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2400      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2401      if (Context.hasSameType(FromArgType, ToArgType)) {
2402        // Okay, the types match exactly. Nothing to do.
2403      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2404                                         ConvertedType, IncompatibleObjC)) {
2405        if (IncompatibleObjC)
2406          return false;
2407        // Okay, we have an Objective-C pointer conversion.
2408      } else
2409        // Argument types are too different. Abort.
2410        return false;
2411    }
2412    if (LangOpts.ObjCAutoRefCount &&
2413        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2414                                                     ToFunctionType))
2415      return false;
2416 
2417    ConvertedType = ToType;
2418    return true;
2419 }
2420 
2421 enum {
2422   ft_default,
2423   ft_different_class,
2424   ft_parameter_arity,
2425   ft_parameter_mismatch,
2426   ft_return_type,
2427   ft_qualifer_mismatch
2428 };
2429 
2430 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2431 /// function types.  Catches different number of parameter, mismatch in
2432 /// parameter types, and different return types.
2433 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2434                                       QualType FromType, QualType ToType) {
2435   // If either type is not valid, include no extra info.
2436   if (FromType.isNull() || ToType.isNull()) {
2437     PDiag << ft_default;
2438     return;
2439   }
2440 
2441   // Get the function type from the pointers.
2442   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2443     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2444                             *ToMember = ToType->getAs<MemberPointerType>();
2445     if (FromMember->getClass() != ToMember->getClass()) {
2446       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2447             << QualType(FromMember->getClass(), 0);
2448       return;
2449     }
2450     FromType = FromMember->getPointeeType();
2451     ToType = ToMember->getPointeeType();
2452   }
2453 
2454   if (FromType->isPointerType())
2455     FromType = FromType->getPointeeType();
2456   if (ToType->isPointerType())
2457     ToType = ToType->getPointeeType();
2458 
2459   // Remove references.
2460   FromType = FromType.getNonReferenceType();
2461   ToType = ToType.getNonReferenceType();
2462 
2463   // Don't print extra info for non-specialized template functions.
2464   if (FromType->isInstantiationDependentType() &&
2465       !FromType->getAs<TemplateSpecializationType>()) {
2466     PDiag << ft_default;
2467     return;
2468   }
2469 
2470   // No extra info for same types.
2471   if (Context.hasSameType(FromType, ToType)) {
2472     PDiag << ft_default;
2473     return;
2474   }
2475 
2476   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2477                           *ToFunction = ToType->getAs<FunctionProtoType>();
2478 
2479   // Both types need to be function types.
2480   if (!FromFunction || !ToFunction) {
2481     PDiag << ft_default;
2482     return;
2483   }
2484 
2485   if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2486     PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2487           << FromFunction->getNumArgs();
2488     return;
2489   }
2490 
2491   // Handle different parameter types.
2492   unsigned ArgPos;
2493   if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2494     PDiag << ft_parameter_mismatch << ArgPos + 1
2495           << ToFunction->getArgType(ArgPos)
2496           << FromFunction->getArgType(ArgPos);
2497     return;
2498   }
2499 
2500   // Handle different return type.
2501   if (!Context.hasSameType(FromFunction->getResultType(),
2502                            ToFunction->getResultType())) {
2503     PDiag << ft_return_type << ToFunction->getResultType()
2504           << FromFunction->getResultType();
2505     return;
2506   }
2507 
2508   unsigned FromQuals = FromFunction->getTypeQuals(),
2509            ToQuals = ToFunction->getTypeQuals();
2510   if (FromQuals != ToQuals) {
2511     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2512     return;
2513   }
2514 
2515   // Unable to find a difference, so add no extra info.
2516   PDiag << ft_default;
2517 }
2518 
2519 /// FunctionArgTypesAreEqual - This routine checks two function proto types
2520 /// for equality of their argument types. Caller has already checked that
2521 /// they have same number of arguments. This routine assumes that Objective-C
2522 /// pointer types which only differ in their protocol qualifiers are equal.
2523 /// If the parameters are different, ArgPos will have the parameter index
2524 /// of the first different parameter.
2525 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2526                                     const FunctionProtoType *NewType,
2527                                     unsigned *ArgPos) {
2528   if (!getLangOpts().ObjC1) {
2529     for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2530          N = NewType->arg_type_begin(),
2531          E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2532       if (!Context.hasSameType(*O, *N)) {
2533         if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2534         return false;
2535       }
2536     }
2537     return true;
2538   }
2539 
2540   for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2541        N = NewType->arg_type_begin(),
2542        E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2543     QualType ToType = (*O);
2544     QualType FromType = (*N);
2545     if (!Context.hasSameType(ToType, FromType)) {
2546       if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2547         if (const PointerType *PTFr = FromType->getAs<PointerType>())
2548           if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2549                PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2550               (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2551                PTFr->getPointeeType()->isObjCQualifiedClassType()))
2552             continue;
2553       }
2554       else if (const ObjCObjectPointerType *PTTo =
2555                  ToType->getAs<ObjCObjectPointerType>()) {
2556         if (const ObjCObjectPointerType *PTFr =
2557               FromType->getAs<ObjCObjectPointerType>())
2558           if (Context.hasSameUnqualifiedType(
2559                 PTTo->getObjectType()->getBaseType(),
2560                 PTFr->getObjectType()->getBaseType()))
2561             continue;
2562       }
2563       if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2564       return false;
2565     }
2566   }
2567   return true;
2568 }
2569 
2570 /// CheckPointerConversion - Check the pointer conversion from the
2571 /// expression From to the type ToType. This routine checks for
2572 /// ambiguous or inaccessible derived-to-base pointer
2573 /// conversions for which IsPointerConversion has already returned
2574 /// true. It returns true and produces a diagnostic if there was an
2575 /// error, or returns false otherwise.
2576 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2577                                   CastKind &Kind,
2578                                   CXXCastPath& BasePath,
2579                                   bool IgnoreBaseAccess) {
2580   QualType FromType = From->getType();
2581   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2582 
2583   Kind = CK_BitCast;
2584 
2585   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2586       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2587       Expr::NPCK_ZeroExpression) {
2588     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2589       DiagRuntimeBehavior(From->getExprLoc(), From,
2590                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2591                             << ToType << From->getSourceRange());
2592     else if (!isUnevaluatedContext())
2593       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2594         << ToType << From->getSourceRange();
2595   }
2596   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2597     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2598       QualType FromPointeeType = FromPtrType->getPointeeType(),
2599                ToPointeeType   = ToPtrType->getPointeeType();
2600 
2601       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2602           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2603         // We must have a derived-to-base conversion. Check an
2604         // ambiguous or inaccessible conversion.
2605         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2606                                          From->getExprLoc(),
2607                                          From->getSourceRange(), &BasePath,
2608                                          IgnoreBaseAccess))
2609           return true;
2610 
2611         // The conversion was successful.
2612         Kind = CK_DerivedToBase;
2613       }
2614     }
2615   } else if (const ObjCObjectPointerType *ToPtrType =
2616                ToType->getAs<ObjCObjectPointerType>()) {
2617     if (const ObjCObjectPointerType *FromPtrType =
2618           FromType->getAs<ObjCObjectPointerType>()) {
2619       // Objective-C++ conversions are always okay.
2620       // FIXME: We should have a different class of conversions for the
2621       // Objective-C++ implicit conversions.
2622       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2623         return false;
2624     } else if (FromType->isBlockPointerType()) {
2625       Kind = CK_BlockPointerToObjCPointerCast;
2626     } else {
2627       Kind = CK_CPointerToObjCPointerCast;
2628     }
2629   } else if (ToType->isBlockPointerType()) {
2630     if (!FromType->isBlockPointerType())
2631       Kind = CK_AnyPointerToBlockPointerCast;
2632   }
2633 
2634   // We shouldn't fall into this case unless it's valid for other
2635   // reasons.
2636   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2637     Kind = CK_NullToPointer;
2638 
2639   return false;
2640 }
2641 
2642 /// IsMemberPointerConversion - Determines whether the conversion of the
2643 /// expression From, which has the (possibly adjusted) type FromType, can be
2644 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2645 /// If so, returns true and places the converted type (that might differ from
2646 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2647 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2648                                      QualType ToType,
2649                                      bool InOverloadResolution,
2650                                      QualType &ConvertedType) {
2651   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2652   if (!ToTypePtr)
2653     return false;
2654 
2655   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2656   if (From->isNullPointerConstant(Context,
2657                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2658                                         : Expr::NPC_ValueDependentIsNull)) {
2659     ConvertedType = ToType;
2660     return true;
2661   }
2662 
2663   // Otherwise, both types have to be member pointers.
2664   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2665   if (!FromTypePtr)
2666     return false;
2667 
2668   // A pointer to member of B can be converted to a pointer to member of D,
2669   // where D is derived from B (C++ 4.11p2).
2670   QualType FromClass(FromTypePtr->getClass(), 0);
2671   QualType ToClass(ToTypePtr->getClass(), 0);
2672 
2673   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2674       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2675       IsDerivedFrom(ToClass, FromClass)) {
2676     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2677                                                  ToClass.getTypePtr());
2678     return true;
2679   }
2680 
2681   return false;
2682 }
2683 
2684 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2685 /// expression From to the type ToType. This routine checks for ambiguous or
2686 /// virtual or inaccessible base-to-derived member pointer conversions
2687 /// for which IsMemberPointerConversion has already returned true. It returns
2688 /// true and produces a diagnostic if there was an error, or returns false
2689 /// otherwise.
2690 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2691                                         CastKind &Kind,
2692                                         CXXCastPath &BasePath,
2693                                         bool IgnoreBaseAccess) {
2694   QualType FromType = From->getType();
2695   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2696   if (!FromPtrType) {
2697     // This must be a null pointer to member pointer conversion
2698     assert(From->isNullPointerConstant(Context,
2699                                        Expr::NPC_ValueDependentIsNull) &&
2700            "Expr must be null pointer constant!");
2701     Kind = CK_NullToMemberPointer;
2702     return false;
2703   }
2704 
2705   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2706   assert(ToPtrType && "No member pointer cast has a target type "
2707                       "that is not a member pointer.");
2708 
2709   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2710   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2711 
2712   // FIXME: What about dependent types?
2713   assert(FromClass->isRecordType() && "Pointer into non-class.");
2714   assert(ToClass->isRecordType() && "Pointer into non-class.");
2715 
2716   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2717                      /*DetectVirtual=*/true);
2718   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2719   assert(DerivationOkay &&
2720          "Should not have been called if derivation isn't OK.");
2721   (void)DerivationOkay;
2722 
2723   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2724                                   getUnqualifiedType())) {
2725     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2726     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2727       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2728     return true;
2729   }
2730 
2731   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2732     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2733       << FromClass << ToClass << QualType(VBase, 0)
2734       << From->getSourceRange();
2735     return true;
2736   }
2737 
2738   if (!IgnoreBaseAccess)
2739     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2740                          Paths.front(),
2741                          diag::err_downcast_from_inaccessible_base);
2742 
2743   // Must be a base to derived member conversion.
2744   BuildBasePathArray(Paths, BasePath);
2745   Kind = CK_BaseToDerivedMemberPointer;
2746   return false;
2747 }
2748 
2749 /// IsQualificationConversion - Determines whether the conversion from
2750 /// an rvalue of type FromType to ToType is a qualification conversion
2751 /// (C++ 4.4).
2752 ///
2753 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2754 /// when the qualification conversion involves a change in the Objective-C
2755 /// object lifetime.
2756 bool
2757 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2758                                 bool CStyle, bool &ObjCLifetimeConversion) {
2759   FromType = Context.getCanonicalType(FromType);
2760   ToType = Context.getCanonicalType(ToType);
2761   ObjCLifetimeConversion = false;
2762 
2763   // If FromType and ToType are the same type, this is not a
2764   // qualification conversion.
2765   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2766     return false;
2767 
2768   // (C++ 4.4p4):
2769   //   A conversion can add cv-qualifiers at levels other than the first
2770   //   in multi-level pointers, subject to the following rules: [...]
2771   bool PreviousToQualsIncludeConst = true;
2772   bool UnwrappedAnyPointer = false;
2773   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2774     // Within each iteration of the loop, we check the qualifiers to
2775     // determine if this still looks like a qualification
2776     // conversion. Then, if all is well, we unwrap one more level of
2777     // pointers or pointers-to-members and do it all again
2778     // until there are no more pointers or pointers-to-members left to
2779     // unwrap.
2780     UnwrappedAnyPointer = true;
2781 
2782     Qualifiers FromQuals = FromType.getQualifiers();
2783     Qualifiers ToQuals = ToType.getQualifiers();
2784 
2785     // Objective-C ARC:
2786     //   Check Objective-C lifetime conversions.
2787     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2788         UnwrappedAnyPointer) {
2789       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2790         ObjCLifetimeConversion = true;
2791         FromQuals.removeObjCLifetime();
2792         ToQuals.removeObjCLifetime();
2793       } else {
2794         // Qualification conversions cannot cast between different
2795         // Objective-C lifetime qualifiers.
2796         return false;
2797       }
2798     }
2799 
2800     // Allow addition/removal of GC attributes but not changing GC attributes.
2801     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2802         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2803       FromQuals.removeObjCGCAttr();
2804       ToQuals.removeObjCGCAttr();
2805     }
2806 
2807     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2808     //      2,j, and similarly for volatile.
2809     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2810       return false;
2811 
2812     //   -- if the cv 1,j and cv 2,j are different, then const is in
2813     //      every cv for 0 < k < j.
2814     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2815         && !PreviousToQualsIncludeConst)
2816       return false;
2817 
2818     // Keep track of whether all prior cv-qualifiers in the "to" type
2819     // include const.
2820     PreviousToQualsIncludeConst
2821       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2822   }
2823 
2824   // We are left with FromType and ToType being the pointee types
2825   // after unwrapping the original FromType and ToType the same number
2826   // of types. If we unwrapped any pointers, and if FromType and
2827   // ToType have the same unqualified type (since we checked
2828   // qualifiers above), then this is a qualification conversion.
2829   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2830 }
2831 
2832 /// \brief - Determine whether this is a conversion from a scalar type to an
2833 /// atomic type.
2834 ///
2835 /// If successful, updates \c SCS's second and third steps in the conversion
2836 /// sequence to finish the conversion.
2837 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2838                                 bool InOverloadResolution,
2839                                 StandardConversionSequence &SCS,
2840                                 bool CStyle) {
2841   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2842   if (!ToAtomic)
2843     return false;
2844 
2845   StandardConversionSequence InnerSCS;
2846   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2847                             InOverloadResolution, InnerSCS,
2848                             CStyle, /*AllowObjCWritebackConversion=*/false))
2849     return false;
2850 
2851   SCS.Second = InnerSCS.Second;
2852   SCS.setToType(1, InnerSCS.getToType(1));
2853   SCS.Third = InnerSCS.Third;
2854   SCS.QualificationIncludesObjCLifetime
2855     = InnerSCS.QualificationIncludesObjCLifetime;
2856   SCS.setToType(2, InnerSCS.getToType(2));
2857   return true;
2858 }
2859 
2860 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2861                                               CXXConstructorDecl *Constructor,
2862                                               QualType Type) {
2863   const FunctionProtoType *CtorType =
2864       Constructor->getType()->getAs<FunctionProtoType>();
2865   if (CtorType->getNumArgs() > 0) {
2866     QualType FirstArg = CtorType->getArgType(0);
2867     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2868       return true;
2869   }
2870   return false;
2871 }
2872 
2873 static OverloadingResult
2874 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2875                                        CXXRecordDecl *To,
2876                                        UserDefinedConversionSequence &User,
2877                                        OverloadCandidateSet &CandidateSet,
2878                                        bool AllowExplicit) {
2879   DeclContext::lookup_iterator Con, ConEnd;
2880   for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2881        Con != ConEnd; ++Con) {
2882     NamedDecl *D = *Con;
2883     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2884 
2885     // Find the constructor (which may be a template).
2886     CXXConstructorDecl *Constructor = 0;
2887     FunctionTemplateDecl *ConstructorTmpl
2888       = dyn_cast<FunctionTemplateDecl>(D);
2889     if (ConstructorTmpl)
2890       Constructor
2891         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2892     else
2893       Constructor = cast<CXXConstructorDecl>(D);
2894 
2895     bool Usable = !Constructor->isInvalidDecl() &&
2896                   S.isInitListConstructor(Constructor) &&
2897                   (AllowExplicit || !Constructor->isExplicit());
2898     if (Usable) {
2899       // If the first argument is (a reference to) the target type,
2900       // suppress conversions.
2901       bool SuppressUserConversions =
2902           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2903       if (ConstructorTmpl)
2904         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2905                                        /*ExplicitArgs*/ 0,
2906                                        From, CandidateSet,
2907                                        SuppressUserConversions);
2908       else
2909         S.AddOverloadCandidate(Constructor, FoundDecl,
2910                                From, CandidateSet,
2911                                SuppressUserConversions);
2912     }
2913   }
2914 
2915   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2916 
2917   OverloadCandidateSet::iterator Best;
2918   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2919   case OR_Success: {
2920     // Record the standard conversion we used and the conversion function.
2921     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2922     S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2923 
2924     QualType ThisType = Constructor->getThisType(S.Context);
2925     // Initializer lists don't have conversions as such.
2926     User.Before.setAsIdentityConversion();
2927     User.HadMultipleCandidates = HadMultipleCandidates;
2928     User.ConversionFunction = Constructor;
2929     User.FoundConversionFunction = Best->FoundDecl;
2930     User.After.setAsIdentityConversion();
2931     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2932     User.After.setAllToTypes(ToType);
2933     return OR_Success;
2934   }
2935 
2936   case OR_No_Viable_Function:
2937     return OR_No_Viable_Function;
2938   case OR_Deleted:
2939     return OR_Deleted;
2940   case OR_Ambiguous:
2941     return OR_Ambiguous;
2942   }
2943 
2944   llvm_unreachable("Invalid OverloadResult!");
2945 }
2946 
2947 /// Determines whether there is a user-defined conversion sequence
2948 /// (C++ [over.ics.user]) that converts expression From to the type
2949 /// ToType. If such a conversion exists, User will contain the
2950 /// user-defined conversion sequence that performs such a conversion
2951 /// and this routine will return true. Otherwise, this routine returns
2952 /// false and User is unspecified.
2953 ///
2954 /// \param AllowExplicit  true if the conversion should consider C++0x
2955 /// "explicit" conversion functions as well as non-explicit conversion
2956 /// functions (C++0x [class.conv.fct]p2).
2957 static OverloadingResult
2958 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2959                         UserDefinedConversionSequence &User,
2960                         OverloadCandidateSet &CandidateSet,
2961                         bool AllowExplicit) {
2962   // Whether we will only visit constructors.
2963   bool ConstructorsOnly = false;
2964 
2965   // If the type we are conversion to is a class type, enumerate its
2966   // constructors.
2967   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2968     // C++ [over.match.ctor]p1:
2969     //   When objects of class type are direct-initialized (8.5), or
2970     //   copy-initialized from an expression of the same or a
2971     //   derived class type (8.5), overload resolution selects the
2972     //   constructor. [...] For copy-initialization, the candidate
2973     //   functions are all the converting constructors (12.3.1) of
2974     //   that class. The argument list is the expression-list within
2975     //   the parentheses of the initializer.
2976     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2977         (From->getType()->getAs<RecordType>() &&
2978          S.IsDerivedFrom(From->getType(), ToType)))
2979       ConstructorsOnly = true;
2980 
2981     S.RequireCompleteType(From->getLocStart(), ToType, 0);
2982     // RequireCompleteType may have returned true due to some invalid decl
2983     // during template instantiation, but ToType may be complete enough now
2984     // to try to recover.
2985     if (ToType->isIncompleteType()) {
2986       // We're not going to find any constructors.
2987     } else if (CXXRecordDecl *ToRecordDecl
2988                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
2989 
2990       Expr **Args = &From;
2991       unsigned NumArgs = 1;
2992       bool ListInitializing = false;
2993       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
2994         // But first, see if there is an init-list-contructor that will work.
2995         OverloadingResult Result = IsInitializerListConstructorConversion(
2996             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2997         if (Result != OR_No_Viable_Function)
2998           return Result;
2999         // Never mind.
3000         CandidateSet.clear();
3001 
3002         // If we're list-initializing, we pass the individual elements as
3003         // arguments, not the entire list.
3004         Args = InitList->getInits();
3005         NumArgs = InitList->getNumInits();
3006         ListInitializing = true;
3007       }
3008 
3009       DeclContext::lookup_iterator Con, ConEnd;
3010       for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
3011            Con != ConEnd; ++Con) {
3012         NamedDecl *D = *Con;
3013         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3014 
3015         // Find the constructor (which may be a template).
3016         CXXConstructorDecl *Constructor = 0;
3017         FunctionTemplateDecl *ConstructorTmpl
3018           = dyn_cast<FunctionTemplateDecl>(D);
3019         if (ConstructorTmpl)
3020           Constructor
3021             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3022         else
3023           Constructor = cast<CXXConstructorDecl>(D);
3024 
3025         bool Usable = !Constructor->isInvalidDecl();
3026         if (ListInitializing)
3027           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3028         else
3029           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3030         if (Usable) {
3031           bool SuppressUserConversions = !ConstructorsOnly;
3032           if (SuppressUserConversions && ListInitializing) {
3033             SuppressUserConversions = false;
3034             if (NumArgs == 1) {
3035               // If the first argument is (a reference to) the target type,
3036               // suppress conversions.
3037               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3038                                                 S.Context, Constructor, ToType);
3039             }
3040           }
3041           if (ConstructorTmpl)
3042             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3043                                            /*ExplicitArgs*/ 0,
3044                                            llvm::makeArrayRef(Args, NumArgs),
3045                                            CandidateSet, SuppressUserConversions);
3046           else
3047             // Allow one user-defined conversion when user specifies a
3048             // From->ToType conversion via an static cast (c-style, etc).
3049             S.AddOverloadCandidate(Constructor, FoundDecl,
3050                                    llvm::makeArrayRef(Args, NumArgs),
3051                                    CandidateSet, SuppressUserConversions);
3052         }
3053       }
3054     }
3055   }
3056 
3057   // Enumerate conversion functions, if we're allowed to.
3058   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3059   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3060     // No conversion functions from incomplete types.
3061   } else if (const RecordType *FromRecordType
3062                                    = From->getType()->getAs<RecordType>()) {
3063     if (CXXRecordDecl *FromRecordDecl
3064          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3065       // Add all of the conversion functions as candidates.
3066       const UnresolvedSetImpl *Conversions
3067         = FromRecordDecl->getVisibleConversionFunctions();
3068       for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3069              E = Conversions->end(); I != E; ++I) {
3070         DeclAccessPair FoundDecl = I.getPair();
3071         NamedDecl *D = FoundDecl.getDecl();
3072         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3073         if (isa<UsingShadowDecl>(D))
3074           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3075 
3076         CXXConversionDecl *Conv;
3077         FunctionTemplateDecl *ConvTemplate;
3078         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3079           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3080         else
3081           Conv = cast<CXXConversionDecl>(D);
3082 
3083         if (AllowExplicit || !Conv->isExplicit()) {
3084           if (ConvTemplate)
3085             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3086                                              ActingContext, From, ToType,
3087                                              CandidateSet);
3088           else
3089             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3090                                      From, ToType, CandidateSet);
3091         }
3092       }
3093     }
3094   }
3095 
3096   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3097 
3098   OverloadCandidateSet::iterator Best;
3099   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3100   case OR_Success:
3101     // Record the standard conversion we used and the conversion function.
3102     if (CXXConstructorDecl *Constructor
3103           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3104       S.MarkFunctionReferenced(From->getLocStart(), Constructor);
3105 
3106       // C++ [over.ics.user]p1:
3107       //   If the user-defined conversion is specified by a
3108       //   constructor (12.3.1), the initial standard conversion
3109       //   sequence converts the source type to the type required by
3110       //   the argument of the constructor.
3111       //
3112       QualType ThisType = Constructor->getThisType(S.Context);
3113       if (isa<InitListExpr>(From)) {
3114         // Initializer lists don't have conversions as such.
3115         User.Before.setAsIdentityConversion();
3116       } else {
3117         if (Best->Conversions[0].isEllipsis())
3118           User.EllipsisConversion = true;
3119         else {
3120           User.Before = Best->Conversions[0].Standard;
3121           User.EllipsisConversion = false;
3122         }
3123       }
3124       User.HadMultipleCandidates = HadMultipleCandidates;
3125       User.ConversionFunction = Constructor;
3126       User.FoundConversionFunction = Best->FoundDecl;
3127       User.After.setAsIdentityConversion();
3128       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3129       User.After.setAllToTypes(ToType);
3130       return OR_Success;
3131     }
3132     if (CXXConversionDecl *Conversion
3133                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3134       S.MarkFunctionReferenced(From->getLocStart(), Conversion);
3135 
3136       // C++ [over.ics.user]p1:
3137       //
3138       //   [...] If the user-defined conversion is specified by a
3139       //   conversion function (12.3.2), the initial standard
3140       //   conversion sequence converts the source type to the
3141       //   implicit object parameter of the conversion function.
3142       User.Before = Best->Conversions[0].Standard;
3143       User.HadMultipleCandidates = HadMultipleCandidates;
3144       User.ConversionFunction = Conversion;
3145       User.FoundConversionFunction = Best->FoundDecl;
3146       User.EllipsisConversion = false;
3147 
3148       // C++ [over.ics.user]p2:
3149       //   The second standard conversion sequence converts the
3150       //   result of the user-defined conversion to the target type
3151       //   for the sequence. Since an implicit conversion sequence
3152       //   is an initialization, the special rules for
3153       //   initialization by user-defined conversion apply when
3154       //   selecting the best user-defined conversion for a
3155       //   user-defined conversion sequence (see 13.3.3 and
3156       //   13.3.3.1).
3157       User.After = Best->FinalConversion;
3158       return OR_Success;
3159     }
3160     llvm_unreachable("Not a constructor or conversion function?");
3161 
3162   case OR_No_Viable_Function:
3163     return OR_No_Viable_Function;
3164   case OR_Deleted:
3165     // No conversion here! We're done.
3166     return OR_Deleted;
3167 
3168   case OR_Ambiguous:
3169     return OR_Ambiguous;
3170   }
3171 
3172   llvm_unreachable("Invalid OverloadResult!");
3173 }
3174 
3175 bool
3176 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3177   ImplicitConversionSequence ICS;
3178   OverloadCandidateSet CandidateSet(From->getExprLoc());
3179   OverloadingResult OvResult =
3180     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3181                             CandidateSet, false);
3182   if (OvResult == OR_Ambiguous)
3183     Diag(From->getLocStart(),
3184          diag::err_typecheck_ambiguous_condition)
3185           << From->getType() << ToType << From->getSourceRange();
3186   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3187     Diag(From->getLocStart(),
3188          diag::err_typecheck_nonviable_condition)
3189     << From->getType() << ToType << From->getSourceRange();
3190   else
3191     return false;
3192   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3193   return true;
3194 }
3195 
3196 /// \brief Compare the user-defined conversion functions or constructors
3197 /// of two user-defined conversion sequences to determine whether any ordering
3198 /// is possible.
3199 static ImplicitConversionSequence::CompareKind
3200 compareConversionFunctions(Sema &S,
3201                            FunctionDecl *Function1,
3202                            FunctionDecl *Function2) {
3203   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
3204     return ImplicitConversionSequence::Indistinguishable;
3205 
3206   // Objective-C++:
3207   //   If both conversion functions are implicitly-declared conversions from
3208   //   a lambda closure type to a function pointer and a block pointer,
3209   //   respectively, always prefer the conversion to a function pointer,
3210   //   because the function pointer is more lightweight and is more likely
3211   //   to keep code working.
3212   CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3213   if (!Conv1)
3214     return ImplicitConversionSequence::Indistinguishable;
3215 
3216   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3217   if (!Conv2)
3218     return ImplicitConversionSequence::Indistinguishable;
3219 
3220   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3221     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3222     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3223     if (Block1 != Block2)
3224       return Block1? ImplicitConversionSequence::Worse
3225                    : ImplicitConversionSequence::Better;
3226   }
3227 
3228   return ImplicitConversionSequence::Indistinguishable;
3229 }
3230 
3231 /// CompareImplicitConversionSequences - Compare two implicit
3232 /// conversion sequences to determine whether one is better than the
3233 /// other or if they are indistinguishable (C++ 13.3.3.2).
3234 static ImplicitConversionSequence::CompareKind
3235 CompareImplicitConversionSequences(Sema &S,
3236                                    const ImplicitConversionSequence& ICS1,
3237                                    const ImplicitConversionSequence& ICS2)
3238 {
3239   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3240   // conversion sequences (as defined in 13.3.3.1)
3241   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3242   //      conversion sequence than a user-defined conversion sequence or
3243   //      an ellipsis conversion sequence, and
3244   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3245   //      conversion sequence than an ellipsis conversion sequence
3246   //      (13.3.3.1.3).
3247   //
3248   // C++0x [over.best.ics]p10:
3249   //   For the purpose of ranking implicit conversion sequences as
3250   //   described in 13.3.3.2, the ambiguous conversion sequence is
3251   //   treated as a user-defined sequence that is indistinguishable
3252   //   from any other user-defined conversion sequence.
3253   if (ICS1.getKindRank() < ICS2.getKindRank())
3254     return ImplicitConversionSequence::Better;
3255   if (ICS2.getKindRank() < ICS1.getKindRank())
3256     return ImplicitConversionSequence::Worse;
3257 
3258   // The following checks require both conversion sequences to be of
3259   // the same kind.
3260   if (ICS1.getKind() != ICS2.getKind())
3261     return ImplicitConversionSequence::Indistinguishable;
3262 
3263   ImplicitConversionSequence::CompareKind Result =
3264       ImplicitConversionSequence::Indistinguishable;
3265 
3266   // Two implicit conversion sequences of the same form are
3267   // indistinguishable conversion sequences unless one of the
3268   // following rules apply: (C++ 13.3.3.2p3):
3269   if (ICS1.isStandard())
3270     Result = CompareStandardConversionSequences(S,
3271                                                 ICS1.Standard, ICS2.Standard);
3272   else if (ICS1.isUserDefined()) {
3273     // User-defined conversion sequence U1 is a better conversion
3274     // sequence than another user-defined conversion sequence U2 if
3275     // they contain the same user-defined conversion function or
3276     // constructor and if the second standard conversion sequence of
3277     // U1 is better than the second standard conversion sequence of
3278     // U2 (C++ 13.3.3.2p3).
3279     if (ICS1.UserDefined.ConversionFunction ==
3280           ICS2.UserDefined.ConversionFunction)
3281       Result = CompareStandardConversionSequences(S,
3282                                                   ICS1.UserDefined.After,
3283                                                   ICS2.UserDefined.After);
3284     else
3285       Result = compareConversionFunctions(S,
3286                                           ICS1.UserDefined.ConversionFunction,
3287                                           ICS2.UserDefined.ConversionFunction);
3288   }
3289 
3290   // List-initialization sequence L1 is a better conversion sequence than
3291   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3292   // for some X and L2 does not.
3293   if (Result == ImplicitConversionSequence::Indistinguishable &&
3294       !ICS1.isBad() &&
3295       ICS1.isListInitializationSequence() &&
3296       ICS2.isListInitializationSequence()) {
3297     if (ICS1.isStdInitializerListElement() &&
3298         !ICS2.isStdInitializerListElement())
3299       return ImplicitConversionSequence::Better;
3300     if (!ICS1.isStdInitializerListElement() &&
3301         ICS2.isStdInitializerListElement())
3302       return ImplicitConversionSequence::Worse;
3303   }
3304 
3305   return Result;
3306 }
3307 
3308 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3309   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3310     Qualifiers Quals;
3311     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3312     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3313   }
3314 
3315   return Context.hasSameUnqualifiedType(T1, T2);
3316 }
3317 
3318 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3319 // determine if one is a proper subset of the other.
3320 static ImplicitConversionSequence::CompareKind
3321 compareStandardConversionSubsets(ASTContext &Context,
3322                                  const StandardConversionSequence& SCS1,
3323                                  const StandardConversionSequence& SCS2) {
3324   ImplicitConversionSequence::CompareKind Result
3325     = ImplicitConversionSequence::Indistinguishable;
3326 
3327   // the identity conversion sequence is considered to be a subsequence of
3328   // any non-identity conversion sequence
3329   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3330     return ImplicitConversionSequence::Better;
3331   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3332     return ImplicitConversionSequence::Worse;
3333 
3334   if (SCS1.Second != SCS2.Second) {
3335     if (SCS1.Second == ICK_Identity)
3336       Result = ImplicitConversionSequence::Better;
3337     else if (SCS2.Second == ICK_Identity)
3338       Result = ImplicitConversionSequence::Worse;
3339     else
3340       return ImplicitConversionSequence::Indistinguishable;
3341   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3342     return ImplicitConversionSequence::Indistinguishable;
3343 
3344   if (SCS1.Third == SCS2.Third) {
3345     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3346                              : ImplicitConversionSequence::Indistinguishable;
3347   }
3348 
3349   if (SCS1.Third == ICK_Identity)
3350     return Result == ImplicitConversionSequence::Worse
3351              ? ImplicitConversionSequence::Indistinguishable
3352              : ImplicitConversionSequence::Better;
3353 
3354   if (SCS2.Third == ICK_Identity)
3355     return Result == ImplicitConversionSequence::Better
3356              ? ImplicitConversionSequence::Indistinguishable
3357              : ImplicitConversionSequence::Worse;
3358 
3359   return ImplicitConversionSequence::Indistinguishable;
3360 }
3361 
3362 /// \brief Determine whether one of the given reference bindings is better
3363 /// than the other based on what kind of bindings they are.
3364 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3365                                        const StandardConversionSequence &SCS2) {
3366   // C++0x [over.ics.rank]p3b4:
3367   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3368   //      implicit object parameter of a non-static member function declared
3369   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3370   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3371   //      lvalue reference to a function lvalue and S2 binds an rvalue
3372   //      reference*.
3373   //
3374   // FIXME: Rvalue references. We're going rogue with the above edits,
3375   // because the semantics in the current C++0x working paper (N3225 at the
3376   // time of this writing) break the standard definition of std::forward
3377   // and std::reference_wrapper when dealing with references to functions.
3378   // Proposed wording changes submitted to CWG for consideration.
3379   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3380       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3381     return false;
3382 
3383   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3384           SCS2.IsLvalueReference) ||
3385          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3386           !SCS2.IsLvalueReference);
3387 }
3388 
3389 /// CompareStandardConversionSequences - Compare two standard
3390 /// conversion sequences to determine whether one is better than the
3391 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3392 static ImplicitConversionSequence::CompareKind
3393 CompareStandardConversionSequences(Sema &S,
3394                                    const StandardConversionSequence& SCS1,
3395                                    const StandardConversionSequence& SCS2)
3396 {
3397   // Standard conversion sequence S1 is a better conversion sequence
3398   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3399 
3400   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3401   //     sequences in the canonical form defined by 13.3.3.1.1,
3402   //     excluding any Lvalue Transformation; the identity conversion
3403   //     sequence is considered to be a subsequence of any
3404   //     non-identity conversion sequence) or, if not that,
3405   if (ImplicitConversionSequence::CompareKind CK
3406         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3407     return CK;
3408 
3409   //  -- the rank of S1 is better than the rank of S2 (by the rules
3410   //     defined below), or, if not that,
3411   ImplicitConversionRank Rank1 = SCS1.getRank();
3412   ImplicitConversionRank Rank2 = SCS2.getRank();
3413   if (Rank1 < Rank2)
3414     return ImplicitConversionSequence::Better;
3415   else if (Rank2 < Rank1)
3416     return ImplicitConversionSequence::Worse;
3417 
3418   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3419   // are indistinguishable unless one of the following rules
3420   // applies:
3421 
3422   //   A conversion that is not a conversion of a pointer, or
3423   //   pointer to member, to bool is better than another conversion
3424   //   that is such a conversion.
3425   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3426     return SCS2.isPointerConversionToBool()
3427              ? ImplicitConversionSequence::Better
3428              : ImplicitConversionSequence::Worse;
3429 
3430   // C++ [over.ics.rank]p4b2:
3431   //
3432   //   If class B is derived directly or indirectly from class A,
3433   //   conversion of B* to A* is better than conversion of B* to
3434   //   void*, and conversion of A* to void* is better than conversion
3435   //   of B* to void*.
3436   bool SCS1ConvertsToVoid
3437     = SCS1.isPointerConversionToVoidPointer(S.Context);
3438   bool SCS2ConvertsToVoid
3439     = SCS2.isPointerConversionToVoidPointer(S.Context);
3440   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3441     // Exactly one of the conversion sequences is a conversion to
3442     // a void pointer; it's the worse conversion.
3443     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3444                               : ImplicitConversionSequence::Worse;
3445   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3446     // Neither conversion sequence converts to a void pointer; compare
3447     // their derived-to-base conversions.
3448     if (ImplicitConversionSequence::CompareKind DerivedCK
3449           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3450       return DerivedCK;
3451   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3452              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3453     // Both conversion sequences are conversions to void
3454     // pointers. Compare the source types to determine if there's an
3455     // inheritance relationship in their sources.
3456     QualType FromType1 = SCS1.getFromType();
3457     QualType FromType2 = SCS2.getFromType();
3458 
3459     // Adjust the types we're converting from via the array-to-pointer
3460     // conversion, if we need to.
3461     if (SCS1.First == ICK_Array_To_Pointer)
3462       FromType1 = S.Context.getArrayDecayedType(FromType1);
3463     if (SCS2.First == ICK_Array_To_Pointer)
3464       FromType2 = S.Context.getArrayDecayedType(FromType2);
3465 
3466     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3467     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3468 
3469     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3470       return ImplicitConversionSequence::Better;
3471     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3472       return ImplicitConversionSequence::Worse;
3473 
3474     // Objective-C++: If one interface is more specific than the
3475     // other, it is the better one.
3476     const ObjCObjectPointerType* FromObjCPtr1
3477       = FromType1->getAs<ObjCObjectPointerType>();
3478     const ObjCObjectPointerType* FromObjCPtr2
3479       = FromType2->getAs<ObjCObjectPointerType>();
3480     if (FromObjCPtr1 && FromObjCPtr2) {
3481       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3482                                                           FromObjCPtr2);
3483       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3484                                                            FromObjCPtr1);
3485       if (AssignLeft != AssignRight) {
3486         return AssignLeft? ImplicitConversionSequence::Better
3487                          : ImplicitConversionSequence::Worse;
3488       }
3489     }
3490   }
3491 
3492   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3493   // bullet 3).
3494   if (ImplicitConversionSequence::CompareKind QualCK
3495         = CompareQualificationConversions(S, SCS1, SCS2))
3496     return QualCK;
3497 
3498   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3499     // Check for a better reference binding based on the kind of bindings.
3500     if (isBetterReferenceBindingKind(SCS1, SCS2))
3501       return ImplicitConversionSequence::Better;
3502     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3503       return ImplicitConversionSequence::Worse;
3504 
3505     // C++ [over.ics.rank]p3b4:
3506     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3507     //      which the references refer are the same type except for
3508     //      top-level cv-qualifiers, and the type to which the reference
3509     //      initialized by S2 refers is more cv-qualified than the type
3510     //      to which the reference initialized by S1 refers.
3511     QualType T1 = SCS1.getToType(2);
3512     QualType T2 = SCS2.getToType(2);
3513     T1 = S.Context.getCanonicalType(T1);
3514     T2 = S.Context.getCanonicalType(T2);
3515     Qualifiers T1Quals, T2Quals;
3516     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3517     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3518     if (UnqualT1 == UnqualT2) {
3519       // Objective-C++ ARC: If the references refer to objects with different
3520       // lifetimes, prefer bindings that don't change lifetime.
3521       if (SCS1.ObjCLifetimeConversionBinding !=
3522                                           SCS2.ObjCLifetimeConversionBinding) {
3523         return SCS1.ObjCLifetimeConversionBinding
3524                                            ? ImplicitConversionSequence::Worse
3525                                            : ImplicitConversionSequence::Better;
3526       }
3527 
3528       // If the type is an array type, promote the element qualifiers to the
3529       // type for comparison.
3530       if (isa<ArrayType>(T1) && T1Quals)
3531         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3532       if (isa<ArrayType>(T2) && T2Quals)
3533         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3534       if (T2.isMoreQualifiedThan(T1))
3535         return ImplicitConversionSequence::Better;
3536       else if (T1.isMoreQualifiedThan(T2))
3537         return ImplicitConversionSequence::Worse;
3538     }
3539   }
3540 
3541   // In Microsoft mode, prefer an integral conversion to a
3542   // floating-to-integral conversion if the integral conversion
3543   // is between types of the same size.
3544   // For example:
3545   // void f(float);
3546   // void f(int);
3547   // int main {
3548   //    long a;
3549   //    f(a);
3550   // }
3551   // Here, MSVC will call f(int) instead of generating a compile error
3552   // as clang will do in standard mode.
3553   if (S.getLangOpts().MicrosoftMode &&
3554       SCS1.Second == ICK_Integral_Conversion &&
3555       SCS2.Second == ICK_Floating_Integral &&
3556       S.Context.getTypeSize(SCS1.getFromType()) ==
3557       S.Context.getTypeSize(SCS1.getToType(2)))
3558     return ImplicitConversionSequence::Better;
3559 
3560   return ImplicitConversionSequence::Indistinguishable;
3561 }
3562 
3563 /// CompareQualificationConversions - Compares two standard conversion
3564 /// sequences to determine whether they can be ranked based on their
3565 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3566 ImplicitConversionSequence::CompareKind
3567 CompareQualificationConversions(Sema &S,
3568                                 const StandardConversionSequence& SCS1,
3569                                 const StandardConversionSequence& SCS2) {
3570   // C++ 13.3.3.2p3:
3571   //  -- S1 and S2 differ only in their qualification conversion and
3572   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3573   //     cv-qualification signature of type T1 is a proper subset of
3574   //     the cv-qualification signature of type T2, and S1 is not the
3575   //     deprecated string literal array-to-pointer conversion (4.2).
3576   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3577       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3578     return ImplicitConversionSequence::Indistinguishable;
3579 
3580   // FIXME: the example in the standard doesn't use a qualification
3581   // conversion (!)
3582   QualType T1 = SCS1.getToType(2);
3583   QualType T2 = SCS2.getToType(2);
3584   T1 = S.Context.getCanonicalType(T1);
3585   T2 = S.Context.getCanonicalType(T2);
3586   Qualifiers T1Quals, T2Quals;
3587   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3588   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3589 
3590   // If the types are the same, we won't learn anything by unwrapped
3591   // them.
3592   if (UnqualT1 == UnqualT2)
3593     return ImplicitConversionSequence::Indistinguishable;
3594 
3595   // If the type is an array type, promote the element qualifiers to the type
3596   // for comparison.
3597   if (isa<ArrayType>(T1) && T1Quals)
3598     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3599   if (isa<ArrayType>(T2) && T2Quals)
3600     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3601 
3602   ImplicitConversionSequence::CompareKind Result
3603     = ImplicitConversionSequence::Indistinguishable;
3604 
3605   // Objective-C++ ARC:
3606   //   Prefer qualification conversions not involving a change in lifetime
3607   //   to qualification conversions that do not change lifetime.
3608   if (SCS1.QualificationIncludesObjCLifetime !=
3609                                       SCS2.QualificationIncludesObjCLifetime) {
3610     Result = SCS1.QualificationIncludesObjCLifetime
3611                ? ImplicitConversionSequence::Worse
3612                : ImplicitConversionSequence::Better;
3613   }
3614 
3615   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3616     // Within each iteration of the loop, we check the qualifiers to
3617     // determine if this still looks like a qualification
3618     // conversion. Then, if all is well, we unwrap one more level of
3619     // pointers or pointers-to-members and do it all again
3620     // until there are no more pointers or pointers-to-members left
3621     // to unwrap. This essentially mimics what
3622     // IsQualificationConversion does, but here we're checking for a
3623     // strict subset of qualifiers.
3624     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3625       // The qualifiers are the same, so this doesn't tell us anything
3626       // about how the sequences rank.
3627       ;
3628     else if (T2.isMoreQualifiedThan(T1)) {
3629       // T1 has fewer qualifiers, so it could be the better sequence.
3630       if (Result == ImplicitConversionSequence::Worse)
3631         // Neither has qualifiers that are a subset of the other's
3632         // qualifiers.
3633         return ImplicitConversionSequence::Indistinguishable;
3634 
3635       Result = ImplicitConversionSequence::Better;
3636     } else if (T1.isMoreQualifiedThan(T2)) {
3637       // T2 has fewer qualifiers, so it could be the better sequence.
3638       if (Result == ImplicitConversionSequence::Better)
3639         // Neither has qualifiers that are a subset of the other's
3640         // qualifiers.
3641         return ImplicitConversionSequence::Indistinguishable;
3642 
3643       Result = ImplicitConversionSequence::Worse;
3644     } else {
3645       // Qualifiers are disjoint.
3646       return ImplicitConversionSequence::Indistinguishable;
3647     }
3648 
3649     // If the types after this point are equivalent, we're done.
3650     if (S.Context.hasSameUnqualifiedType(T1, T2))
3651       break;
3652   }
3653 
3654   // Check that the winning standard conversion sequence isn't using
3655   // the deprecated string literal array to pointer conversion.
3656   switch (Result) {
3657   case ImplicitConversionSequence::Better:
3658     if (SCS1.DeprecatedStringLiteralToCharPtr)
3659       Result = ImplicitConversionSequence::Indistinguishable;
3660     break;
3661 
3662   case ImplicitConversionSequence::Indistinguishable:
3663     break;
3664 
3665   case ImplicitConversionSequence::Worse:
3666     if (SCS2.DeprecatedStringLiteralToCharPtr)
3667       Result = ImplicitConversionSequence::Indistinguishable;
3668     break;
3669   }
3670 
3671   return Result;
3672 }
3673 
3674 /// CompareDerivedToBaseConversions - Compares two standard conversion
3675 /// sequences to determine whether they can be ranked based on their
3676 /// various kinds of derived-to-base conversions (C++
3677 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3678 /// conversions between Objective-C interface types.
3679 ImplicitConversionSequence::CompareKind
3680 CompareDerivedToBaseConversions(Sema &S,
3681                                 const StandardConversionSequence& SCS1,
3682                                 const StandardConversionSequence& SCS2) {
3683   QualType FromType1 = SCS1.getFromType();
3684   QualType ToType1 = SCS1.getToType(1);
3685   QualType FromType2 = SCS2.getFromType();
3686   QualType ToType2 = SCS2.getToType(1);
3687 
3688   // Adjust the types we're converting from via the array-to-pointer
3689   // conversion, if we need to.
3690   if (SCS1.First == ICK_Array_To_Pointer)
3691     FromType1 = S.Context.getArrayDecayedType(FromType1);
3692   if (SCS2.First == ICK_Array_To_Pointer)
3693     FromType2 = S.Context.getArrayDecayedType(FromType2);
3694 
3695   // Canonicalize all of the types.
3696   FromType1 = S.Context.getCanonicalType(FromType1);
3697   ToType1 = S.Context.getCanonicalType(ToType1);
3698   FromType2 = S.Context.getCanonicalType(FromType2);
3699   ToType2 = S.Context.getCanonicalType(ToType2);
3700 
3701   // C++ [over.ics.rank]p4b3:
3702   //
3703   //   If class B is derived directly or indirectly from class A and
3704   //   class C is derived directly or indirectly from B,
3705   //
3706   // Compare based on pointer conversions.
3707   if (SCS1.Second == ICK_Pointer_Conversion &&
3708       SCS2.Second == ICK_Pointer_Conversion &&
3709       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3710       FromType1->isPointerType() && FromType2->isPointerType() &&
3711       ToType1->isPointerType() && ToType2->isPointerType()) {
3712     QualType FromPointee1
3713       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3714     QualType ToPointee1
3715       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3716     QualType FromPointee2
3717       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3718     QualType ToPointee2
3719       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3720 
3721     //   -- conversion of C* to B* is better than conversion of C* to A*,
3722     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3723       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3724         return ImplicitConversionSequence::Better;
3725       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3726         return ImplicitConversionSequence::Worse;
3727     }
3728 
3729     //   -- conversion of B* to A* is better than conversion of C* to A*,
3730     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3731       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3732         return ImplicitConversionSequence::Better;
3733       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3734         return ImplicitConversionSequence::Worse;
3735     }
3736   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3737              SCS2.Second == ICK_Pointer_Conversion) {
3738     const ObjCObjectPointerType *FromPtr1
3739       = FromType1->getAs<ObjCObjectPointerType>();
3740     const ObjCObjectPointerType *FromPtr2
3741       = FromType2->getAs<ObjCObjectPointerType>();
3742     const ObjCObjectPointerType *ToPtr1
3743       = ToType1->getAs<ObjCObjectPointerType>();
3744     const ObjCObjectPointerType *ToPtr2
3745       = ToType2->getAs<ObjCObjectPointerType>();
3746 
3747     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3748       // Apply the same conversion ranking rules for Objective-C pointer types
3749       // that we do for C++ pointers to class types. However, we employ the
3750       // Objective-C pseudo-subtyping relationship used for assignment of
3751       // Objective-C pointer types.
3752       bool FromAssignLeft
3753         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3754       bool FromAssignRight
3755         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3756       bool ToAssignLeft
3757         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3758       bool ToAssignRight
3759         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3760 
3761       // A conversion to an a non-id object pointer type or qualified 'id'
3762       // type is better than a conversion to 'id'.
3763       if (ToPtr1->isObjCIdType() &&
3764           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3765         return ImplicitConversionSequence::Worse;
3766       if (ToPtr2->isObjCIdType() &&
3767           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3768         return ImplicitConversionSequence::Better;
3769 
3770       // A conversion to a non-id object pointer type is better than a
3771       // conversion to a qualified 'id' type
3772       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3773         return ImplicitConversionSequence::Worse;
3774       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3775         return ImplicitConversionSequence::Better;
3776 
3777       // A conversion to an a non-Class object pointer type or qualified 'Class'
3778       // type is better than a conversion to 'Class'.
3779       if (ToPtr1->isObjCClassType() &&
3780           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3781         return ImplicitConversionSequence::Worse;
3782       if (ToPtr2->isObjCClassType() &&
3783           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3784         return ImplicitConversionSequence::Better;
3785 
3786       // A conversion to a non-Class object pointer type is better than a
3787       // conversion to a qualified 'Class' type.
3788       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3789         return ImplicitConversionSequence::Worse;
3790       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3791         return ImplicitConversionSequence::Better;
3792 
3793       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3794       if (S.Context.hasSameType(FromType1, FromType2) &&
3795           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3796           (ToAssignLeft != ToAssignRight))
3797         return ToAssignLeft? ImplicitConversionSequence::Worse
3798                            : ImplicitConversionSequence::Better;
3799 
3800       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3801       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3802           (FromAssignLeft != FromAssignRight))
3803         return FromAssignLeft? ImplicitConversionSequence::Better
3804         : ImplicitConversionSequence::Worse;
3805     }
3806   }
3807 
3808   // Ranking of member-pointer types.
3809   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3810       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3811       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3812     const MemberPointerType * FromMemPointer1 =
3813                                         FromType1->getAs<MemberPointerType>();
3814     const MemberPointerType * ToMemPointer1 =
3815                                           ToType1->getAs<MemberPointerType>();
3816     const MemberPointerType * FromMemPointer2 =
3817                                           FromType2->getAs<MemberPointerType>();
3818     const MemberPointerType * ToMemPointer2 =
3819                                           ToType2->getAs<MemberPointerType>();
3820     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3821     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3822     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3823     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3824     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3825     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3826     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3827     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3828     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3829     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3830       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3831         return ImplicitConversionSequence::Worse;
3832       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3833         return ImplicitConversionSequence::Better;
3834     }
3835     // conversion of B::* to C::* is better than conversion of A::* to C::*
3836     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3837       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3838         return ImplicitConversionSequence::Better;
3839       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3840         return ImplicitConversionSequence::Worse;
3841     }
3842   }
3843 
3844   if (SCS1.Second == ICK_Derived_To_Base) {
3845     //   -- conversion of C to B is better than conversion of C to A,
3846     //   -- binding of an expression of type C to a reference of type
3847     //      B& is better than binding an expression of type C to a
3848     //      reference of type A&,
3849     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3850         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3851       if (S.IsDerivedFrom(ToType1, ToType2))
3852         return ImplicitConversionSequence::Better;
3853       else if (S.IsDerivedFrom(ToType2, ToType1))
3854         return ImplicitConversionSequence::Worse;
3855     }
3856 
3857     //   -- conversion of B to A is better than conversion of C to A.
3858     //   -- binding of an expression of type B to a reference of type
3859     //      A& is better than binding an expression of type C to a
3860     //      reference of type A&,
3861     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3862         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3863       if (S.IsDerivedFrom(FromType2, FromType1))
3864         return ImplicitConversionSequence::Better;
3865       else if (S.IsDerivedFrom(FromType1, FromType2))
3866         return ImplicitConversionSequence::Worse;
3867     }
3868   }
3869 
3870   return ImplicitConversionSequence::Indistinguishable;
3871 }
3872 
3873 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3874 /// determine whether they are reference-related,
3875 /// reference-compatible, reference-compatible with added
3876 /// qualification, or incompatible, for use in C++ initialization by
3877 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3878 /// type, and the first type (T1) is the pointee type of the reference
3879 /// type being initialized.
3880 Sema::ReferenceCompareResult
3881 Sema::CompareReferenceRelationship(SourceLocation Loc,
3882                                    QualType OrigT1, QualType OrigT2,
3883                                    bool &DerivedToBase,
3884                                    bool &ObjCConversion,
3885                                    bool &ObjCLifetimeConversion) {
3886   assert(!OrigT1->isReferenceType() &&
3887     "T1 must be the pointee type of the reference type");
3888   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3889 
3890   QualType T1 = Context.getCanonicalType(OrigT1);
3891   QualType T2 = Context.getCanonicalType(OrigT2);
3892   Qualifiers T1Quals, T2Quals;
3893   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3894   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3895 
3896   // C++ [dcl.init.ref]p4:
3897   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3898   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3899   //   T1 is a base class of T2.
3900   DerivedToBase = false;
3901   ObjCConversion = false;
3902   ObjCLifetimeConversion = false;
3903   if (UnqualT1 == UnqualT2) {
3904     // Nothing to do.
3905   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3906            IsDerivedFrom(UnqualT2, UnqualT1))
3907     DerivedToBase = true;
3908   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3909            UnqualT2->isObjCObjectOrInterfaceType() &&
3910            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3911     ObjCConversion = true;
3912   else
3913     return Ref_Incompatible;
3914 
3915   // At this point, we know that T1 and T2 are reference-related (at
3916   // least).
3917 
3918   // If the type is an array type, promote the element qualifiers to the type
3919   // for comparison.
3920   if (isa<ArrayType>(T1) && T1Quals)
3921     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3922   if (isa<ArrayType>(T2) && T2Quals)
3923     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3924 
3925   // C++ [dcl.init.ref]p4:
3926   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3927   //   reference-related to T2 and cv1 is the same cv-qualification
3928   //   as, or greater cv-qualification than, cv2. For purposes of
3929   //   overload resolution, cases for which cv1 is greater
3930   //   cv-qualification than cv2 are identified as
3931   //   reference-compatible with added qualification (see 13.3.3.2).
3932   //
3933   // Note that we also require equivalence of Objective-C GC and address-space
3934   // qualifiers when performing these computations, so that e.g., an int in
3935   // address space 1 is not reference-compatible with an int in address
3936   // space 2.
3937   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3938       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3939     T1Quals.removeObjCLifetime();
3940     T2Quals.removeObjCLifetime();
3941     ObjCLifetimeConversion = true;
3942   }
3943 
3944   if (T1Quals == T2Quals)
3945     return Ref_Compatible;
3946   else if (T1Quals.compatiblyIncludes(T2Quals))
3947     return Ref_Compatible_With_Added_Qualification;
3948   else
3949     return Ref_Related;
3950 }
3951 
3952 /// \brief Look for a user-defined conversion to an value reference-compatible
3953 ///        with DeclType. Return true if something definite is found.
3954 static bool
3955 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3956                          QualType DeclType, SourceLocation DeclLoc,
3957                          Expr *Init, QualType T2, bool AllowRvalues,
3958                          bool AllowExplicit) {
3959   assert(T2->isRecordType() && "Can only find conversions of record types.");
3960   CXXRecordDecl *T2RecordDecl
3961     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3962 
3963   OverloadCandidateSet CandidateSet(DeclLoc);
3964   const UnresolvedSetImpl *Conversions
3965     = T2RecordDecl->getVisibleConversionFunctions();
3966   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3967          E = Conversions->end(); I != E; ++I) {
3968     NamedDecl *D = *I;
3969     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3970     if (isa<UsingShadowDecl>(D))
3971       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3972 
3973     FunctionTemplateDecl *ConvTemplate
3974       = dyn_cast<FunctionTemplateDecl>(D);
3975     CXXConversionDecl *Conv;
3976     if (ConvTemplate)
3977       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3978     else
3979       Conv = cast<CXXConversionDecl>(D);
3980 
3981     // If this is an explicit conversion, and we're not allowed to consider
3982     // explicit conversions, skip it.
3983     if (!AllowExplicit && Conv->isExplicit())
3984       continue;
3985 
3986     if (AllowRvalues) {
3987       bool DerivedToBase = false;
3988       bool ObjCConversion = false;
3989       bool ObjCLifetimeConversion = false;
3990 
3991       // If we are initializing an rvalue reference, don't permit conversion
3992       // functions that return lvalues.
3993       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3994         const ReferenceType *RefType
3995           = Conv->getConversionType()->getAs<LValueReferenceType>();
3996         if (RefType && !RefType->getPointeeType()->isFunctionType())
3997           continue;
3998       }
3999 
4000       if (!ConvTemplate &&
4001           S.CompareReferenceRelationship(
4002             DeclLoc,
4003             Conv->getConversionType().getNonReferenceType()
4004               .getUnqualifiedType(),
4005             DeclType.getNonReferenceType().getUnqualifiedType(),
4006             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4007           Sema::Ref_Incompatible)
4008         continue;
4009     } else {
4010       // If the conversion function doesn't return a reference type,
4011       // it can't be considered for this conversion. An rvalue reference
4012       // is only acceptable if its referencee is a function type.
4013 
4014       const ReferenceType *RefType =
4015         Conv->getConversionType()->getAs<ReferenceType>();
4016       if (!RefType ||
4017           (!RefType->isLValueReferenceType() &&
4018            !RefType->getPointeeType()->isFunctionType()))
4019         continue;
4020     }
4021 
4022     if (ConvTemplate)
4023       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4024                                        Init, DeclType, CandidateSet);
4025     else
4026       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4027                                DeclType, CandidateSet);
4028   }
4029 
4030   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4031 
4032   OverloadCandidateSet::iterator Best;
4033   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4034   case OR_Success:
4035     // C++ [over.ics.ref]p1:
4036     //
4037     //   [...] If the parameter binds directly to the result of
4038     //   applying a conversion function to the argument
4039     //   expression, the implicit conversion sequence is a
4040     //   user-defined conversion sequence (13.3.3.1.2), with the
4041     //   second standard conversion sequence either an identity
4042     //   conversion or, if the conversion function returns an
4043     //   entity of a type that is a derived class of the parameter
4044     //   type, a derived-to-base Conversion.
4045     if (!Best->FinalConversion.DirectBinding)
4046       return false;
4047 
4048     if (Best->Function)
4049       S.MarkFunctionReferenced(DeclLoc, Best->Function);
4050     ICS.setUserDefined();
4051     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4052     ICS.UserDefined.After = Best->FinalConversion;
4053     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4054     ICS.UserDefined.ConversionFunction = Best->Function;
4055     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4056     ICS.UserDefined.EllipsisConversion = false;
4057     assert(ICS.UserDefined.After.ReferenceBinding &&
4058            ICS.UserDefined.After.DirectBinding &&
4059            "Expected a direct reference binding!");
4060     return true;
4061 
4062   case OR_Ambiguous:
4063     ICS.setAmbiguous();
4064     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4065          Cand != CandidateSet.end(); ++Cand)
4066       if (Cand->Viable)
4067         ICS.Ambiguous.addConversion(Cand->Function);
4068     return true;
4069 
4070   case OR_No_Viable_Function:
4071   case OR_Deleted:
4072     // There was no suitable conversion, or we found a deleted
4073     // conversion; continue with other checks.
4074     return false;
4075   }
4076 
4077   llvm_unreachable("Invalid OverloadResult!");
4078 }
4079 
4080 /// \brief Compute an implicit conversion sequence for reference
4081 /// initialization.
4082 static ImplicitConversionSequence
4083 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4084                  SourceLocation DeclLoc,
4085                  bool SuppressUserConversions,
4086                  bool AllowExplicit) {
4087   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4088 
4089   // Most paths end in a failed conversion.
4090   ImplicitConversionSequence ICS;
4091   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4092 
4093   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4094   QualType T2 = Init->getType();
4095 
4096   // If the initializer is the address of an overloaded function, try
4097   // to resolve the overloaded function. If all goes well, T2 is the
4098   // type of the resulting function.
4099   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4100     DeclAccessPair Found;
4101     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4102                                                                 false, Found))
4103       T2 = Fn->getType();
4104   }
4105 
4106   // Compute some basic properties of the types and the initializer.
4107   bool isRValRef = DeclType->isRValueReferenceType();
4108   bool DerivedToBase = false;
4109   bool ObjCConversion = false;
4110   bool ObjCLifetimeConversion = false;
4111   Expr::Classification InitCategory = Init->Classify(S.Context);
4112   Sema::ReferenceCompareResult RefRelationship
4113     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4114                                      ObjCConversion, ObjCLifetimeConversion);
4115 
4116 
4117   // C++0x [dcl.init.ref]p5:
4118   //   A reference to type "cv1 T1" is initialized by an expression
4119   //   of type "cv2 T2" as follows:
4120 
4121   //     -- If reference is an lvalue reference and the initializer expression
4122   if (!isRValRef) {
4123     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4124     //        reference-compatible with "cv2 T2," or
4125     //
4126     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4127     if (InitCategory.isLValue() &&
4128         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4129       // C++ [over.ics.ref]p1:
4130       //   When a parameter of reference type binds directly (8.5.3)
4131       //   to an argument expression, the implicit conversion sequence
4132       //   is the identity conversion, unless the argument expression
4133       //   has a type that is a derived class of the parameter type,
4134       //   in which case the implicit conversion sequence is a
4135       //   derived-to-base Conversion (13.3.3.1).
4136       ICS.setStandard();
4137       ICS.Standard.First = ICK_Identity;
4138       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4139                          : ObjCConversion? ICK_Compatible_Conversion
4140                          : ICK_Identity;
4141       ICS.Standard.Third = ICK_Identity;
4142       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4143       ICS.Standard.setToType(0, T2);
4144       ICS.Standard.setToType(1, T1);
4145       ICS.Standard.setToType(2, T1);
4146       ICS.Standard.ReferenceBinding = true;
4147       ICS.Standard.DirectBinding = true;
4148       ICS.Standard.IsLvalueReference = !isRValRef;
4149       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4150       ICS.Standard.BindsToRvalue = false;
4151       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4152       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4153       ICS.Standard.CopyConstructor = 0;
4154 
4155       // Nothing more to do: the inaccessibility/ambiguity check for
4156       // derived-to-base conversions is suppressed when we're
4157       // computing the implicit conversion sequence (C++
4158       // [over.best.ics]p2).
4159       return ICS;
4160     }
4161 
4162     //       -- has a class type (i.e., T2 is a class type), where T1 is
4163     //          not reference-related to T2, and can be implicitly
4164     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4165     //          is reference-compatible with "cv3 T3" 92) (this
4166     //          conversion is selected by enumerating the applicable
4167     //          conversion functions (13.3.1.6) and choosing the best
4168     //          one through overload resolution (13.3)),
4169     if (!SuppressUserConversions && T2->isRecordType() &&
4170         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4171         RefRelationship == Sema::Ref_Incompatible) {
4172       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4173                                    Init, T2, /*AllowRvalues=*/false,
4174                                    AllowExplicit))
4175         return ICS;
4176     }
4177   }
4178 
4179   //     -- Otherwise, the reference shall be an lvalue reference to a
4180   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4181   //        shall be an rvalue reference.
4182   //
4183   // We actually handle one oddity of C++ [over.ics.ref] at this
4184   // point, which is that, due to p2 (which short-circuits reference
4185   // binding by only attempting a simple conversion for non-direct
4186   // bindings) and p3's strange wording, we allow a const volatile
4187   // reference to bind to an rvalue. Hence the check for the presence
4188   // of "const" rather than checking for "const" being the only
4189   // qualifier.
4190   // This is also the point where rvalue references and lvalue inits no longer
4191   // go together.
4192   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4193     return ICS;
4194 
4195   //       -- If the initializer expression
4196   //
4197   //            -- is an xvalue, class prvalue, array prvalue or function
4198   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4199   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4200       (InitCategory.isXValue() ||
4201       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4202       (InitCategory.isLValue() && T2->isFunctionType()))) {
4203     ICS.setStandard();
4204     ICS.Standard.First = ICK_Identity;
4205     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4206                       : ObjCConversion? ICK_Compatible_Conversion
4207                       : ICK_Identity;
4208     ICS.Standard.Third = ICK_Identity;
4209     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4210     ICS.Standard.setToType(0, T2);
4211     ICS.Standard.setToType(1, T1);
4212     ICS.Standard.setToType(2, T1);
4213     ICS.Standard.ReferenceBinding = true;
4214     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4215     // binding unless we're binding to a class prvalue.
4216     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4217     // allow the use of rvalue references in C++98/03 for the benefit of
4218     // standard library implementors; therefore, we need the xvalue check here.
4219     ICS.Standard.DirectBinding =
4220       S.getLangOpts().CPlusPlus0x ||
4221       (InitCategory.isPRValue() && !T2->isRecordType());
4222     ICS.Standard.IsLvalueReference = !isRValRef;
4223     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4224     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4225     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4226     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4227     ICS.Standard.CopyConstructor = 0;
4228     return ICS;
4229   }
4230 
4231   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4232   //               reference-related to T2, and can be implicitly converted to
4233   //               an xvalue, class prvalue, or function lvalue of type
4234   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4235   //               "cv3 T3",
4236   //
4237   //          then the reference is bound to the value of the initializer
4238   //          expression in the first case and to the result of the conversion
4239   //          in the second case (or, in either case, to an appropriate base
4240   //          class subobject).
4241   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4242       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4243       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4244                                Init, T2, /*AllowRvalues=*/true,
4245                                AllowExplicit)) {
4246     // In the second case, if the reference is an rvalue reference
4247     // and the second standard conversion sequence of the
4248     // user-defined conversion sequence includes an lvalue-to-rvalue
4249     // conversion, the program is ill-formed.
4250     if (ICS.isUserDefined() && isRValRef &&
4251         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4252       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4253 
4254     return ICS;
4255   }
4256 
4257   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4258   //          initialized from the initializer expression using the
4259   //          rules for a non-reference copy initialization (8.5). The
4260   //          reference is then bound to the temporary. If T1 is
4261   //          reference-related to T2, cv1 must be the same
4262   //          cv-qualification as, or greater cv-qualification than,
4263   //          cv2; otherwise, the program is ill-formed.
4264   if (RefRelationship == Sema::Ref_Related) {
4265     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4266     // we would be reference-compatible or reference-compatible with
4267     // added qualification. But that wasn't the case, so the reference
4268     // initialization fails.
4269     //
4270     // Note that we only want to check address spaces and cvr-qualifiers here.
4271     // ObjC GC and lifetime qualifiers aren't important.
4272     Qualifiers T1Quals = T1.getQualifiers();
4273     Qualifiers T2Quals = T2.getQualifiers();
4274     T1Quals.removeObjCGCAttr();
4275     T1Quals.removeObjCLifetime();
4276     T2Quals.removeObjCGCAttr();
4277     T2Quals.removeObjCLifetime();
4278     if (!T1Quals.compatiblyIncludes(T2Quals))
4279       return ICS;
4280   }
4281 
4282   // If at least one of the types is a class type, the types are not
4283   // related, and we aren't allowed any user conversions, the
4284   // reference binding fails. This case is important for breaking
4285   // recursion, since TryImplicitConversion below will attempt to
4286   // create a temporary through the use of a copy constructor.
4287   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4288       (T1->isRecordType() || T2->isRecordType()))
4289     return ICS;
4290 
4291   // If T1 is reference-related to T2 and the reference is an rvalue
4292   // reference, the initializer expression shall not be an lvalue.
4293   if (RefRelationship >= Sema::Ref_Related &&
4294       isRValRef && Init->Classify(S.Context).isLValue())
4295     return ICS;
4296 
4297   // C++ [over.ics.ref]p2:
4298   //   When a parameter of reference type is not bound directly to
4299   //   an argument expression, the conversion sequence is the one
4300   //   required to convert the argument expression to the
4301   //   underlying type of the reference according to
4302   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4303   //   to copy-initializing a temporary of the underlying type with
4304   //   the argument expression. Any difference in top-level
4305   //   cv-qualification is subsumed by the initialization itself
4306   //   and does not constitute a conversion.
4307   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4308                               /*AllowExplicit=*/false,
4309                               /*InOverloadResolution=*/false,
4310                               /*CStyle=*/false,
4311                               /*AllowObjCWritebackConversion=*/false);
4312 
4313   // Of course, that's still a reference binding.
4314   if (ICS.isStandard()) {
4315     ICS.Standard.ReferenceBinding = true;
4316     ICS.Standard.IsLvalueReference = !isRValRef;
4317     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4318     ICS.Standard.BindsToRvalue = true;
4319     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4320     ICS.Standard.ObjCLifetimeConversionBinding = false;
4321   } else if (ICS.isUserDefined()) {
4322     // Don't allow rvalue references to bind to lvalues.
4323     if (DeclType->isRValueReferenceType()) {
4324       if (const ReferenceType *RefType
4325             = ICS.UserDefined.ConversionFunction->getResultType()
4326                 ->getAs<LValueReferenceType>()) {
4327         if (!RefType->getPointeeType()->isFunctionType()) {
4328           ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4329                      DeclType);
4330           return ICS;
4331         }
4332       }
4333     }
4334 
4335     ICS.UserDefined.After.ReferenceBinding = true;
4336     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4337     ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4338     ICS.UserDefined.After.BindsToRvalue = true;
4339     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4340     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4341   }
4342 
4343   return ICS;
4344 }
4345 
4346 static ImplicitConversionSequence
4347 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4348                       bool SuppressUserConversions,
4349                       bool InOverloadResolution,
4350                       bool AllowObjCWritebackConversion,
4351                       bool AllowExplicit = false);
4352 
4353 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4354 /// initializer list From.
4355 static ImplicitConversionSequence
4356 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4357                   bool SuppressUserConversions,
4358                   bool InOverloadResolution,
4359                   bool AllowObjCWritebackConversion) {
4360   // C++11 [over.ics.list]p1:
4361   //   When an argument is an initializer list, it is not an expression and
4362   //   special rules apply for converting it to a parameter type.
4363 
4364   ImplicitConversionSequence Result;
4365   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4366   Result.setListInitializationSequence();
4367 
4368   // We need a complete type for what follows. Incomplete types can never be
4369   // initialized from init lists.
4370   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4371     return Result;
4372 
4373   // C++11 [over.ics.list]p2:
4374   //   If the parameter type is std::initializer_list<X> or "array of X" and
4375   //   all the elements can be implicitly converted to X, the implicit
4376   //   conversion sequence is the worst conversion necessary to convert an
4377   //   element of the list to X.
4378   bool toStdInitializerList = false;
4379   QualType X;
4380   if (ToType->isArrayType())
4381     X = S.Context.getBaseElementType(ToType);
4382   else
4383     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4384   if (!X.isNull()) {
4385     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4386       Expr *Init = From->getInit(i);
4387       ImplicitConversionSequence ICS =
4388           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4389                                 InOverloadResolution,
4390                                 AllowObjCWritebackConversion);
4391       // If a single element isn't convertible, fail.
4392       if (ICS.isBad()) {
4393         Result = ICS;
4394         break;
4395       }
4396       // Otherwise, look for the worst conversion.
4397       if (Result.isBad() ||
4398           CompareImplicitConversionSequences(S, ICS, Result) ==
4399               ImplicitConversionSequence::Worse)
4400         Result = ICS;
4401     }
4402 
4403     // For an empty list, we won't have computed any conversion sequence.
4404     // Introduce the identity conversion sequence.
4405     if (From->getNumInits() == 0) {
4406       Result.setStandard();
4407       Result.Standard.setAsIdentityConversion();
4408       Result.Standard.setFromType(ToType);
4409       Result.Standard.setAllToTypes(ToType);
4410     }
4411 
4412     Result.setListInitializationSequence();
4413     Result.setStdInitializerListElement(toStdInitializerList);
4414     return Result;
4415   }
4416 
4417   // C++11 [over.ics.list]p3:
4418   //   Otherwise, if the parameter is a non-aggregate class X and overload
4419   //   resolution chooses a single best constructor [...] the implicit
4420   //   conversion sequence is a user-defined conversion sequence. If multiple
4421   //   constructors are viable but none is better than the others, the
4422   //   implicit conversion sequence is a user-defined conversion sequence.
4423   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4424     // This function can deal with initializer lists.
4425     Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4426                                       /*AllowExplicit=*/false,
4427                                       InOverloadResolution, /*CStyle=*/false,
4428                                       AllowObjCWritebackConversion);
4429     Result.setListInitializationSequence();
4430     return Result;
4431   }
4432 
4433   // C++11 [over.ics.list]p4:
4434   //   Otherwise, if the parameter has an aggregate type which can be
4435   //   initialized from the initializer list [...] the implicit conversion
4436   //   sequence is a user-defined conversion sequence.
4437   if (ToType->isAggregateType()) {
4438     // Type is an aggregate, argument is an init list. At this point it comes
4439     // down to checking whether the initialization works.
4440     // FIXME: Find out whether this parameter is consumed or not.
4441     InitializedEntity Entity =
4442         InitializedEntity::InitializeParameter(S.Context, ToType,
4443                                                /*Consumed=*/false);
4444     if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4445       Result.setUserDefined();
4446       Result.UserDefined.Before.setAsIdentityConversion();
4447       // Initializer lists don't have a type.
4448       Result.UserDefined.Before.setFromType(QualType());
4449       Result.UserDefined.Before.setAllToTypes(QualType());
4450 
4451       Result.UserDefined.After.setAsIdentityConversion();
4452       Result.UserDefined.After.setFromType(ToType);
4453       Result.UserDefined.After.setAllToTypes(ToType);
4454       Result.UserDefined.ConversionFunction = 0;
4455     }
4456     return Result;
4457   }
4458 
4459   // C++11 [over.ics.list]p5:
4460   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4461   if (ToType->isReferenceType()) {
4462     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4463     // mention initializer lists in any way. So we go by what list-
4464     // initialization would do and try to extrapolate from that.
4465 
4466     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4467 
4468     // If the initializer list has a single element that is reference-related
4469     // to the parameter type, we initialize the reference from that.
4470     if (From->getNumInits() == 1) {
4471       Expr *Init = From->getInit(0);
4472 
4473       QualType T2 = Init->getType();
4474 
4475       // If the initializer is the address of an overloaded function, try
4476       // to resolve the overloaded function. If all goes well, T2 is the
4477       // type of the resulting function.
4478       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4479         DeclAccessPair Found;
4480         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4481                                    Init, ToType, false, Found))
4482           T2 = Fn->getType();
4483       }
4484 
4485       // Compute some basic properties of the types and the initializer.
4486       bool dummy1 = false;
4487       bool dummy2 = false;
4488       bool dummy3 = false;
4489       Sema::ReferenceCompareResult RefRelationship
4490         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4491                                          dummy2, dummy3);
4492 
4493       if (RefRelationship >= Sema::Ref_Related)
4494         return TryReferenceInit(S, Init, ToType,
4495                                 /*FIXME:*/From->getLocStart(),
4496                                 SuppressUserConversions,
4497                                 /*AllowExplicit=*/false);
4498     }
4499 
4500     // Otherwise, we bind the reference to a temporary created from the
4501     // initializer list.
4502     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4503                                InOverloadResolution,
4504                                AllowObjCWritebackConversion);
4505     if (Result.isFailure())
4506       return Result;
4507     assert(!Result.isEllipsis() &&
4508            "Sub-initialization cannot result in ellipsis conversion.");
4509 
4510     // Can we even bind to a temporary?
4511     if (ToType->isRValueReferenceType() ||
4512         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4513       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4514                                             Result.UserDefined.After;
4515       SCS.ReferenceBinding = true;
4516       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4517       SCS.BindsToRvalue = true;
4518       SCS.BindsToFunctionLvalue = false;
4519       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4520       SCS.ObjCLifetimeConversionBinding = false;
4521     } else
4522       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4523                     From, ToType);
4524     return Result;
4525   }
4526 
4527   // C++11 [over.ics.list]p6:
4528   //   Otherwise, if the parameter type is not a class:
4529   if (!ToType->isRecordType()) {
4530     //    - if the initializer list has one element, the implicit conversion
4531     //      sequence is the one required to convert the element to the
4532     //      parameter type.
4533     unsigned NumInits = From->getNumInits();
4534     if (NumInits == 1)
4535       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4536                                      SuppressUserConversions,
4537                                      InOverloadResolution,
4538                                      AllowObjCWritebackConversion);
4539     //    - if the initializer list has no elements, the implicit conversion
4540     //      sequence is the identity conversion.
4541     else if (NumInits == 0) {
4542       Result.setStandard();
4543       Result.Standard.setAsIdentityConversion();
4544       Result.Standard.setFromType(ToType);
4545       Result.Standard.setAllToTypes(ToType);
4546     }
4547     Result.setListInitializationSequence();
4548     return Result;
4549   }
4550 
4551   // C++11 [over.ics.list]p7:
4552   //   In all cases other than those enumerated above, no conversion is possible
4553   return Result;
4554 }
4555 
4556 /// TryCopyInitialization - Try to copy-initialize a value of type
4557 /// ToType from the expression From. Return the implicit conversion
4558 /// sequence required to pass this argument, which may be a bad
4559 /// conversion sequence (meaning that the argument cannot be passed to
4560 /// a parameter of this type). If @p SuppressUserConversions, then we
4561 /// do not permit any user-defined conversion sequences.
4562 static ImplicitConversionSequence
4563 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4564                       bool SuppressUserConversions,
4565                       bool InOverloadResolution,
4566                       bool AllowObjCWritebackConversion,
4567                       bool AllowExplicit) {
4568   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4569     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4570                              InOverloadResolution,AllowObjCWritebackConversion);
4571 
4572   if (ToType->isReferenceType())
4573     return TryReferenceInit(S, From, ToType,
4574                             /*FIXME:*/From->getLocStart(),
4575                             SuppressUserConversions,
4576                             AllowExplicit);
4577 
4578   return TryImplicitConversion(S, From, ToType,
4579                                SuppressUserConversions,
4580                                /*AllowExplicit=*/false,
4581                                InOverloadResolution,
4582                                /*CStyle=*/false,
4583                                AllowObjCWritebackConversion);
4584 }
4585 
4586 static bool TryCopyInitialization(const CanQualType FromQTy,
4587                                   const CanQualType ToQTy,
4588                                   Sema &S,
4589                                   SourceLocation Loc,
4590                                   ExprValueKind FromVK) {
4591   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4592   ImplicitConversionSequence ICS =
4593     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4594 
4595   return !ICS.isBad();
4596 }
4597 
4598 /// TryObjectArgumentInitialization - Try to initialize the object
4599 /// parameter of the given member function (@c Method) from the
4600 /// expression @p From.
4601 static ImplicitConversionSequence
4602 TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
4603                                 Expr::Classification FromClassification,
4604                                 CXXMethodDecl *Method,
4605                                 CXXRecordDecl *ActingContext) {
4606   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4607   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4608   //                 const volatile object.
4609   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4610     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4611   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4612 
4613   // Set up the conversion sequence as a "bad" conversion, to allow us
4614   // to exit early.
4615   ImplicitConversionSequence ICS;
4616 
4617   // We need to have an object of class type.
4618   QualType FromType = OrigFromType;
4619   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4620     FromType = PT->getPointeeType();
4621 
4622     // When we had a pointer, it's implicitly dereferenced, so we
4623     // better have an lvalue.
4624     assert(FromClassification.isLValue());
4625   }
4626 
4627   assert(FromType->isRecordType());
4628 
4629   // C++0x [over.match.funcs]p4:
4630   //   For non-static member functions, the type of the implicit object
4631   //   parameter is
4632   //
4633   //     - "lvalue reference to cv X" for functions declared without a
4634   //        ref-qualifier or with the & ref-qualifier
4635   //     - "rvalue reference to cv X" for functions declared with the &&
4636   //        ref-qualifier
4637   //
4638   // where X is the class of which the function is a member and cv is the
4639   // cv-qualification on the member function declaration.
4640   //
4641   // However, when finding an implicit conversion sequence for the argument, we
4642   // are not allowed to create temporaries or perform user-defined conversions
4643   // (C++ [over.match.funcs]p5). We perform a simplified version of
4644   // reference binding here, that allows class rvalues to bind to
4645   // non-constant references.
4646 
4647   // First check the qualifiers.
4648   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4649   if (ImplicitParamType.getCVRQualifiers()
4650                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4651       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4652     ICS.setBad(BadConversionSequence::bad_qualifiers,
4653                OrigFromType, ImplicitParamType);
4654     return ICS;
4655   }
4656 
4657   // Check that we have either the same type or a derived type. It
4658   // affects the conversion rank.
4659   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4660   ImplicitConversionKind SecondKind;
4661   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4662     SecondKind = ICK_Identity;
4663   } else if (S.IsDerivedFrom(FromType, ClassType))
4664     SecondKind = ICK_Derived_To_Base;
4665   else {
4666     ICS.setBad(BadConversionSequence::unrelated_class,
4667                FromType, ImplicitParamType);
4668     return ICS;
4669   }
4670 
4671   // Check the ref-qualifier.
4672   switch (Method->getRefQualifier()) {
4673   case RQ_None:
4674     // Do nothing; we don't care about lvalueness or rvalueness.
4675     break;
4676 
4677   case RQ_LValue:
4678     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4679       // non-const lvalue reference cannot bind to an rvalue
4680       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4681                  ImplicitParamType);
4682       return ICS;
4683     }
4684     break;
4685 
4686   case RQ_RValue:
4687     if (!FromClassification.isRValue()) {
4688       // rvalue reference cannot bind to an lvalue
4689       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4690                  ImplicitParamType);
4691       return ICS;
4692     }
4693     break;
4694   }
4695 
4696   // Success. Mark this as a reference binding.
4697   ICS.setStandard();
4698   ICS.Standard.setAsIdentityConversion();
4699   ICS.Standard.Second = SecondKind;
4700   ICS.Standard.setFromType(FromType);
4701   ICS.Standard.setAllToTypes(ImplicitParamType);
4702   ICS.Standard.ReferenceBinding = true;
4703   ICS.Standard.DirectBinding = true;
4704   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4705   ICS.Standard.BindsToFunctionLvalue = false;
4706   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4707   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4708     = (Method->getRefQualifier() == RQ_None);
4709   return ICS;
4710 }
4711 
4712 /// PerformObjectArgumentInitialization - Perform initialization of
4713 /// the implicit object parameter for the given Method with the given
4714 /// expression.
4715 ExprResult
4716 Sema::PerformObjectArgumentInitialization(Expr *From,
4717                                           NestedNameSpecifier *Qualifier,
4718                                           NamedDecl *FoundDecl,
4719                                           CXXMethodDecl *Method) {
4720   QualType FromRecordType, DestType;
4721   QualType ImplicitParamRecordType  =
4722     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4723 
4724   Expr::Classification FromClassification;
4725   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4726     FromRecordType = PT->getPointeeType();
4727     DestType = Method->getThisType(Context);
4728     FromClassification = Expr::Classification::makeSimpleLValue();
4729   } else {
4730     FromRecordType = From->getType();
4731     DestType = ImplicitParamRecordType;
4732     FromClassification = From->Classify(Context);
4733   }
4734 
4735   // Note that we always use the true parent context when performing
4736   // the actual argument initialization.
4737   ImplicitConversionSequence ICS
4738     = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4739                                       Method, Method->getParent());
4740   if (ICS.isBad()) {
4741     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4742       Qualifiers FromQs = FromRecordType.getQualifiers();
4743       Qualifiers ToQs = DestType.getQualifiers();
4744       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4745       if (CVR) {
4746         Diag(From->getLocStart(),
4747              diag::err_member_function_call_bad_cvr)
4748           << Method->getDeclName() << FromRecordType << (CVR - 1)
4749           << From->getSourceRange();
4750         Diag(Method->getLocation(), diag::note_previous_decl)
4751           << Method->getDeclName();
4752         return ExprError();
4753       }
4754     }
4755 
4756     return Diag(From->getLocStart(),
4757                 diag::err_implicit_object_parameter_init)
4758        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4759   }
4760 
4761   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4762     ExprResult FromRes =
4763       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4764     if (FromRes.isInvalid())
4765       return ExprError();
4766     From = FromRes.take();
4767   }
4768 
4769   if (!Context.hasSameType(From->getType(), DestType))
4770     From = ImpCastExprToType(From, DestType, CK_NoOp,
4771                              From->getValueKind()).take();
4772   return Owned(From);
4773 }
4774 
4775 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4776 /// expression From to bool (C++0x [conv]p3).
4777 static ImplicitConversionSequence
4778 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4779   // FIXME: This is pretty broken.
4780   return TryImplicitConversion(S, From, S.Context.BoolTy,
4781                                // FIXME: Are these flags correct?
4782                                /*SuppressUserConversions=*/false,
4783                                /*AllowExplicit=*/true,
4784                                /*InOverloadResolution=*/false,
4785                                /*CStyle=*/false,
4786                                /*AllowObjCWritebackConversion=*/false);
4787 }
4788 
4789 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4790 /// of the expression From to bool (C++0x [conv]p3).
4791 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4792   if (checkPlaceholderForOverload(*this, From))
4793     return ExprError();
4794 
4795   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4796   if (!ICS.isBad())
4797     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4798 
4799   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4800     return Diag(From->getLocStart(),
4801                 diag::err_typecheck_bool_condition)
4802                   << From->getType() << From->getSourceRange();
4803   return ExprError();
4804 }
4805 
4806 /// Check that the specified conversion is permitted in a converted constant
4807 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4808 /// is acceptable.
4809 static bool CheckConvertedConstantConversions(Sema &S,
4810                                               StandardConversionSequence &SCS) {
4811   // Since we know that the target type is an integral or unscoped enumeration
4812   // type, most conversion kinds are impossible. All possible First and Third
4813   // conversions are fine.
4814   switch (SCS.Second) {
4815   case ICK_Identity:
4816   case ICK_Integral_Promotion:
4817   case ICK_Integral_Conversion:
4818     return true;
4819 
4820   case ICK_Boolean_Conversion:
4821     // Conversion from an integral or unscoped enumeration type to bool is
4822     // classified as ICK_Boolean_Conversion, but it's also an integral
4823     // conversion, so it's permitted in a converted constant expression.
4824     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4825            SCS.getToType(2)->isBooleanType();
4826 
4827   case ICK_Floating_Integral:
4828   case ICK_Complex_Real:
4829     return false;
4830 
4831   case ICK_Lvalue_To_Rvalue:
4832   case ICK_Array_To_Pointer:
4833   case ICK_Function_To_Pointer:
4834   case ICK_NoReturn_Adjustment:
4835   case ICK_Qualification:
4836   case ICK_Compatible_Conversion:
4837   case ICK_Vector_Conversion:
4838   case ICK_Vector_Splat:
4839   case ICK_Derived_To_Base:
4840   case ICK_Pointer_Conversion:
4841   case ICK_Pointer_Member:
4842   case ICK_Block_Pointer_Conversion:
4843   case ICK_Writeback_Conversion:
4844   case ICK_Floating_Promotion:
4845   case ICK_Complex_Promotion:
4846   case ICK_Complex_Conversion:
4847   case ICK_Floating_Conversion:
4848   case ICK_TransparentUnionConversion:
4849     llvm_unreachable("unexpected second conversion kind");
4850 
4851   case ICK_Num_Conversion_Kinds:
4852     break;
4853   }
4854 
4855   llvm_unreachable("unknown conversion kind");
4856 }
4857 
4858 /// CheckConvertedConstantExpression - Check that the expression From is a
4859 /// converted constant expression of type T, perform the conversion and produce
4860 /// the converted expression, per C++11 [expr.const]p3.
4861 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4862                                                   llvm::APSInt &Value,
4863                                                   CCEKind CCE) {
4864   assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4865   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4866 
4867   if (checkPlaceholderForOverload(*this, From))
4868     return ExprError();
4869 
4870   // C++11 [expr.const]p3 with proposed wording fixes:
4871   //  A converted constant expression of type T is a core constant expression,
4872   //  implicitly converted to a prvalue of type T, where the converted
4873   //  expression is a literal constant expression and the implicit conversion
4874   //  sequence contains only user-defined conversions, lvalue-to-rvalue
4875   //  conversions, integral promotions, and integral conversions other than
4876   //  narrowing conversions.
4877   ImplicitConversionSequence ICS =
4878     TryImplicitConversion(From, T,
4879                           /*SuppressUserConversions=*/false,
4880                           /*AllowExplicit=*/false,
4881                           /*InOverloadResolution=*/false,
4882                           /*CStyle=*/false,
4883                           /*AllowObjcWritebackConversion=*/false);
4884   StandardConversionSequence *SCS = 0;
4885   switch (ICS.getKind()) {
4886   case ImplicitConversionSequence::StandardConversion:
4887     if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4888       return Diag(From->getLocStart(),
4889                   diag::err_typecheck_converted_constant_expression_disallowed)
4890                << From->getType() << From->getSourceRange() << T;
4891     SCS = &ICS.Standard;
4892     break;
4893   case ImplicitConversionSequence::UserDefinedConversion:
4894     // We are converting from class type to an integral or enumeration type, so
4895     // the Before sequence must be trivial.
4896     if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4897       return Diag(From->getLocStart(),
4898                   diag::err_typecheck_converted_constant_expression_disallowed)
4899                << From->getType() << From->getSourceRange() << T;
4900     SCS = &ICS.UserDefined.After;
4901     break;
4902   case ImplicitConversionSequence::AmbiguousConversion:
4903   case ImplicitConversionSequence::BadConversion:
4904     if (!DiagnoseMultipleUserDefinedConversion(From, T))
4905       return Diag(From->getLocStart(),
4906                   diag::err_typecheck_converted_constant_expression)
4907                     << From->getType() << From->getSourceRange() << T;
4908     return ExprError();
4909 
4910   case ImplicitConversionSequence::EllipsisConversion:
4911     llvm_unreachable("ellipsis conversion in converted constant expression");
4912   }
4913 
4914   ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4915   if (Result.isInvalid())
4916     return Result;
4917 
4918   // Check for a narrowing implicit conversion.
4919   APValue PreNarrowingValue;
4920   QualType PreNarrowingType;
4921   switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4922                                 PreNarrowingType)) {
4923   case NK_Variable_Narrowing:
4924     // Implicit conversion to a narrower type, and the value is not a constant
4925     // expression. We'll diagnose this in a moment.
4926   case NK_Not_Narrowing:
4927     break;
4928 
4929   case NK_Constant_Narrowing:
4930     Diag(From->getLocStart(),
4931          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4932                              diag::err_cce_narrowing)
4933       << CCE << /*Constant*/1
4934       << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
4935     break;
4936 
4937   case NK_Type_Narrowing:
4938     Diag(From->getLocStart(),
4939          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4940                              diag::err_cce_narrowing)
4941       << CCE << /*Constant*/0 << From->getType() << T;
4942     break;
4943   }
4944 
4945   // Check the expression is a constant expression.
4946   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4947   Expr::EvalResult Eval;
4948   Eval.Diag = &Notes;
4949 
4950   if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4951     // The expression can't be folded, so we can't keep it at this position in
4952     // the AST.
4953     Result = ExprError();
4954   } else {
4955     Value = Eval.Val.getInt();
4956 
4957     if (Notes.empty()) {
4958       // It's a constant expression.
4959       return Result;
4960     }
4961   }
4962 
4963   // It's not a constant expression. Produce an appropriate diagnostic.
4964   if (Notes.size() == 1 &&
4965       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4966     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4967   else {
4968     Diag(From->getLocStart(), diag::err_expr_not_cce)
4969       << CCE << From->getSourceRange();
4970     for (unsigned I = 0; I < Notes.size(); ++I)
4971       Diag(Notes[I].first, Notes[I].second);
4972   }
4973   return Result;
4974 }
4975 
4976 /// dropPointerConversions - If the given standard conversion sequence
4977 /// involves any pointer conversions, remove them.  This may change
4978 /// the result type of the conversion sequence.
4979 static void dropPointerConversion(StandardConversionSequence &SCS) {
4980   if (SCS.Second == ICK_Pointer_Conversion) {
4981     SCS.Second = ICK_Identity;
4982     SCS.Third = ICK_Identity;
4983     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4984   }
4985 }
4986 
4987 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
4988 /// convert the expression From to an Objective-C pointer type.
4989 static ImplicitConversionSequence
4990 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4991   // Do an implicit conversion to 'id'.
4992   QualType Ty = S.Context.getObjCIdType();
4993   ImplicitConversionSequence ICS
4994     = TryImplicitConversion(S, From, Ty,
4995                             // FIXME: Are these flags correct?
4996                             /*SuppressUserConversions=*/false,
4997                             /*AllowExplicit=*/true,
4998                             /*InOverloadResolution=*/false,
4999                             /*CStyle=*/false,
5000                             /*AllowObjCWritebackConversion=*/false);
5001 
5002   // Strip off any final conversions to 'id'.
5003   switch (ICS.getKind()) {
5004   case ImplicitConversionSequence::BadConversion:
5005   case ImplicitConversionSequence::AmbiguousConversion:
5006   case ImplicitConversionSequence::EllipsisConversion:
5007     break;
5008 
5009   case ImplicitConversionSequence::UserDefinedConversion:
5010     dropPointerConversion(ICS.UserDefined.After);
5011     break;
5012 
5013   case ImplicitConversionSequence::StandardConversion:
5014     dropPointerConversion(ICS.Standard);
5015     break;
5016   }
5017 
5018   return ICS;
5019 }
5020 
5021 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5022 /// conversion of the expression From to an Objective-C pointer type.
5023 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5024   if (checkPlaceholderForOverload(*this, From))
5025     return ExprError();
5026 
5027   QualType Ty = Context.getObjCIdType();
5028   ImplicitConversionSequence ICS =
5029     TryContextuallyConvertToObjCPointer(*this, From);
5030   if (!ICS.isBad())
5031     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5032   return ExprError();
5033 }
5034 
5035 /// Determine whether the provided type is an integral type, or an enumeration
5036 /// type of a permitted flavor.
5037 static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5038   return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5039                          : T->isIntegralOrUnscopedEnumerationType();
5040 }
5041 
5042 /// \brief Attempt to convert the given expression to an integral or
5043 /// enumeration type.
5044 ///
5045 /// This routine will attempt to convert an expression of class type to an
5046 /// integral or enumeration type, if that class type only has a single
5047 /// conversion to an integral or enumeration type.
5048 ///
5049 /// \param Loc The source location of the construct that requires the
5050 /// conversion.
5051 ///
5052 /// \param From The expression we're converting from.
5053 ///
5054 /// \param Diagnoser Used to output any diagnostics.
5055 ///
5056 /// \param AllowScopedEnumerations Specifies whether conversions to scoped
5057 /// enumerations should be considered.
5058 ///
5059 /// \returns The expression, converted to an integral or enumeration type if
5060 /// successful.
5061 ExprResult
5062 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
5063                                          ICEConvertDiagnoser &Diagnoser,
5064                                          bool AllowScopedEnumerations) {
5065   // We can't perform any more checking for type-dependent expressions.
5066   if (From->isTypeDependent())
5067     return Owned(From);
5068 
5069   // Process placeholders immediately.
5070   if (From->hasPlaceholderType()) {
5071     ExprResult result = CheckPlaceholderExpr(From);
5072     if (result.isInvalid()) return result;
5073     From = result.take();
5074   }
5075 
5076   // If the expression already has integral or enumeration type, we're golden.
5077   QualType T = From->getType();
5078   if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
5079     return DefaultLvalueConversion(From);
5080 
5081   // FIXME: Check for missing '()' if T is a function type?
5082 
5083   // If we don't have a class type in C++, there's no way we can get an
5084   // expression of integral or enumeration type.
5085   const RecordType *RecordTy = T->getAs<RecordType>();
5086   if (!RecordTy || !getLangOpts().CPlusPlus) {
5087     if (!Diagnoser.Suppress)
5088       Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
5089     return Owned(From);
5090   }
5091 
5092   // We must have a complete class type.
5093   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5094     ICEConvertDiagnoser &Diagnoser;
5095     Expr *From;
5096 
5097     TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5098       : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
5099 
5100     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5101       Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5102     }
5103   } IncompleteDiagnoser(Diagnoser, From);
5104 
5105   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5106     return Owned(From);
5107 
5108   // Look for a conversion to an integral or enumeration type.
5109   UnresolvedSet<4> ViableConversions;
5110   UnresolvedSet<4> ExplicitConversions;
5111   const UnresolvedSetImpl *Conversions
5112     = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5113 
5114   bool HadMultipleCandidates = (Conversions->size() > 1);
5115 
5116   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5117                                    E = Conversions->end();
5118        I != E;
5119        ++I) {
5120     if (CXXConversionDecl *Conversion
5121           = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5122       if (isIntegralOrEnumerationType(
5123             Conversion->getConversionType().getNonReferenceType(),
5124             AllowScopedEnumerations)) {
5125         if (Conversion->isExplicit())
5126           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5127         else
5128           ViableConversions.addDecl(I.getDecl(), I.getAccess());
5129       }
5130     }
5131   }
5132 
5133   switch (ViableConversions.size()) {
5134   case 0:
5135     if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
5136       DeclAccessPair Found = ExplicitConversions[0];
5137       CXXConversionDecl *Conversion
5138         = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5139 
5140       // The user probably meant to invoke the given explicit
5141       // conversion; use it.
5142       QualType ConvTy
5143         = Conversion->getConversionType().getNonReferenceType();
5144       std::string TypeStr;
5145       ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
5146 
5147       Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
5148         << FixItHint::CreateInsertion(From->getLocStart(),
5149                                       "static_cast<" + TypeStr + ">(")
5150         << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5151                                       ")");
5152       Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
5153 
5154       // If we aren't in a SFINAE context, build a call to the
5155       // explicit conversion function.
5156       if (isSFINAEContext())
5157         return ExprError();
5158 
5159       CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5160       ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5161                                                  HadMultipleCandidates);
5162       if (Result.isInvalid())
5163         return ExprError();
5164       // Record usage of conversion in an implicit cast.
5165       From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5166                                       CK_UserDefinedConversion,
5167                                       Result.get(), 0,
5168                                       Result.get()->getValueKind());
5169     }
5170 
5171     // We'll complain below about a non-integral condition type.
5172     break;
5173 
5174   case 1: {
5175     // Apply this conversion.
5176     DeclAccessPair Found = ViableConversions[0];
5177     CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5178 
5179     CXXConversionDecl *Conversion
5180       = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5181     QualType ConvTy
5182       = Conversion->getConversionType().getNonReferenceType();
5183     if (!Diagnoser.SuppressConversion) {
5184       if (isSFINAEContext())
5185         return ExprError();
5186 
5187       Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5188         << From->getSourceRange();
5189     }
5190 
5191     ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5192                                                HadMultipleCandidates);
5193     if (Result.isInvalid())
5194       return ExprError();
5195     // Record usage of conversion in an implicit cast.
5196     From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5197                                     CK_UserDefinedConversion,
5198                                     Result.get(), 0,
5199                                     Result.get()->getValueKind());
5200     break;
5201   }
5202 
5203   default:
5204     if (Diagnoser.Suppress)
5205       return ExprError();
5206 
5207     Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
5208     for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5209       CXXConversionDecl *Conv
5210         = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5211       QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5212       Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
5213     }
5214     return Owned(From);
5215   }
5216 
5217   if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5218       !Diagnoser.Suppress) {
5219     Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5220       << From->getSourceRange();
5221   }
5222 
5223   return DefaultLvalueConversion(From);
5224 }
5225 
5226 /// AddOverloadCandidate - Adds the given function to the set of
5227 /// candidate functions, using the given function call arguments.  If
5228 /// @p SuppressUserConversions, then don't allow user-defined
5229 /// conversions via constructors or conversion operators.
5230 ///
5231 /// \param PartialOverloading true if we are performing "partial" overloading
5232 /// based on an incomplete set of function arguments. This feature is used by
5233 /// code completion.
5234 void
5235 Sema::AddOverloadCandidate(FunctionDecl *Function,
5236                            DeclAccessPair FoundDecl,
5237                            llvm::ArrayRef<Expr *> Args,
5238                            OverloadCandidateSet& CandidateSet,
5239                            bool SuppressUserConversions,
5240                            bool PartialOverloading,
5241                            bool AllowExplicit) {
5242   const FunctionProtoType* Proto
5243     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5244   assert(Proto && "Functions without a prototype cannot be overloaded");
5245   assert(!Function->getDescribedFunctionTemplate() &&
5246          "Use AddTemplateOverloadCandidate for function templates");
5247 
5248   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5249     if (!isa<CXXConstructorDecl>(Method)) {
5250       // If we get here, it's because we're calling a member function
5251       // that is named without a member access expression (e.g.,
5252       // "this->f") that was either written explicitly or created
5253       // implicitly. This can happen with a qualified call to a member
5254       // function, e.g., X::f(). We use an empty type for the implied
5255       // object argument (C++ [over.call.func]p3), and the acting context
5256       // is irrelevant.
5257       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5258                          QualType(), Expr::Classification::makeSimpleLValue(),
5259                          Args, CandidateSet, SuppressUserConversions);
5260       return;
5261     }
5262     // We treat a constructor like a non-member function, since its object
5263     // argument doesn't participate in overload resolution.
5264   }
5265 
5266   if (!CandidateSet.isNewCandidate(Function))
5267     return;
5268 
5269   // Overload resolution is always an unevaluated context.
5270   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5271 
5272   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5273     // C++ [class.copy]p3:
5274     //   A member function template is never instantiated to perform the copy
5275     //   of a class object to an object of its class type.
5276     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5277     if (Args.size() == 1 &&
5278         Constructor->isSpecializationCopyingObject() &&
5279         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5280          IsDerivedFrom(Args[0]->getType(), ClassType)))
5281       return;
5282   }
5283 
5284   // Add this candidate
5285   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5286   Candidate.FoundDecl = FoundDecl;
5287   Candidate.Function = Function;
5288   Candidate.Viable = true;
5289   Candidate.IsSurrogate = false;
5290   Candidate.IgnoreObjectArgument = false;
5291   Candidate.ExplicitCallArguments = Args.size();
5292 
5293   unsigned NumArgsInProto = Proto->getNumArgs();
5294 
5295   // (C++ 13.3.2p2): A candidate function having fewer than m
5296   // parameters is viable only if it has an ellipsis in its parameter
5297   // list (8.3.5).
5298   if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5299       !Proto->isVariadic()) {
5300     Candidate.Viable = false;
5301     Candidate.FailureKind = ovl_fail_too_many_arguments;
5302     return;
5303   }
5304 
5305   // (C++ 13.3.2p2): A candidate function having more than m parameters
5306   // is viable only if the (m+1)st parameter has a default argument
5307   // (8.3.6). For the purposes of overload resolution, the
5308   // parameter list is truncated on the right, so that there are
5309   // exactly m parameters.
5310   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5311   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5312     // Not enough arguments.
5313     Candidate.Viable = false;
5314     Candidate.FailureKind = ovl_fail_too_few_arguments;
5315     return;
5316   }
5317 
5318   // (CUDA B.1): Check for invalid calls between targets.
5319   if (getLangOpts().CUDA)
5320     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5321       if (CheckCUDATarget(Caller, Function)) {
5322         Candidate.Viable = false;
5323         Candidate.FailureKind = ovl_fail_bad_target;
5324         return;
5325       }
5326 
5327   // Determine the implicit conversion sequences for each of the
5328   // arguments.
5329   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5330     if (ArgIdx < NumArgsInProto) {
5331       // (C++ 13.3.2p3): for F to be a viable function, there shall
5332       // exist for each argument an implicit conversion sequence
5333       // (13.3.3.1) that converts that argument to the corresponding
5334       // parameter of F.
5335       QualType ParamType = Proto->getArgType(ArgIdx);
5336       Candidate.Conversions[ArgIdx]
5337         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5338                                 SuppressUserConversions,
5339                                 /*InOverloadResolution=*/true,
5340                                 /*AllowObjCWritebackConversion=*/
5341                                   getLangOpts().ObjCAutoRefCount,
5342                                 AllowExplicit);
5343       if (Candidate.Conversions[ArgIdx].isBad()) {
5344         Candidate.Viable = false;
5345         Candidate.FailureKind = ovl_fail_bad_conversion;
5346         break;
5347       }
5348     } else {
5349       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5350       // argument for which there is no corresponding parameter is
5351       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5352       Candidate.Conversions[ArgIdx].setEllipsis();
5353     }
5354   }
5355 }
5356 
5357 /// \brief Add all of the function declarations in the given function set to
5358 /// the overload canddiate set.
5359 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5360                                  llvm::ArrayRef<Expr *> Args,
5361                                  OverloadCandidateSet& CandidateSet,
5362                                  bool SuppressUserConversions,
5363                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
5364   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5365     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5366     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5367       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5368         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5369                            cast<CXXMethodDecl>(FD)->getParent(),
5370                            Args[0]->getType(), Args[0]->Classify(Context),
5371                            Args.slice(1), CandidateSet,
5372                            SuppressUserConversions);
5373       else
5374         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5375                              SuppressUserConversions);
5376     } else {
5377       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5378       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5379           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5380         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5381                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5382                                    ExplicitTemplateArgs,
5383                                    Args[0]->getType(),
5384                                    Args[0]->Classify(Context), Args.slice(1),
5385                                    CandidateSet, SuppressUserConversions);
5386       else
5387         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5388                                      ExplicitTemplateArgs, Args,
5389                                      CandidateSet, SuppressUserConversions);
5390     }
5391   }
5392 }
5393 
5394 /// AddMethodCandidate - Adds a named decl (which is some kind of
5395 /// method) as a method candidate to the given overload set.
5396 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5397                               QualType ObjectType,
5398                               Expr::Classification ObjectClassification,
5399                               Expr **Args, unsigned NumArgs,
5400                               OverloadCandidateSet& CandidateSet,
5401                               bool SuppressUserConversions) {
5402   NamedDecl *Decl = FoundDecl.getDecl();
5403   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5404 
5405   if (isa<UsingShadowDecl>(Decl))
5406     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5407 
5408   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5409     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5410            "Expected a member function template");
5411     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5412                                /*ExplicitArgs*/ 0,
5413                                ObjectType, ObjectClassification,
5414                                llvm::makeArrayRef(Args, NumArgs), CandidateSet,
5415                                SuppressUserConversions);
5416   } else {
5417     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5418                        ObjectType, ObjectClassification,
5419                        llvm::makeArrayRef(Args, NumArgs),
5420                        CandidateSet, SuppressUserConversions);
5421   }
5422 }
5423 
5424 /// AddMethodCandidate - Adds the given C++ member function to the set
5425 /// of candidate functions, using the given function call arguments
5426 /// and the object argument (@c Object). For example, in a call
5427 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5428 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5429 /// allow user-defined conversions via constructors or conversion
5430 /// operators.
5431 void
5432 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5433                          CXXRecordDecl *ActingContext, QualType ObjectType,
5434                          Expr::Classification ObjectClassification,
5435                          llvm::ArrayRef<Expr *> Args,
5436                          OverloadCandidateSet& CandidateSet,
5437                          bool SuppressUserConversions) {
5438   const FunctionProtoType* Proto
5439     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5440   assert(Proto && "Methods without a prototype cannot be overloaded");
5441   assert(!isa<CXXConstructorDecl>(Method) &&
5442          "Use AddOverloadCandidate for constructors");
5443 
5444   if (!CandidateSet.isNewCandidate(Method))
5445     return;
5446 
5447   // Overload resolution is always an unevaluated context.
5448   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5449 
5450   // Add this candidate
5451   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5452   Candidate.FoundDecl = FoundDecl;
5453   Candidate.Function = Method;
5454   Candidate.IsSurrogate = false;
5455   Candidate.IgnoreObjectArgument = false;
5456   Candidate.ExplicitCallArguments = Args.size();
5457 
5458   unsigned NumArgsInProto = Proto->getNumArgs();
5459 
5460   // (C++ 13.3.2p2): A candidate function having fewer than m
5461   // parameters is viable only if it has an ellipsis in its parameter
5462   // list (8.3.5).
5463   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5464     Candidate.Viable = false;
5465     Candidate.FailureKind = ovl_fail_too_many_arguments;
5466     return;
5467   }
5468 
5469   // (C++ 13.3.2p2): A candidate function having more than m parameters
5470   // is viable only if the (m+1)st parameter has a default argument
5471   // (8.3.6). For the purposes of overload resolution, the
5472   // parameter list is truncated on the right, so that there are
5473   // exactly m parameters.
5474   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5475   if (Args.size() < MinRequiredArgs) {
5476     // Not enough arguments.
5477     Candidate.Viable = false;
5478     Candidate.FailureKind = ovl_fail_too_few_arguments;
5479     return;
5480   }
5481 
5482   Candidate.Viable = true;
5483 
5484   if (Method->isStatic() || ObjectType.isNull())
5485     // The implicit object argument is ignored.
5486     Candidate.IgnoreObjectArgument = true;
5487   else {
5488     // Determine the implicit conversion sequence for the object
5489     // parameter.
5490     Candidate.Conversions[0]
5491       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5492                                         Method, ActingContext);
5493     if (Candidate.Conversions[0].isBad()) {
5494       Candidate.Viable = false;
5495       Candidate.FailureKind = ovl_fail_bad_conversion;
5496       return;
5497     }
5498   }
5499 
5500   // Determine the implicit conversion sequences for each of the
5501   // arguments.
5502   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5503     if (ArgIdx < NumArgsInProto) {
5504       // (C++ 13.3.2p3): for F to be a viable function, there shall
5505       // exist for each argument an implicit conversion sequence
5506       // (13.3.3.1) that converts that argument to the corresponding
5507       // parameter of F.
5508       QualType ParamType = Proto->getArgType(ArgIdx);
5509       Candidate.Conversions[ArgIdx + 1]
5510         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5511                                 SuppressUserConversions,
5512                                 /*InOverloadResolution=*/true,
5513                                 /*AllowObjCWritebackConversion=*/
5514                                   getLangOpts().ObjCAutoRefCount);
5515       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5516         Candidate.Viable = false;
5517         Candidate.FailureKind = ovl_fail_bad_conversion;
5518         break;
5519       }
5520     } else {
5521       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5522       // argument for which there is no corresponding parameter is
5523       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5524       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5525     }
5526   }
5527 }
5528 
5529 /// \brief Add a C++ member function template as a candidate to the candidate
5530 /// set, using template argument deduction to produce an appropriate member
5531 /// function template specialization.
5532 void
5533 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5534                                  DeclAccessPair FoundDecl,
5535                                  CXXRecordDecl *ActingContext,
5536                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5537                                  QualType ObjectType,
5538                                  Expr::Classification ObjectClassification,
5539                                  llvm::ArrayRef<Expr *> Args,
5540                                  OverloadCandidateSet& CandidateSet,
5541                                  bool SuppressUserConversions) {
5542   if (!CandidateSet.isNewCandidate(MethodTmpl))
5543     return;
5544 
5545   // C++ [over.match.funcs]p7:
5546   //   In each case where a candidate is a function template, candidate
5547   //   function template specializations are generated using template argument
5548   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5549   //   candidate functions in the usual way.113) A given name can refer to one
5550   //   or more function templates and also to a set of overloaded non-template
5551   //   functions. In such a case, the candidate functions generated from each
5552   //   function template are combined with the set of non-template candidate
5553   //   functions.
5554   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5555   FunctionDecl *Specialization = 0;
5556   if (TemplateDeductionResult Result
5557       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5558                                 Specialization, Info)) {
5559     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5560     Candidate.FoundDecl = FoundDecl;
5561     Candidate.Function = MethodTmpl->getTemplatedDecl();
5562     Candidate.Viable = false;
5563     Candidate.FailureKind = ovl_fail_bad_deduction;
5564     Candidate.IsSurrogate = false;
5565     Candidate.IgnoreObjectArgument = false;
5566     Candidate.ExplicitCallArguments = Args.size();
5567     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5568                                                           Info);
5569     return;
5570   }
5571 
5572   // Add the function template specialization produced by template argument
5573   // deduction as a candidate.
5574   assert(Specialization && "Missing member function template specialization?");
5575   assert(isa<CXXMethodDecl>(Specialization) &&
5576          "Specialization is not a member function?");
5577   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5578                      ActingContext, ObjectType, ObjectClassification, Args,
5579                      CandidateSet, SuppressUserConversions);
5580 }
5581 
5582 /// \brief Add a C++ function template specialization as a candidate
5583 /// in the candidate set, using template argument deduction to produce
5584 /// an appropriate function template specialization.
5585 void
5586 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5587                                    DeclAccessPair FoundDecl,
5588                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5589                                    llvm::ArrayRef<Expr *> Args,
5590                                    OverloadCandidateSet& CandidateSet,
5591                                    bool SuppressUserConversions) {
5592   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5593     return;
5594 
5595   // C++ [over.match.funcs]p7:
5596   //   In each case where a candidate is a function template, candidate
5597   //   function template specializations are generated using template argument
5598   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5599   //   candidate functions in the usual way.113) A given name can refer to one
5600   //   or more function templates and also to a set of overloaded non-template
5601   //   functions. In such a case, the candidate functions generated from each
5602   //   function template are combined with the set of non-template candidate
5603   //   functions.
5604   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5605   FunctionDecl *Specialization = 0;
5606   if (TemplateDeductionResult Result
5607         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5608                                   Specialization, Info)) {
5609     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5610     Candidate.FoundDecl = FoundDecl;
5611     Candidate.Function = FunctionTemplate->getTemplatedDecl();
5612     Candidate.Viable = false;
5613     Candidate.FailureKind = ovl_fail_bad_deduction;
5614     Candidate.IsSurrogate = false;
5615     Candidate.IgnoreObjectArgument = false;
5616     Candidate.ExplicitCallArguments = Args.size();
5617     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5618                                                           Info);
5619     return;
5620   }
5621 
5622   // Add the function template specialization produced by template argument
5623   // deduction as a candidate.
5624   assert(Specialization && "Missing function template specialization?");
5625   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5626                        SuppressUserConversions);
5627 }
5628 
5629 /// AddConversionCandidate - Add a C++ conversion function as a
5630 /// candidate in the candidate set (C++ [over.match.conv],
5631 /// C++ [over.match.copy]). From is the expression we're converting from,
5632 /// and ToType is the type that we're eventually trying to convert to
5633 /// (which may or may not be the same type as the type that the
5634 /// conversion function produces).
5635 void
5636 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5637                              DeclAccessPair FoundDecl,
5638                              CXXRecordDecl *ActingContext,
5639                              Expr *From, QualType ToType,
5640                              OverloadCandidateSet& CandidateSet) {
5641   assert(!Conversion->getDescribedFunctionTemplate() &&
5642          "Conversion function templates use AddTemplateConversionCandidate");
5643   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5644   if (!CandidateSet.isNewCandidate(Conversion))
5645     return;
5646 
5647   // Overload resolution is always an unevaluated context.
5648   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5649 
5650   // Add this candidate
5651   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5652   Candidate.FoundDecl = FoundDecl;
5653   Candidate.Function = Conversion;
5654   Candidate.IsSurrogate = false;
5655   Candidate.IgnoreObjectArgument = false;
5656   Candidate.FinalConversion.setAsIdentityConversion();
5657   Candidate.FinalConversion.setFromType(ConvType);
5658   Candidate.FinalConversion.setAllToTypes(ToType);
5659   Candidate.Viable = true;
5660   Candidate.ExplicitCallArguments = 1;
5661 
5662   // C++ [over.match.funcs]p4:
5663   //   For conversion functions, the function is considered to be a member of
5664   //   the class of the implicit implied object argument for the purpose of
5665   //   defining the type of the implicit object parameter.
5666   //
5667   // Determine the implicit conversion sequence for the implicit
5668   // object parameter.
5669   QualType ImplicitParamType = From->getType();
5670   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5671     ImplicitParamType = FromPtrType->getPointeeType();
5672   CXXRecordDecl *ConversionContext
5673     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5674 
5675   Candidate.Conversions[0]
5676     = TryObjectArgumentInitialization(*this, From->getType(),
5677                                       From->Classify(Context),
5678                                       Conversion, ConversionContext);
5679 
5680   if (Candidate.Conversions[0].isBad()) {
5681     Candidate.Viable = false;
5682     Candidate.FailureKind = ovl_fail_bad_conversion;
5683     return;
5684   }
5685 
5686   // We won't go through a user-define type conversion function to convert a
5687   // derived to base as such conversions are given Conversion Rank. They only
5688   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5689   QualType FromCanon
5690     = Context.getCanonicalType(From->getType().getUnqualifiedType());
5691   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5692   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5693     Candidate.Viable = false;
5694     Candidate.FailureKind = ovl_fail_trivial_conversion;
5695     return;
5696   }
5697 
5698   // To determine what the conversion from the result of calling the
5699   // conversion function to the type we're eventually trying to
5700   // convert to (ToType), we need to synthesize a call to the
5701   // conversion function and attempt copy initialization from it. This
5702   // makes sure that we get the right semantics with respect to
5703   // lvalues/rvalues and the type. Fortunately, we can allocate this
5704   // call on the stack and we don't need its arguments to be
5705   // well-formed.
5706   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5707                             VK_LValue, From->getLocStart());
5708   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5709                                 Context.getPointerType(Conversion->getType()),
5710                                 CK_FunctionToPointerDecay,
5711                                 &ConversionRef, VK_RValue);
5712 
5713   QualType ConversionType = Conversion->getConversionType();
5714   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5715     Candidate.Viable = false;
5716     Candidate.FailureKind = ovl_fail_bad_final_conversion;
5717     return;
5718   }
5719 
5720   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5721 
5722   // Note that it is safe to allocate CallExpr on the stack here because
5723   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5724   // allocator).
5725   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5726   CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
5727                 From->getLocStart());
5728   ImplicitConversionSequence ICS =
5729     TryCopyInitialization(*this, &Call, ToType,
5730                           /*SuppressUserConversions=*/true,
5731                           /*InOverloadResolution=*/false,
5732                           /*AllowObjCWritebackConversion=*/false);
5733 
5734   switch (ICS.getKind()) {
5735   case ImplicitConversionSequence::StandardConversion:
5736     Candidate.FinalConversion = ICS.Standard;
5737 
5738     // C++ [over.ics.user]p3:
5739     //   If the user-defined conversion is specified by a specialization of a
5740     //   conversion function template, the second standard conversion sequence
5741     //   shall have exact match rank.
5742     if (Conversion->getPrimaryTemplate() &&
5743         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5744       Candidate.Viable = false;
5745       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5746     }
5747 
5748     // C++0x [dcl.init.ref]p5:
5749     //    In the second case, if the reference is an rvalue reference and
5750     //    the second standard conversion sequence of the user-defined
5751     //    conversion sequence includes an lvalue-to-rvalue conversion, the
5752     //    program is ill-formed.
5753     if (ToType->isRValueReferenceType() &&
5754         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5755       Candidate.Viable = false;
5756       Candidate.FailureKind = ovl_fail_bad_final_conversion;
5757     }
5758     break;
5759 
5760   case ImplicitConversionSequence::BadConversion:
5761     Candidate.Viable = false;
5762     Candidate.FailureKind = ovl_fail_bad_final_conversion;
5763     break;
5764 
5765   default:
5766     llvm_unreachable(
5767            "Can only end up with a standard conversion sequence or failure");
5768   }
5769 }
5770 
5771 /// \brief Adds a conversion function template specialization
5772 /// candidate to the overload set, using template argument deduction
5773 /// to deduce the template arguments of the conversion function
5774 /// template from the type that we are converting to (C++
5775 /// [temp.deduct.conv]).
5776 void
5777 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5778                                      DeclAccessPair FoundDecl,
5779                                      CXXRecordDecl *ActingDC,
5780                                      Expr *From, QualType ToType,
5781                                      OverloadCandidateSet &CandidateSet) {
5782   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5783          "Only conversion function templates permitted here");
5784 
5785   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5786     return;
5787 
5788   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5789   CXXConversionDecl *Specialization = 0;
5790   if (TemplateDeductionResult Result
5791         = DeduceTemplateArguments(FunctionTemplate, ToType,
5792                                   Specialization, Info)) {
5793     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5794     Candidate.FoundDecl = FoundDecl;
5795     Candidate.Function = FunctionTemplate->getTemplatedDecl();
5796     Candidate.Viable = false;
5797     Candidate.FailureKind = ovl_fail_bad_deduction;
5798     Candidate.IsSurrogate = false;
5799     Candidate.IgnoreObjectArgument = false;
5800     Candidate.ExplicitCallArguments = 1;
5801     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5802                                                           Info);
5803     return;
5804   }
5805 
5806   // Add the conversion function template specialization produced by
5807   // template argument deduction as a candidate.
5808   assert(Specialization && "Missing function template specialization?");
5809   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5810                          CandidateSet);
5811 }
5812 
5813 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5814 /// converts the given @c Object to a function pointer via the
5815 /// conversion function @c Conversion, and then attempts to call it
5816 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
5817 /// the type of function that we'll eventually be calling.
5818 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5819                                  DeclAccessPair FoundDecl,
5820                                  CXXRecordDecl *ActingContext,
5821                                  const FunctionProtoType *Proto,
5822                                  Expr *Object,
5823                                  llvm::ArrayRef<Expr *> Args,
5824                                  OverloadCandidateSet& CandidateSet) {
5825   if (!CandidateSet.isNewCandidate(Conversion))
5826     return;
5827 
5828   // Overload resolution is always an unevaluated context.
5829   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5830 
5831   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5832   Candidate.FoundDecl = FoundDecl;
5833   Candidate.Function = 0;
5834   Candidate.Surrogate = Conversion;
5835   Candidate.Viable = true;
5836   Candidate.IsSurrogate = true;
5837   Candidate.IgnoreObjectArgument = false;
5838   Candidate.ExplicitCallArguments = Args.size();
5839 
5840   // Determine the implicit conversion sequence for the implicit
5841   // object parameter.
5842   ImplicitConversionSequence ObjectInit
5843     = TryObjectArgumentInitialization(*this, Object->getType(),
5844                                       Object->Classify(Context),
5845                                       Conversion, ActingContext);
5846   if (ObjectInit.isBad()) {
5847     Candidate.Viable = false;
5848     Candidate.FailureKind = ovl_fail_bad_conversion;
5849     Candidate.Conversions[0] = ObjectInit;
5850     return;
5851   }
5852 
5853   // The first conversion is actually a user-defined conversion whose
5854   // first conversion is ObjectInit's standard conversion (which is
5855   // effectively a reference binding). Record it as such.
5856   Candidate.Conversions[0].setUserDefined();
5857   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
5858   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
5859   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
5860   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
5861   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
5862   Candidate.Conversions[0].UserDefined.After
5863     = Candidate.Conversions[0].UserDefined.Before;
5864   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5865 
5866   // Find the
5867   unsigned NumArgsInProto = Proto->getNumArgs();
5868 
5869   // (C++ 13.3.2p2): A candidate function having fewer than m
5870   // parameters is viable only if it has an ellipsis in its parameter
5871   // list (8.3.5).
5872   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5873     Candidate.Viable = false;
5874     Candidate.FailureKind = ovl_fail_too_many_arguments;
5875     return;
5876   }
5877 
5878   // Function types don't have any default arguments, so just check if
5879   // we have enough arguments.
5880   if (Args.size() < NumArgsInProto) {
5881     // Not enough arguments.
5882     Candidate.Viable = false;
5883     Candidate.FailureKind = ovl_fail_too_few_arguments;
5884     return;
5885   }
5886 
5887   // Determine the implicit conversion sequences for each of the
5888   // arguments.
5889   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5890     if (ArgIdx < NumArgsInProto) {
5891       // (C++ 13.3.2p3): for F to be a viable function, there shall
5892       // exist for each argument an implicit conversion sequence
5893       // (13.3.3.1) that converts that argument to the corresponding
5894       // parameter of F.
5895       QualType ParamType = Proto->getArgType(ArgIdx);
5896       Candidate.Conversions[ArgIdx + 1]
5897         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5898                                 /*SuppressUserConversions=*/false,
5899                                 /*InOverloadResolution=*/false,
5900                                 /*AllowObjCWritebackConversion=*/
5901                                   getLangOpts().ObjCAutoRefCount);
5902       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5903         Candidate.Viable = false;
5904         Candidate.FailureKind = ovl_fail_bad_conversion;
5905         break;
5906       }
5907     } else {
5908       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5909       // argument for which there is no corresponding parameter is
5910       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5911       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5912     }
5913   }
5914 }
5915 
5916 /// \brief Add overload candidates for overloaded operators that are
5917 /// member functions.
5918 ///
5919 /// Add the overloaded operator candidates that are member functions
5920 /// for the operator Op that was used in an operator expression such
5921 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
5922 /// CandidateSet will store the added overload candidates. (C++
5923 /// [over.match.oper]).
5924 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5925                                        SourceLocation OpLoc,
5926                                        Expr **Args, unsigned NumArgs,
5927                                        OverloadCandidateSet& CandidateSet,
5928                                        SourceRange OpRange) {
5929   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5930 
5931   // C++ [over.match.oper]p3:
5932   //   For a unary operator @ with an operand of a type whose
5933   //   cv-unqualified version is T1, and for a binary operator @ with
5934   //   a left operand of a type whose cv-unqualified version is T1 and
5935   //   a right operand of a type whose cv-unqualified version is T2,
5936   //   three sets of candidate functions, designated member
5937   //   candidates, non-member candidates and built-in candidates, are
5938   //   constructed as follows:
5939   QualType T1 = Args[0]->getType();
5940 
5941   //     -- If T1 is a class type, the set of member candidates is the
5942   //        result of the qualified lookup of T1::operator@
5943   //        (13.3.1.1.1); otherwise, the set of member candidates is
5944   //        empty.
5945   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
5946     // Complete the type if it can be completed. Otherwise, we're done.
5947     if (RequireCompleteType(OpLoc, T1, 0))
5948       return;
5949 
5950     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5951     LookupQualifiedName(Operators, T1Rec->getDecl());
5952     Operators.suppressDiagnostics();
5953 
5954     for (LookupResult::iterator Oper = Operators.begin(),
5955                              OperEnd = Operators.end();
5956          Oper != OperEnd;
5957          ++Oper)
5958       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
5959                          Args[0]->Classify(Context), Args + 1, NumArgs - 1,
5960                          CandidateSet,
5961                          /* SuppressUserConversions = */ false);
5962   }
5963 }
5964 
5965 /// AddBuiltinCandidate - Add a candidate for a built-in
5966 /// operator. ResultTy and ParamTys are the result and parameter types
5967 /// of the built-in candidate, respectively. Args and NumArgs are the
5968 /// arguments being passed to the candidate. IsAssignmentOperator
5969 /// should be true when this built-in candidate is an assignment
5970 /// operator. NumContextualBoolArguments is the number of arguments
5971 /// (at the beginning of the argument list) that will be contextually
5972 /// converted to bool.
5973 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
5974                                Expr **Args, unsigned NumArgs,
5975                                OverloadCandidateSet& CandidateSet,
5976                                bool IsAssignmentOperator,
5977                                unsigned NumContextualBoolArguments) {
5978   // Overload resolution is always an unevaluated context.
5979   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5980 
5981   // Add this candidate
5982   OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
5983   Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
5984   Candidate.Function = 0;
5985   Candidate.IsSurrogate = false;
5986   Candidate.IgnoreObjectArgument = false;
5987   Candidate.BuiltinTypes.ResultTy = ResultTy;
5988   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5989     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5990 
5991   // Determine the implicit conversion sequences for each of the
5992   // arguments.
5993   Candidate.Viable = true;
5994   Candidate.ExplicitCallArguments = NumArgs;
5995   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5996     // C++ [over.match.oper]p4:
5997     //   For the built-in assignment operators, conversions of the
5998     //   left operand are restricted as follows:
5999     //     -- no temporaries are introduced to hold the left operand, and
6000     //     -- no user-defined conversions are applied to the left
6001     //        operand to achieve a type match with the left-most
6002     //        parameter of a built-in candidate.
6003     //
6004     // We block these conversions by turning off user-defined
6005     // conversions, since that is the only way that initialization of
6006     // a reference to a non-class type can occur from something that
6007     // is not of the same type.
6008     if (ArgIdx < NumContextualBoolArguments) {
6009       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6010              "Contextual conversion to bool requires bool type");
6011       Candidate.Conversions[ArgIdx]
6012         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6013     } else {
6014       Candidate.Conversions[ArgIdx]
6015         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6016                                 ArgIdx == 0 && IsAssignmentOperator,
6017                                 /*InOverloadResolution=*/false,
6018                                 /*AllowObjCWritebackConversion=*/
6019                                   getLangOpts().ObjCAutoRefCount);
6020     }
6021     if (Candidate.Conversions[ArgIdx].isBad()) {
6022       Candidate.Viable = false;
6023       Candidate.FailureKind = ovl_fail_bad_conversion;
6024       break;
6025     }
6026   }
6027 }
6028 
6029 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6030 /// candidate operator functions for built-in operators (C++
6031 /// [over.built]). The types are separated into pointer types and
6032 /// enumeration types.
6033 class BuiltinCandidateTypeSet  {
6034   /// TypeSet - A set of types.
6035   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6036 
6037   /// PointerTypes - The set of pointer types that will be used in the
6038   /// built-in candidates.
6039   TypeSet PointerTypes;
6040 
6041   /// MemberPointerTypes - The set of member pointer types that will be
6042   /// used in the built-in candidates.
6043   TypeSet MemberPointerTypes;
6044 
6045   /// EnumerationTypes - The set of enumeration types that will be
6046   /// used in the built-in candidates.
6047   TypeSet EnumerationTypes;
6048 
6049   /// \brief The set of vector types that will be used in the built-in
6050   /// candidates.
6051   TypeSet VectorTypes;
6052 
6053   /// \brief A flag indicating non-record types are viable candidates
6054   bool HasNonRecordTypes;
6055 
6056   /// \brief A flag indicating whether either arithmetic or enumeration types
6057   /// were present in the candidate set.
6058   bool HasArithmeticOrEnumeralTypes;
6059 
6060   /// \brief A flag indicating whether the nullptr type was present in the
6061   /// candidate set.
6062   bool HasNullPtrType;
6063 
6064   /// Sema - The semantic analysis instance where we are building the
6065   /// candidate type set.
6066   Sema &SemaRef;
6067 
6068   /// Context - The AST context in which we will build the type sets.
6069   ASTContext &Context;
6070 
6071   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6072                                                const Qualifiers &VisibleQuals);
6073   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6074 
6075 public:
6076   /// iterator - Iterates through the types that are part of the set.
6077   typedef TypeSet::iterator iterator;
6078 
6079   BuiltinCandidateTypeSet(Sema &SemaRef)
6080     : HasNonRecordTypes(false),
6081       HasArithmeticOrEnumeralTypes(false),
6082       HasNullPtrType(false),
6083       SemaRef(SemaRef),
6084       Context(SemaRef.Context) { }
6085 
6086   void AddTypesConvertedFrom(QualType Ty,
6087                              SourceLocation Loc,
6088                              bool AllowUserConversions,
6089                              bool AllowExplicitConversions,
6090                              const Qualifiers &VisibleTypeConversionsQuals);
6091 
6092   /// pointer_begin - First pointer type found;
6093   iterator pointer_begin() { return PointerTypes.begin(); }
6094 
6095   /// pointer_end - Past the last pointer type found;
6096   iterator pointer_end() { return PointerTypes.end(); }
6097 
6098   /// member_pointer_begin - First member pointer type found;
6099   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6100 
6101   /// member_pointer_end - Past the last member pointer type found;
6102   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6103 
6104   /// enumeration_begin - First enumeration type found;
6105   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6106 
6107   /// enumeration_end - Past the last enumeration type found;
6108   iterator enumeration_end() { return EnumerationTypes.end(); }
6109 
6110   iterator vector_begin() { return VectorTypes.begin(); }
6111   iterator vector_end() { return VectorTypes.end(); }
6112 
6113   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6114   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6115   bool hasNullPtrType() const { return HasNullPtrType; }
6116 };
6117 
6118 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6119 /// the set of pointer types along with any more-qualified variants of
6120 /// that type. For example, if @p Ty is "int const *", this routine
6121 /// will add "int const *", "int const volatile *", "int const
6122 /// restrict *", and "int const volatile restrict *" to the set of
6123 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6124 /// false otherwise.
6125 ///
6126 /// FIXME: what to do about extended qualifiers?
6127 bool
6128 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6129                                              const Qualifiers &VisibleQuals) {
6130 
6131   // Insert this type.
6132   if (!PointerTypes.insert(Ty))
6133     return false;
6134 
6135   QualType PointeeTy;
6136   const PointerType *PointerTy = Ty->getAs<PointerType>();
6137   bool buildObjCPtr = false;
6138   if (!PointerTy) {
6139     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6140     PointeeTy = PTy->getPointeeType();
6141     buildObjCPtr = true;
6142   } else {
6143     PointeeTy = PointerTy->getPointeeType();
6144   }
6145 
6146   // Don't add qualified variants of arrays. For one, they're not allowed
6147   // (the qualifier would sink to the element type), and for another, the
6148   // only overload situation where it matters is subscript or pointer +- int,
6149   // and those shouldn't have qualifier variants anyway.
6150   if (PointeeTy->isArrayType())
6151     return true;
6152 
6153   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6154   bool hasVolatile = VisibleQuals.hasVolatile();
6155   bool hasRestrict = VisibleQuals.hasRestrict();
6156 
6157   // Iterate through all strict supersets of BaseCVR.
6158   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6159     if ((CVR | BaseCVR) != CVR) continue;
6160     // Skip over volatile if no volatile found anywhere in the types.
6161     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6162 
6163     // Skip over restrict if no restrict found anywhere in the types, or if
6164     // the type cannot be restrict-qualified.
6165     if ((CVR & Qualifiers::Restrict) &&
6166         (!hasRestrict ||
6167          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6168       continue;
6169 
6170     // Build qualified pointee type.
6171     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6172 
6173     // Build qualified pointer type.
6174     QualType QPointerTy;
6175     if (!buildObjCPtr)
6176       QPointerTy = Context.getPointerType(QPointeeTy);
6177     else
6178       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6179 
6180     // Insert qualified pointer type.
6181     PointerTypes.insert(QPointerTy);
6182   }
6183 
6184   return true;
6185 }
6186 
6187 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6188 /// to the set of pointer types along with any more-qualified variants of
6189 /// that type. For example, if @p Ty is "int const *", this routine
6190 /// will add "int const *", "int const volatile *", "int const
6191 /// restrict *", and "int const volatile restrict *" to the set of
6192 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6193 /// false otherwise.
6194 ///
6195 /// FIXME: what to do about extended qualifiers?
6196 bool
6197 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6198     QualType Ty) {
6199   // Insert this type.
6200   if (!MemberPointerTypes.insert(Ty))
6201     return false;
6202 
6203   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6204   assert(PointerTy && "type was not a member pointer type!");
6205 
6206   QualType PointeeTy = PointerTy->getPointeeType();
6207   // Don't add qualified variants of arrays. For one, they're not allowed
6208   // (the qualifier would sink to the element type), and for another, the
6209   // only overload situation where it matters is subscript or pointer +- int,
6210   // and those shouldn't have qualifier variants anyway.
6211   if (PointeeTy->isArrayType())
6212     return true;
6213   const Type *ClassTy = PointerTy->getClass();
6214 
6215   // Iterate through all strict supersets of the pointee type's CVR
6216   // qualifiers.
6217   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6218   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6219     if ((CVR | BaseCVR) != CVR) continue;
6220 
6221     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6222     MemberPointerTypes.insert(
6223       Context.getMemberPointerType(QPointeeTy, ClassTy));
6224   }
6225 
6226   return true;
6227 }
6228 
6229 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6230 /// Ty can be implicit converted to the given set of @p Types. We're
6231 /// primarily interested in pointer types and enumeration types. We also
6232 /// take member pointer types, for the conditional operator.
6233 /// AllowUserConversions is true if we should look at the conversion
6234 /// functions of a class type, and AllowExplicitConversions if we
6235 /// should also include the explicit conversion functions of a class
6236 /// type.
6237 void
6238 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6239                                                SourceLocation Loc,
6240                                                bool AllowUserConversions,
6241                                                bool AllowExplicitConversions,
6242                                                const Qualifiers &VisibleQuals) {
6243   // Only deal with canonical types.
6244   Ty = Context.getCanonicalType(Ty);
6245 
6246   // Look through reference types; they aren't part of the type of an
6247   // expression for the purposes of conversions.
6248   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6249     Ty = RefTy->getPointeeType();
6250 
6251   // If we're dealing with an array type, decay to the pointer.
6252   if (Ty->isArrayType())
6253     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6254 
6255   // Otherwise, we don't care about qualifiers on the type.
6256   Ty = Ty.getLocalUnqualifiedType();
6257 
6258   // Flag if we ever add a non-record type.
6259   const RecordType *TyRec = Ty->getAs<RecordType>();
6260   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6261 
6262   // Flag if we encounter an arithmetic type.
6263   HasArithmeticOrEnumeralTypes =
6264     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6265 
6266   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6267     PointerTypes.insert(Ty);
6268   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6269     // Insert our type, and its more-qualified variants, into the set
6270     // of types.
6271     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6272       return;
6273   } else if (Ty->isMemberPointerType()) {
6274     // Member pointers are far easier, since the pointee can't be converted.
6275     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6276       return;
6277   } else if (Ty->isEnumeralType()) {
6278     HasArithmeticOrEnumeralTypes = true;
6279     EnumerationTypes.insert(Ty);
6280   } else if (Ty->isVectorType()) {
6281     // We treat vector types as arithmetic types in many contexts as an
6282     // extension.
6283     HasArithmeticOrEnumeralTypes = true;
6284     VectorTypes.insert(Ty);
6285   } else if (Ty->isNullPtrType()) {
6286     HasNullPtrType = true;
6287   } else if (AllowUserConversions && TyRec) {
6288     // No conversion functions in incomplete types.
6289     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6290       return;
6291 
6292     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6293     const UnresolvedSetImpl *Conversions
6294       = ClassDecl->getVisibleConversionFunctions();
6295     for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6296            E = Conversions->end(); I != E; ++I) {
6297       NamedDecl *D = I.getDecl();
6298       if (isa<UsingShadowDecl>(D))
6299         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6300 
6301       // Skip conversion function templates; they don't tell us anything
6302       // about which builtin types we can convert to.
6303       if (isa<FunctionTemplateDecl>(D))
6304         continue;
6305 
6306       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6307       if (AllowExplicitConversions || !Conv->isExplicit()) {
6308         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6309                               VisibleQuals);
6310       }
6311     }
6312   }
6313 }
6314 
6315 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6316 /// the volatile- and non-volatile-qualified assignment operators for the
6317 /// given type to the candidate set.
6318 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6319                                                    QualType T,
6320                                                    Expr **Args,
6321                                                    unsigned NumArgs,
6322                                     OverloadCandidateSet &CandidateSet) {
6323   QualType ParamTypes[2];
6324 
6325   // T& operator=(T&, T)
6326   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6327   ParamTypes[1] = T;
6328   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6329                         /*IsAssignmentOperator=*/true);
6330 
6331   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6332     // volatile T& operator=(volatile T&, T)
6333     ParamTypes[0]
6334       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6335     ParamTypes[1] = T;
6336     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6337                           /*IsAssignmentOperator=*/true);
6338   }
6339 }
6340 
6341 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6342 /// if any, found in visible type conversion functions found in ArgExpr's type.
6343 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6344     Qualifiers VRQuals;
6345     const RecordType *TyRec;
6346     if (const MemberPointerType *RHSMPType =
6347         ArgExpr->getType()->getAs<MemberPointerType>())
6348       TyRec = RHSMPType->getClass()->getAs<RecordType>();
6349     else
6350       TyRec = ArgExpr->getType()->getAs<RecordType>();
6351     if (!TyRec) {
6352       // Just to be safe, assume the worst case.
6353       VRQuals.addVolatile();
6354       VRQuals.addRestrict();
6355       return VRQuals;
6356     }
6357 
6358     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6359     if (!ClassDecl->hasDefinition())
6360       return VRQuals;
6361 
6362     const UnresolvedSetImpl *Conversions =
6363       ClassDecl->getVisibleConversionFunctions();
6364 
6365     for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6366            E = Conversions->end(); I != E; ++I) {
6367       NamedDecl *D = I.getDecl();
6368       if (isa<UsingShadowDecl>(D))
6369         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6370       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6371         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6372         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6373           CanTy = ResTypeRef->getPointeeType();
6374         // Need to go down the pointer/mempointer chain and add qualifiers
6375         // as see them.
6376         bool done = false;
6377         while (!done) {
6378           if (CanTy.isRestrictQualified())
6379             VRQuals.addRestrict();
6380           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6381             CanTy = ResTypePtr->getPointeeType();
6382           else if (const MemberPointerType *ResTypeMPtr =
6383                 CanTy->getAs<MemberPointerType>())
6384             CanTy = ResTypeMPtr->getPointeeType();
6385           else
6386             done = true;
6387           if (CanTy.isVolatileQualified())
6388             VRQuals.addVolatile();
6389           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6390             return VRQuals;
6391         }
6392       }
6393     }
6394     return VRQuals;
6395 }
6396 
6397 namespace {
6398 
6399 /// \brief Helper class to manage the addition of builtin operator overload
6400 /// candidates. It provides shared state and utility methods used throughout
6401 /// the process, as well as a helper method to add each group of builtin
6402 /// operator overloads from the standard to a candidate set.
6403 class BuiltinOperatorOverloadBuilder {
6404   // Common instance state available to all overload candidate addition methods.
6405   Sema &S;
6406   Expr **Args;
6407   unsigned NumArgs;
6408   Qualifiers VisibleTypeConversionsQuals;
6409   bool HasArithmeticOrEnumeralCandidateType;
6410   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6411   OverloadCandidateSet &CandidateSet;
6412 
6413   // Define some constants used to index and iterate over the arithemetic types
6414   // provided via the getArithmeticType() method below.
6415   // The "promoted arithmetic types" are the arithmetic
6416   // types are that preserved by promotion (C++ [over.built]p2).
6417   static const unsigned FirstIntegralType = 3;
6418   static const unsigned LastIntegralType = 20;
6419   static const unsigned FirstPromotedIntegralType = 3,
6420                         LastPromotedIntegralType = 11;
6421   static const unsigned FirstPromotedArithmeticType = 0,
6422                         LastPromotedArithmeticType = 11;
6423   static const unsigned NumArithmeticTypes = 20;
6424 
6425   /// \brief Get the canonical type for a given arithmetic type index.
6426   CanQualType getArithmeticType(unsigned index) {
6427     assert(index < NumArithmeticTypes);
6428     static CanQualType ASTContext::* const
6429       ArithmeticTypes[NumArithmeticTypes] = {
6430       // Start of promoted types.
6431       &ASTContext::FloatTy,
6432       &ASTContext::DoubleTy,
6433       &ASTContext::LongDoubleTy,
6434 
6435       // Start of integral types.
6436       &ASTContext::IntTy,
6437       &ASTContext::LongTy,
6438       &ASTContext::LongLongTy,
6439       &ASTContext::Int128Ty,
6440       &ASTContext::UnsignedIntTy,
6441       &ASTContext::UnsignedLongTy,
6442       &ASTContext::UnsignedLongLongTy,
6443       &ASTContext::UnsignedInt128Ty,
6444       // End of promoted types.
6445 
6446       &ASTContext::BoolTy,
6447       &ASTContext::CharTy,
6448       &ASTContext::WCharTy,
6449       &ASTContext::Char16Ty,
6450       &ASTContext::Char32Ty,
6451       &ASTContext::SignedCharTy,
6452       &ASTContext::ShortTy,
6453       &ASTContext::UnsignedCharTy,
6454       &ASTContext::UnsignedShortTy,
6455       // End of integral types.
6456       // FIXME: What about complex? What about half?
6457     };
6458     return S.Context.*ArithmeticTypes[index];
6459   }
6460 
6461   /// \brief Gets the canonical type resulting from the usual arithemetic
6462   /// converions for the given arithmetic types.
6463   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6464     // Accelerator table for performing the usual arithmetic conversions.
6465     // The rules are basically:
6466     //   - if either is floating-point, use the wider floating-point
6467     //   - if same signedness, use the higher rank
6468     //   - if same size, use unsigned of the higher rank
6469     //   - use the larger type
6470     // These rules, together with the axiom that higher ranks are
6471     // never smaller, are sufficient to precompute all of these results
6472     // *except* when dealing with signed types of higher rank.
6473     // (we could precompute SLL x UI for all known platforms, but it's
6474     // better not to make any assumptions).
6475     // We assume that int128 has a higher rank than long long on all platforms.
6476     enum PromotedType {
6477             Dep=-1,
6478             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6479     };
6480     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6481                                         [LastPromotedArithmeticType] = {
6482 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6483 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6484 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6485 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6486 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6487 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6488 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6489 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6490 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6491 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6492 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6493     };
6494 
6495     assert(L < LastPromotedArithmeticType);
6496     assert(R < LastPromotedArithmeticType);
6497     int Idx = ConversionsTable[L][R];
6498 
6499     // Fast path: the table gives us a concrete answer.
6500     if (Idx != Dep) return getArithmeticType(Idx);
6501 
6502     // Slow path: we need to compare widths.
6503     // An invariant is that the signed type has higher rank.
6504     CanQualType LT = getArithmeticType(L),
6505                 RT = getArithmeticType(R);
6506     unsigned LW = S.Context.getIntWidth(LT),
6507              RW = S.Context.getIntWidth(RT);
6508 
6509     // If they're different widths, use the signed type.
6510     if (LW > RW) return LT;
6511     else if (LW < RW) return RT;
6512 
6513     // Otherwise, use the unsigned type of the signed type's rank.
6514     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6515     assert(L == SLL || R == SLL);
6516     return S.Context.UnsignedLongLongTy;
6517   }
6518 
6519   /// \brief Helper method to factor out the common pattern of adding overloads
6520   /// for '++' and '--' builtin operators.
6521   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6522                                            bool HasVolatile,
6523                                            bool HasRestrict) {
6524     QualType ParamTypes[2] = {
6525       S.Context.getLValueReferenceType(CandidateTy),
6526       S.Context.IntTy
6527     };
6528 
6529     // Non-volatile version.
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     // Use a heuristic to reduce number of builtin candidates in the set:
6536     // add volatile version only if there are conversions to a volatile type.
6537     if (HasVolatile) {
6538       ParamTypes[0] =
6539         S.Context.getLValueReferenceType(
6540           S.Context.getVolatileType(CandidateTy));
6541       if (NumArgs == 1)
6542         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6543       else
6544         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6545     }
6546 
6547     // Add restrict version only if there are conversions to a restrict type
6548     // and our candidate type is a non-restrict-qualified pointer.
6549     if (HasRestrict && CandidateTy->isAnyPointerType() &&
6550         !CandidateTy.isRestrictQualified()) {
6551       ParamTypes[0]
6552         = S.Context.getLValueReferenceType(
6553             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6554       if (NumArgs == 1)
6555         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6556       else
6557         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6558 
6559       if (HasVolatile) {
6560         ParamTypes[0]
6561           = S.Context.getLValueReferenceType(
6562               S.Context.getCVRQualifiedType(CandidateTy,
6563                                             (Qualifiers::Volatile |
6564                                              Qualifiers::Restrict)));
6565         if (NumArgs == 1)
6566           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6567                                 CandidateSet);
6568         else
6569           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6570       }
6571     }
6572 
6573   }
6574 
6575 public:
6576   BuiltinOperatorOverloadBuilder(
6577     Sema &S, Expr **Args, unsigned NumArgs,
6578     Qualifiers VisibleTypeConversionsQuals,
6579     bool HasArithmeticOrEnumeralCandidateType,
6580     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6581     OverloadCandidateSet &CandidateSet)
6582     : S(S), Args(Args), NumArgs(NumArgs),
6583       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6584       HasArithmeticOrEnumeralCandidateType(
6585         HasArithmeticOrEnumeralCandidateType),
6586       CandidateTypes(CandidateTypes),
6587       CandidateSet(CandidateSet) {
6588     // Validate some of our static helper constants in debug builds.
6589     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6590            "Invalid first promoted integral type");
6591     assert(getArithmeticType(LastPromotedIntegralType - 1)
6592              == S.Context.UnsignedInt128Ty &&
6593            "Invalid last promoted integral type");
6594     assert(getArithmeticType(FirstPromotedArithmeticType)
6595              == S.Context.FloatTy &&
6596            "Invalid first promoted arithmetic type");
6597     assert(getArithmeticType(LastPromotedArithmeticType - 1)
6598              == S.Context.UnsignedInt128Ty &&
6599            "Invalid last promoted arithmetic type");
6600   }
6601 
6602   // C++ [over.built]p3:
6603   //
6604   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6605   //   is either volatile or empty, there exist candidate operator
6606   //   functions of the form
6607   //
6608   //       VQ T&      operator++(VQ T&);
6609   //       T          operator++(VQ T&, int);
6610   //
6611   // C++ [over.built]p4:
6612   //
6613   //   For every pair (T, VQ), where T is an arithmetic type other
6614   //   than bool, and VQ is either volatile or empty, there exist
6615   //   candidate operator functions of the form
6616   //
6617   //       VQ T&      operator--(VQ T&);
6618   //       T          operator--(VQ T&, int);
6619   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6620     if (!HasArithmeticOrEnumeralCandidateType)
6621       return;
6622 
6623     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6624          Arith < NumArithmeticTypes; ++Arith) {
6625       addPlusPlusMinusMinusStyleOverloads(
6626         getArithmeticType(Arith),
6627         VisibleTypeConversionsQuals.hasVolatile(),
6628         VisibleTypeConversionsQuals.hasRestrict());
6629     }
6630   }
6631 
6632   // C++ [over.built]p5:
6633   //
6634   //   For every pair (T, VQ), where T is a cv-qualified or
6635   //   cv-unqualified object type, and VQ is either volatile or
6636   //   empty, there exist candidate operator functions of the form
6637   //
6638   //       T*VQ&      operator++(T*VQ&);
6639   //       T*VQ&      operator--(T*VQ&);
6640   //       T*         operator++(T*VQ&, int);
6641   //       T*         operator--(T*VQ&, int);
6642   void addPlusPlusMinusMinusPointerOverloads() {
6643     for (BuiltinCandidateTypeSet::iterator
6644               Ptr = CandidateTypes[0].pointer_begin(),
6645            PtrEnd = CandidateTypes[0].pointer_end();
6646          Ptr != PtrEnd; ++Ptr) {
6647       // Skip pointer types that aren't pointers to object types.
6648       if (!(*Ptr)->getPointeeType()->isObjectType())
6649         continue;
6650 
6651       addPlusPlusMinusMinusStyleOverloads(*Ptr,
6652         (!(*Ptr).isVolatileQualified() &&
6653          VisibleTypeConversionsQuals.hasVolatile()),
6654         (!(*Ptr).isRestrictQualified() &&
6655          VisibleTypeConversionsQuals.hasRestrict()));
6656     }
6657   }
6658 
6659   // C++ [over.built]p6:
6660   //   For every cv-qualified or cv-unqualified object type T, there
6661   //   exist candidate operator functions of the form
6662   //
6663   //       T&         operator*(T*);
6664   //
6665   // C++ [over.built]p7:
6666   //   For every function type T that does not have cv-qualifiers or a
6667   //   ref-qualifier, there exist candidate operator functions of the form
6668   //       T&         operator*(T*);
6669   void addUnaryStarPointerOverloads() {
6670     for (BuiltinCandidateTypeSet::iterator
6671               Ptr = CandidateTypes[0].pointer_begin(),
6672            PtrEnd = CandidateTypes[0].pointer_end();
6673          Ptr != PtrEnd; ++Ptr) {
6674       QualType ParamTy = *Ptr;
6675       QualType PointeeTy = ParamTy->getPointeeType();
6676       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6677         continue;
6678 
6679       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6680         if (Proto->getTypeQuals() || Proto->getRefQualifier())
6681           continue;
6682 
6683       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6684                             &ParamTy, Args, 1, CandidateSet);
6685     }
6686   }
6687 
6688   // C++ [over.built]p9:
6689   //  For every promoted arithmetic type T, there exist candidate
6690   //  operator functions of the form
6691   //
6692   //       T         operator+(T);
6693   //       T         operator-(T);
6694   void addUnaryPlusOrMinusArithmeticOverloads() {
6695     if (!HasArithmeticOrEnumeralCandidateType)
6696       return;
6697 
6698     for (unsigned Arith = FirstPromotedArithmeticType;
6699          Arith < LastPromotedArithmeticType; ++Arith) {
6700       QualType ArithTy = getArithmeticType(Arith);
6701       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6702     }
6703 
6704     // Extension: We also add these operators for vector types.
6705     for (BuiltinCandidateTypeSet::iterator
6706               Vec = CandidateTypes[0].vector_begin(),
6707            VecEnd = CandidateTypes[0].vector_end();
6708          Vec != VecEnd; ++Vec) {
6709       QualType VecTy = *Vec;
6710       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6711     }
6712   }
6713 
6714   // C++ [over.built]p8:
6715   //   For every type T, there exist candidate operator functions of
6716   //   the form
6717   //
6718   //       T*         operator+(T*);
6719   void addUnaryPlusPointerOverloads() {
6720     for (BuiltinCandidateTypeSet::iterator
6721               Ptr = CandidateTypes[0].pointer_begin(),
6722            PtrEnd = CandidateTypes[0].pointer_end();
6723          Ptr != PtrEnd; ++Ptr) {
6724       QualType ParamTy = *Ptr;
6725       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6726     }
6727   }
6728 
6729   // C++ [over.built]p10:
6730   //   For every promoted integral type T, there exist candidate
6731   //   operator functions of the form
6732   //
6733   //        T         operator~(T);
6734   void addUnaryTildePromotedIntegralOverloads() {
6735     if (!HasArithmeticOrEnumeralCandidateType)
6736       return;
6737 
6738     for (unsigned Int = FirstPromotedIntegralType;
6739          Int < LastPromotedIntegralType; ++Int) {
6740       QualType IntTy = getArithmeticType(Int);
6741       S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6742     }
6743 
6744     // Extension: We also add this operator for vector types.
6745     for (BuiltinCandidateTypeSet::iterator
6746               Vec = CandidateTypes[0].vector_begin(),
6747            VecEnd = CandidateTypes[0].vector_end();
6748          Vec != VecEnd; ++Vec) {
6749       QualType VecTy = *Vec;
6750       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6751     }
6752   }
6753 
6754   // C++ [over.match.oper]p16:
6755   //   For every pointer to member type T, there exist candidate operator
6756   //   functions of the form
6757   //
6758   //        bool operator==(T,T);
6759   //        bool operator!=(T,T);
6760   void addEqualEqualOrNotEqualMemberPointerOverloads() {
6761     /// Set of (canonical) types that we've already handled.
6762     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6763 
6764     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6765       for (BuiltinCandidateTypeSet::iterator
6766                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6767              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6768            MemPtr != MemPtrEnd;
6769            ++MemPtr) {
6770         // Don't add the same builtin candidate twice.
6771         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6772           continue;
6773 
6774         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6775         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6776                               CandidateSet);
6777       }
6778     }
6779   }
6780 
6781   // C++ [over.built]p15:
6782   //
6783   //   For every T, where T is an enumeration type, a pointer type, or
6784   //   std::nullptr_t, there exist candidate operator functions of the form
6785   //
6786   //        bool       operator<(T, T);
6787   //        bool       operator>(T, T);
6788   //        bool       operator<=(T, T);
6789   //        bool       operator>=(T, T);
6790   //        bool       operator==(T, T);
6791   //        bool       operator!=(T, T);
6792   void addRelationalPointerOrEnumeralOverloads() {
6793     // C++ [over.built]p1:
6794     //   If there is a user-written candidate with the same name and parameter
6795     //   types as a built-in candidate operator function, the built-in operator
6796     //   function is hidden and is not included in the set of candidate
6797     //   functions.
6798     //
6799     // The text is actually in a note, but if we don't implement it then we end
6800     // up with ambiguities when the user provides an overloaded operator for
6801     // an enumeration type. Note that only enumeration types have this problem,
6802     // so we track which enumeration types we've seen operators for. Also, the
6803     // only other overloaded operator with enumeration argumenst, operator=,
6804     // cannot be overloaded for enumeration types, so this is the only place
6805     // where we must suppress candidates like this.
6806     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6807       UserDefinedBinaryOperators;
6808 
6809     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6810       if (CandidateTypes[ArgIdx].enumeration_begin() !=
6811           CandidateTypes[ArgIdx].enumeration_end()) {
6812         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6813                                          CEnd = CandidateSet.end();
6814              C != CEnd; ++C) {
6815           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6816             continue;
6817 
6818           QualType FirstParamType =
6819             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6820           QualType SecondParamType =
6821             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6822 
6823           // Skip if either parameter isn't of enumeral type.
6824           if (!FirstParamType->isEnumeralType() ||
6825               !SecondParamType->isEnumeralType())
6826             continue;
6827 
6828           // Add this operator to the set of known user-defined operators.
6829           UserDefinedBinaryOperators.insert(
6830             std::make_pair(S.Context.getCanonicalType(FirstParamType),
6831                            S.Context.getCanonicalType(SecondParamType)));
6832         }
6833       }
6834     }
6835 
6836     /// Set of (canonical) types that we've already handled.
6837     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6838 
6839     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6840       for (BuiltinCandidateTypeSet::iterator
6841                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6842              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6843            Ptr != PtrEnd; ++Ptr) {
6844         // Don't add the same builtin candidate twice.
6845         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6846           continue;
6847 
6848         QualType ParamTypes[2] = { *Ptr, *Ptr };
6849         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6850                               CandidateSet);
6851       }
6852       for (BuiltinCandidateTypeSet::iterator
6853                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6854              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6855            Enum != EnumEnd; ++Enum) {
6856         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6857 
6858         // Don't add the same builtin candidate twice, or if a user defined
6859         // candidate exists.
6860         if (!AddedTypes.insert(CanonType) ||
6861             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6862                                                             CanonType)))
6863           continue;
6864 
6865         QualType ParamTypes[2] = { *Enum, *Enum };
6866         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6867                               CandidateSet);
6868       }
6869 
6870       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6871         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6872         if (AddedTypes.insert(NullPtrTy) &&
6873             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6874                                                              NullPtrTy))) {
6875           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6876           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6877                                 CandidateSet);
6878         }
6879       }
6880     }
6881   }
6882 
6883   // C++ [over.built]p13:
6884   //
6885   //   For every cv-qualified or cv-unqualified object type T
6886   //   there exist candidate operator functions of the form
6887   //
6888   //      T*         operator+(T*, ptrdiff_t);
6889   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
6890   //      T*         operator-(T*, ptrdiff_t);
6891   //      T*         operator+(ptrdiff_t, T*);
6892   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
6893   //
6894   // C++ [over.built]p14:
6895   //
6896   //   For every T, where T is a pointer to object type, there
6897   //   exist candidate operator functions of the form
6898   //
6899   //      ptrdiff_t  operator-(T, T);
6900   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6901     /// Set of (canonical) types that we've already handled.
6902     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6903 
6904     for (int Arg = 0; Arg < 2; ++Arg) {
6905       QualType AsymetricParamTypes[2] = {
6906         S.Context.getPointerDiffType(),
6907         S.Context.getPointerDiffType(),
6908       };
6909       for (BuiltinCandidateTypeSet::iterator
6910                 Ptr = CandidateTypes[Arg].pointer_begin(),
6911              PtrEnd = CandidateTypes[Arg].pointer_end();
6912            Ptr != PtrEnd; ++Ptr) {
6913         QualType PointeeTy = (*Ptr)->getPointeeType();
6914         if (!PointeeTy->isObjectType())
6915           continue;
6916 
6917         AsymetricParamTypes[Arg] = *Ptr;
6918         if (Arg == 0 || Op == OO_Plus) {
6919           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6920           // T* operator+(ptrdiff_t, T*);
6921           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6922                                 CandidateSet);
6923         }
6924         if (Op == OO_Minus) {
6925           // ptrdiff_t operator-(T, T);
6926           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6927             continue;
6928 
6929           QualType ParamTypes[2] = { *Ptr, *Ptr };
6930           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6931                                 Args, 2, CandidateSet);
6932         }
6933       }
6934     }
6935   }
6936 
6937   // C++ [over.built]p12:
6938   //
6939   //   For every pair of promoted arithmetic types L and R, there
6940   //   exist candidate operator functions of the form
6941   //
6942   //        LR         operator*(L, R);
6943   //        LR         operator/(L, R);
6944   //        LR         operator+(L, R);
6945   //        LR         operator-(L, R);
6946   //        bool       operator<(L, R);
6947   //        bool       operator>(L, R);
6948   //        bool       operator<=(L, R);
6949   //        bool       operator>=(L, R);
6950   //        bool       operator==(L, R);
6951   //        bool       operator!=(L, R);
6952   //
6953   //   where LR is the result of the usual arithmetic conversions
6954   //   between types L and R.
6955   //
6956   // C++ [over.built]p24:
6957   //
6958   //   For every pair of promoted arithmetic types L and R, there exist
6959   //   candidate operator functions of the form
6960   //
6961   //        LR       operator?(bool, L, R);
6962   //
6963   //   where LR is the result of the usual arithmetic conversions
6964   //   between types L and R.
6965   // Our candidates ignore the first parameter.
6966   void addGenericBinaryArithmeticOverloads(bool isComparison) {
6967     if (!HasArithmeticOrEnumeralCandidateType)
6968       return;
6969 
6970     for (unsigned Left = FirstPromotedArithmeticType;
6971          Left < LastPromotedArithmeticType; ++Left) {
6972       for (unsigned Right = FirstPromotedArithmeticType;
6973            Right < LastPromotedArithmeticType; ++Right) {
6974         QualType LandR[2] = { getArithmeticType(Left),
6975                               getArithmeticType(Right) };
6976         QualType Result =
6977           isComparison ? S.Context.BoolTy
6978                        : getUsualArithmeticConversions(Left, Right);
6979         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6980       }
6981     }
6982 
6983     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6984     // conditional operator for vector types.
6985     for (BuiltinCandidateTypeSet::iterator
6986               Vec1 = CandidateTypes[0].vector_begin(),
6987            Vec1End = CandidateTypes[0].vector_end();
6988          Vec1 != Vec1End; ++Vec1) {
6989       for (BuiltinCandidateTypeSet::iterator
6990                 Vec2 = CandidateTypes[1].vector_begin(),
6991              Vec2End = CandidateTypes[1].vector_end();
6992            Vec2 != Vec2End; ++Vec2) {
6993         QualType LandR[2] = { *Vec1, *Vec2 };
6994         QualType Result = S.Context.BoolTy;
6995         if (!isComparison) {
6996           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6997             Result = *Vec1;
6998           else
6999             Result = *Vec2;
7000         }
7001 
7002         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7003       }
7004     }
7005   }
7006 
7007   // C++ [over.built]p17:
7008   //
7009   //   For every pair of promoted integral types L and R, there
7010   //   exist candidate operator functions of the form
7011   //
7012   //      LR         operator%(L, R);
7013   //      LR         operator&(L, R);
7014   //      LR         operator^(L, R);
7015   //      LR         operator|(L, R);
7016   //      L          operator<<(L, R);
7017   //      L          operator>>(L, R);
7018   //
7019   //   where LR is the result of the usual arithmetic conversions
7020   //   between types L and R.
7021   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7022     if (!HasArithmeticOrEnumeralCandidateType)
7023       return;
7024 
7025     for (unsigned Left = FirstPromotedIntegralType;
7026          Left < LastPromotedIntegralType; ++Left) {
7027       for (unsigned Right = FirstPromotedIntegralType;
7028            Right < LastPromotedIntegralType; ++Right) {
7029         QualType LandR[2] = { getArithmeticType(Left),
7030                               getArithmeticType(Right) };
7031         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7032             ? LandR[0]
7033             : getUsualArithmeticConversions(Left, Right);
7034         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7035       }
7036     }
7037   }
7038 
7039   // C++ [over.built]p20:
7040   //
7041   //   For every pair (T, VQ), where T is an enumeration or
7042   //   pointer to member type and VQ is either volatile or
7043   //   empty, there exist candidate operator functions of the form
7044   //
7045   //        VQ T&      operator=(VQ T&, T);
7046   void addAssignmentMemberPointerOrEnumeralOverloads() {
7047     /// Set of (canonical) types that we've already handled.
7048     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7049 
7050     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7051       for (BuiltinCandidateTypeSet::iterator
7052                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7053              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7054            Enum != EnumEnd; ++Enum) {
7055         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7056           continue;
7057 
7058         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7059                                                CandidateSet);
7060       }
7061 
7062       for (BuiltinCandidateTypeSet::iterator
7063                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7064              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7065            MemPtr != MemPtrEnd; ++MemPtr) {
7066         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7067           continue;
7068 
7069         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7070                                                CandidateSet);
7071       }
7072     }
7073   }
7074 
7075   // C++ [over.built]p19:
7076   //
7077   //   For every pair (T, VQ), where T is any type and VQ is either
7078   //   volatile or empty, there exist candidate operator functions
7079   //   of the form
7080   //
7081   //        T*VQ&      operator=(T*VQ&, T*);
7082   //
7083   // C++ [over.built]p21:
7084   //
7085   //   For every pair (T, VQ), where T is a cv-qualified or
7086   //   cv-unqualified object type and VQ is either volatile or
7087   //   empty, there exist candidate operator functions of the form
7088   //
7089   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7090   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7091   void addAssignmentPointerOverloads(bool isEqualOp) {
7092     /// Set of (canonical) types that we've already handled.
7093     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7094 
7095     for (BuiltinCandidateTypeSet::iterator
7096               Ptr = CandidateTypes[0].pointer_begin(),
7097            PtrEnd = CandidateTypes[0].pointer_end();
7098          Ptr != PtrEnd; ++Ptr) {
7099       // If this is operator=, keep track of the builtin candidates we added.
7100       if (isEqualOp)
7101         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7102       else if (!(*Ptr)->getPointeeType()->isObjectType())
7103         continue;
7104 
7105       // non-volatile version
7106       QualType ParamTypes[2] = {
7107         S.Context.getLValueReferenceType(*Ptr),
7108         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7109       };
7110       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7111                             /*IsAssigmentOperator=*/ isEqualOp);
7112 
7113       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7114                           VisibleTypeConversionsQuals.hasVolatile();
7115       if (NeedVolatile) {
7116         // volatile version
7117         ParamTypes[0] =
7118           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7119         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7120                               /*IsAssigmentOperator=*/isEqualOp);
7121       }
7122 
7123       if (!(*Ptr).isRestrictQualified() &&
7124           VisibleTypeConversionsQuals.hasRestrict()) {
7125         // restrict version
7126         ParamTypes[0]
7127           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7128         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7129                               /*IsAssigmentOperator=*/isEqualOp);
7130 
7131         if (NeedVolatile) {
7132           // volatile restrict version
7133           ParamTypes[0]
7134             = S.Context.getLValueReferenceType(
7135                 S.Context.getCVRQualifiedType(*Ptr,
7136                                               (Qualifiers::Volatile |
7137                                                Qualifiers::Restrict)));
7138           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7139                                 CandidateSet,
7140                                 /*IsAssigmentOperator=*/isEqualOp);
7141         }
7142       }
7143     }
7144 
7145     if (isEqualOp) {
7146       for (BuiltinCandidateTypeSet::iterator
7147                 Ptr = CandidateTypes[1].pointer_begin(),
7148              PtrEnd = CandidateTypes[1].pointer_end();
7149            Ptr != PtrEnd; ++Ptr) {
7150         // Make sure we don't add the same candidate twice.
7151         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7152           continue;
7153 
7154         QualType ParamTypes[2] = {
7155           S.Context.getLValueReferenceType(*Ptr),
7156           *Ptr,
7157         };
7158 
7159         // non-volatile version
7160         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7161                               /*IsAssigmentOperator=*/true);
7162 
7163         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7164                            VisibleTypeConversionsQuals.hasVolatile();
7165         if (NeedVolatile) {
7166           // volatile version
7167           ParamTypes[0] =
7168             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7169           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7170                                 CandidateSet, /*IsAssigmentOperator=*/true);
7171         }
7172 
7173         if (!(*Ptr).isRestrictQualified() &&
7174             VisibleTypeConversionsQuals.hasRestrict()) {
7175           // restrict version
7176           ParamTypes[0]
7177             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7178           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7179                                 CandidateSet, /*IsAssigmentOperator=*/true);
7180 
7181           if (NeedVolatile) {
7182             // volatile restrict version
7183             ParamTypes[0]
7184               = S.Context.getLValueReferenceType(
7185                   S.Context.getCVRQualifiedType(*Ptr,
7186                                                 (Qualifiers::Volatile |
7187                                                  Qualifiers::Restrict)));
7188             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7189                                   CandidateSet, /*IsAssigmentOperator=*/true);
7190 
7191           }
7192         }
7193       }
7194     }
7195   }
7196 
7197   // C++ [over.built]p18:
7198   //
7199   //   For every triple (L, VQ, R), where L is an arithmetic type,
7200   //   VQ is either volatile or empty, and R is a promoted
7201   //   arithmetic type, there exist candidate operator functions of
7202   //   the form
7203   //
7204   //        VQ L&      operator=(VQ L&, R);
7205   //        VQ L&      operator*=(VQ L&, R);
7206   //        VQ L&      operator/=(VQ L&, R);
7207   //        VQ L&      operator+=(VQ L&, R);
7208   //        VQ L&      operator-=(VQ L&, R);
7209   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7210     if (!HasArithmeticOrEnumeralCandidateType)
7211       return;
7212 
7213     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7214       for (unsigned Right = FirstPromotedArithmeticType;
7215            Right < LastPromotedArithmeticType; ++Right) {
7216         QualType ParamTypes[2];
7217         ParamTypes[1] = getArithmeticType(Right);
7218 
7219         // Add this built-in operator as a candidate (VQ is empty).
7220         ParamTypes[0] =
7221           S.Context.getLValueReferenceType(getArithmeticType(Left));
7222         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7223                               /*IsAssigmentOperator=*/isEqualOp);
7224 
7225         // Add this built-in operator as a candidate (VQ is 'volatile').
7226         if (VisibleTypeConversionsQuals.hasVolatile()) {
7227           ParamTypes[0] =
7228             S.Context.getVolatileType(getArithmeticType(Left));
7229           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7230           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7231                                 CandidateSet,
7232                                 /*IsAssigmentOperator=*/isEqualOp);
7233         }
7234       }
7235     }
7236 
7237     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7238     for (BuiltinCandidateTypeSet::iterator
7239               Vec1 = CandidateTypes[0].vector_begin(),
7240            Vec1End = CandidateTypes[0].vector_end();
7241          Vec1 != Vec1End; ++Vec1) {
7242       for (BuiltinCandidateTypeSet::iterator
7243                 Vec2 = CandidateTypes[1].vector_begin(),
7244              Vec2End = CandidateTypes[1].vector_end();
7245            Vec2 != Vec2End; ++Vec2) {
7246         QualType ParamTypes[2];
7247         ParamTypes[1] = *Vec2;
7248         // Add this built-in operator as a candidate (VQ is empty).
7249         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7250         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7251                               /*IsAssigmentOperator=*/isEqualOp);
7252 
7253         // Add this built-in operator as a candidate (VQ is 'volatile').
7254         if (VisibleTypeConversionsQuals.hasVolatile()) {
7255           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7256           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7257           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7258                                 CandidateSet,
7259                                 /*IsAssigmentOperator=*/isEqualOp);
7260         }
7261       }
7262     }
7263   }
7264 
7265   // C++ [over.built]p22:
7266   //
7267   //   For every triple (L, VQ, R), where L is an integral type, VQ
7268   //   is either volatile or empty, and R is a promoted integral
7269   //   type, there exist candidate operator functions of the form
7270   //
7271   //        VQ L&       operator%=(VQ L&, R);
7272   //        VQ L&       operator<<=(VQ L&, R);
7273   //        VQ L&       operator>>=(VQ L&, R);
7274   //        VQ L&       operator&=(VQ L&, R);
7275   //        VQ L&       operator^=(VQ L&, R);
7276   //        VQ L&       operator|=(VQ L&, R);
7277   void addAssignmentIntegralOverloads() {
7278     if (!HasArithmeticOrEnumeralCandidateType)
7279       return;
7280 
7281     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7282       for (unsigned Right = FirstPromotedIntegralType;
7283            Right < LastPromotedIntegralType; ++Right) {
7284         QualType ParamTypes[2];
7285         ParamTypes[1] = getArithmeticType(Right);
7286 
7287         // Add this built-in operator as a candidate (VQ is empty).
7288         ParamTypes[0] =
7289           S.Context.getLValueReferenceType(getArithmeticType(Left));
7290         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7291         if (VisibleTypeConversionsQuals.hasVolatile()) {
7292           // Add this built-in operator as a candidate (VQ is 'volatile').
7293           ParamTypes[0] = getArithmeticType(Left);
7294           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7295           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7296           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7297                                 CandidateSet);
7298         }
7299       }
7300     }
7301   }
7302 
7303   // C++ [over.operator]p23:
7304   //
7305   //   There also exist candidate operator functions of the form
7306   //
7307   //        bool        operator!(bool);
7308   //        bool        operator&&(bool, bool);
7309   //        bool        operator||(bool, bool);
7310   void addExclaimOverload() {
7311     QualType ParamTy = S.Context.BoolTy;
7312     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7313                           /*IsAssignmentOperator=*/false,
7314                           /*NumContextualBoolArguments=*/1);
7315   }
7316   void addAmpAmpOrPipePipeOverload() {
7317     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7318     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7319                           /*IsAssignmentOperator=*/false,
7320                           /*NumContextualBoolArguments=*/2);
7321   }
7322 
7323   // C++ [over.built]p13:
7324   //
7325   //   For every cv-qualified or cv-unqualified object type T there
7326   //   exist candidate operator functions of the form
7327   //
7328   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7329   //        T&         operator[](T*, ptrdiff_t);
7330   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7331   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7332   //        T&         operator[](ptrdiff_t, T*);
7333   void addSubscriptOverloads() {
7334     for (BuiltinCandidateTypeSet::iterator
7335               Ptr = CandidateTypes[0].pointer_begin(),
7336            PtrEnd = CandidateTypes[0].pointer_end();
7337          Ptr != PtrEnd; ++Ptr) {
7338       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7339       QualType PointeeType = (*Ptr)->getPointeeType();
7340       if (!PointeeType->isObjectType())
7341         continue;
7342 
7343       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7344 
7345       // T& operator[](T*, ptrdiff_t)
7346       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7347     }
7348 
7349     for (BuiltinCandidateTypeSet::iterator
7350               Ptr = CandidateTypes[1].pointer_begin(),
7351            PtrEnd = CandidateTypes[1].pointer_end();
7352          Ptr != PtrEnd; ++Ptr) {
7353       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7354       QualType PointeeType = (*Ptr)->getPointeeType();
7355       if (!PointeeType->isObjectType())
7356         continue;
7357 
7358       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7359 
7360       // T& operator[](ptrdiff_t, T*)
7361       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7362     }
7363   }
7364 
7365   // C++ [over.built]p11:
7366   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7367   //    C1 is the same type as C2 or is a derived class of C2, T is an object
7368   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7369   //    there exist candidate operator functions of the form
7370   //
7371   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7372   //
7373   //    where CV12 is the union of CV1 and CV2.
7374   void addArrowStarOverloads() {
7375     for (BuiltinCandidateTypeSet::iterator
7376              Ptr = CandidateTypes[0].pointer_begin(),
7377            PtrEnd = CandidateTypes[0].pointer_end();
7378          Ptr != PtrEnd; ++Ptr) {
7379       QualType C1Ty = (*Ptr);
7380       QualType C1;
7381       QualifierCollector Q1;
7382       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7383       if (!isa<RecordType>(C1))
7384         continue;
7385       // heuristic to reduce number of builtin candidates in the set.
7386       // Add volatile/restrict version only if there are conversions to a
7387       // volatile/restrict type.
7388       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7389         continue;
7390       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7391         continue;
7392       for (BuiltinCandidateTypeSet::iterator
7393                 MemPtr = CandidateTypes[1].member_pointer_begin(),
7394              MemPtrEnd = CandidateTypes[1].member_pointer_end();
7395            MemPtr != MemPtrEnd; ++MemPtr) {
7396         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7397         QualType C2 = QualType(mptr->getClass(), 0);
7398         C2 = C2.getUnqualifiedType();
7399         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7400           break;
7401         QualType ParamTypes[2] = { *Ptr, *MemPtr };
7402         // build CV12 T&
7403         QualType T = mptr->getPointeeType();
7404         if (!VisibleTypeConversionsQuals.hasVolatile() &&
7405             T.isVolatileQualified())
7406           continue;
7407         if (!VisibleTypeConversionsQuals.hasRestrict() &&
7408             T.isRestrictQualified())
7409           continue;
7410         T = Q1.apply(S.Context, T);
7411         QualType ResultTy = S.Context.getLValueReferenceType(T);
7412         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7413       }
7414     }
7415   }
7416 
7417   // Note that we don't consider the first argument, since it has been
7418   // contextually converted to bool long ago. The candidates below are
7419   // therefore added as binary.
7420   //
7421   // C++ [over.built]p25:
7422   //   For every type T, where T is a pointer, pointer-to-member, or scoped
7423   //   enumeration type, there exist candidate operator functions of the form
7424   //
7425   //        T        operator?(bool, T, T);
7426   //
7427   void addConditionalOperatorOverloads() {
7428     /// Set of (canonical) types that we've already handled.
7429     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7430 
7431     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7432       for (BuiltinCandidateTypeSet::iterator
7433                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7434              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7435            Ptr != PtrEnd; ++Ptr) {
7436         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7437           continue;
7438 
7439         QualType ParamTypes[2] = { *Ptr, *Ptr };
7440         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7441       }
7442 
7443       for (BuiltinCandidateTypeSet::iterator
7444                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7445              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7446            MemPtr != MemPtrEnd; ++MemPtr) {
7447         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7448           continue;
7449 
7450         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7451         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7452       }
7453 
7454       if (S.getLangOpts().CPlusPlus0x) {
7455         for (BuiltinCandidateTypeSet::iterator
7456                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7457                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7458              Enum != EnumEnd; ++Enum) {
7459           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7460             continue;
7461 
7462           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7463             continue;
7464 
7465           QualType ParamTypes[2] = { *Enum, *Enum };
7466           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7467         }
7468       }
7469     }
7470   }
7471 };
7472 
7473 } // end anonymous namespace
7474 
7475 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
7476 /// operator overloads to the candidate set (C++ [over.built]), based
7477 /// on the operator @p Op and the arguments given. For example, if the
7478 /// operator is a binary '+', this routine might add "int
7479 /// operator+(int, int)" to cover integer addition.
7480 void
7481 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7482                                    SourceLocation OpLoc,
7483                                    Expr **Args, unsigned NumArgs,
7484                                    OverloadCandidateSet& CandidateSet) {
7485   // Find all of the types that the arguments can convert to, but only
7486   // if the operator we're looking at has built-in operator candidates
7487   // that make use of these types. Also record whether we encounter non-record
7488   // candidate types or either arithmetic or enumeral candidate types.
7489   Qualifiers VisibleTypeConversionsQuals;
7490   VisibleTypeConversionsQuals.addConst();
7491   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7492     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7493 
7494   bool HasNonRecordCandidateType = false;
7495   bool HasArithmeticOrEnumeralCandidateType = false;
7496   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7497   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7498     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7499     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7500                                                  OpLoc,
7501                                                  true,
7502                                                  (Op == OO_Exclaim ||
7503                                                   Op == OO_AmpAmp ||
7504                                                   Op == OO_PipePipe),
7505                                                  VisibleTypeConversionsQuals);
7506     HasNonRecordCandidateType = HasNonRecordCandidateType ||
7507         CandidateTypes[ArgIdx].hasNonRecordTypes();
7508     HasArithmeticOrEnumeralCandidateType =
7509         HasArithmeticOrEnumeralCandidateType ||
7510         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7511   }
7512 
7513   // Exit early when no non-record types have been added to the candidate set
7514   // for any of the arguments to the operator.
7515   //
7516   // We can't exit early for !, ||, or &&, since there we have always have
7517   // 'bool' overloads.
7518   if (!HasNonRecordCandidateType &&
7519       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7520     return;
7521 
7522   // Setup an object to manage the common state for building overloads.
7523   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7524                                            VisibleTypeConversionsQuals,
7525                                            HasArithmeticOrEnumeralCandidateType,
7526                                            CandidateTypes, CandidateSet);
7527 
7528   // Dispatch over the operation to add in only those overloads which apply.
7529   switch (Op) {
7530   case OO_None:
7531   case NUM_OVERLOADED_OPERATORS:
7532     llvm_unreachable("Expected an overloaded operator");
7533 
7534   case OO_New:
7535   case OO_Delete:
7536   case OO_Array_New:
7537   case OO_Array_Delete:
7538   case OO_Call:
7539     llvm_unreachable(
7540                     "Special operators don't use AddBuiltinOperatorCandidates");
7541 
7542   case OO_Comma:
7543   case OO_Arrow:
7544     // C++ [over.match.oper]p3:
7545     //   -- For the operator ',', the unary operator '&', or the
7546     //      operator '->', the built-in candidates set is empty.
7547     break;
7548 
7549   case OO_Plus: // '+' is either unary or binary
7550     if (NumArgs == 1)
7551       OpBuilder.addUnaryPlusPointerOverloads();
7552     // Fall through.
7553 
7554   case OO_Minus: // '-' is either unary or binary
7555     if (NumArgs == 1) {
7556       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7557     } else {
7558       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7559       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7560     }
7561     break;
7562 
7563   case OO_Star: // '*' is either unary or binary
7564     if (NumArgs == 1)
7565       OpBuilder.addUnaryStarPointerOverloads();
7566     else
7567       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7568     break;
7569 
7570   case OO_Slash:
7571     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7572     break;
7573 
7574   case OO_PlusPlus:
7575   case OO_MinusMinus:
7576     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7577     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7578     break;
7579 
7580   case OO_EqualEqual:
7581   case OO_ExclaimEqual:
7582     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7583     // Fall through.
7584 
7585   case OO_Less:
7586   case OO_Greater:
7587   case OO_LessEqual:
7588   case OO_GreaterEqual:
7589     OpBuilder.addRelationalPointerOrEnumeralOverloads();
7590     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7591     break;
7592 
7593   case OO_Percent:
7594   case OO_Caret:
7595   case OO_Pipe:
7596   case OO_LessLess:
7597   case OO_GreaterGreater:
7598     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7599     break;
7600 
7601   case OO_Amp: // '&' is either unary or binary
7602     if (NumArgs == 1)
7603       // C++ [over.match.oper]p3:
7604       //   -- For the operator ',', the unary operator '&', or the
7605       //      operator '->', the built-in candidates set is empty.
7606       break;
7607 
7608     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7609     break;
7610 
7611   case OO_Tilde:
7612     OpBuilder.addUnaryTildePromotedIntegralOverloads();
7613     break;
7614 
7615   case OO_Equal:
7616     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7617     // Fall through.
7618 
7619   case OO_PlusEqual:
7620   case OO_MinusEqual:
7621     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7622     // Fall through.
7623 
7624   case OO_StarEqual:
7625   case OO_SlashEqual:
7626     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7627     break;
7628 
7629   case OO_PercentEqual:
7630   case OO_LessLessEqual:
7631   case OO_GreaterGreaterEqual:
7632   case OO_AmpEqual:
7633   case OO_CaretEqual:
7634   case OO_PipeEqual:
7635     OpBuilder.addAssignmentIntegralOverloads();
7636     break;
7637 
7638   case OO_Exclaim:
7639     OpBuilder.addExclaimOverload();
7640     break;
7641 
7642   case OO_AmpAmp:
7643   case OO_PipePipe:
7644     OpBuilder.addAmpAmpOrPipePipeOverload();
7645     break;
7646 
7647   case OO_Subscript:
7648     OpBuilder.addSubscriptOverloads();
7649     break;
7650 
7651   case OO_ArrowStar:
7652     OpBuilder.addArrowStarOverloads();
7653     break;
7654 
7655   case OO_Conditional:
7656     OpBuilder.addConditionalOperatorOverloads();
7657     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7658     break;
7659   }
7660 }
7661 
7662 /// \brief Add function candidates found via argument-dependent lookup
7663 /// to the set of overloading candidates.
7664 ///
7665 /// This routine performs argument-dependent name lookup based on the
7666 /// given function name (which may also be an operator name) and adds
7667 /// all of the overload candidates found by ADL to the overload
7668 /// candidate set (C++ [basic.lookup.argdep]).
7669 void
7670 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7671                                            bool Operator, SourceLocation Loc,
7672                                            llvm::ArrayRef<Expr *> Args,
7673                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
7674                                            OverloadCandidateSet& CandidateSet,
7675                                            bool PartialOverloading,
7676                                            bool StdNamespaceIsAssociated) {
7677   ADLResult Fns;
7678 
7679   // FIXME: This approach for uniquing ADL results (and removing
7680   // redundant candidates from the set) relies on pointer-equality,
7681   // which means we need to key off the canonical decl.  However,
7682   // always going back to the canonical decl might not get us the
7683   // right set of default arguments.  What default arguments are
7684   // we supposed to consider on ADL candidates, anyway?
7685 
7686   // FIXME: Pass in the explicit template arguments?
7687   ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
7688                           StdNamespaceIsAssociated);
7689 
7690   // Erase all of the candidates we already knew about.
7691   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7692                                    CandEnd = CandidateSet.end();
7693        Cand != CandEnd; ++Cand)
7694     if (Cand->Function) {
7695       Fns.erase(Cand->Function);
7696       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7697         Fns.erase(FunTmpl);
7698     }
7699 
7700   // For each of the ADL candidates we found, add it to the overload
7701   // set.
7702   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7703     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7704     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7705       if (ExplicitTemplateArgs)
7706         continue;
7707 
7708       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7709                            PartialOverloading);
7710     } else
7711       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7712                                    FoundDecl, ExplicitTemplateArgs,
7713                                    Args, CandidateSet);
7714   }
7715 }
7716 
7717 /// isBetterOverloadCandidate - Determines whether the first overload
7718 /// candidate is a better candidate than the second (C++ 13.3.3p1).
7719 bool
7720 isBetterOverloadCandidate(Sema &S,
7721                           const OverloadCandidate &Cand1,
7722                           const OverloadCandidate &Cand2,
7723                           SourceLocation Loc,
7724                           bool UserDefinedConversion) {
7725   // Define viable functions to be better candidates than non-viable
7726   // functions.
7727   if (!Cand2.Viable)
7728     return Cand1.Viable;
7729   else if (!Cand1.Viable)
7730     return false;
7731 
7732   // C++ [over.match.best]p1:
7733   //
7734   //   -- if F is a static member function, ICS1(F) is defined such
7735   //      that ICS1(F) is neither better nor worse than ICS1(G) for
7736   //      any function G, and, symmetrically, ICS1(G) is neither
7737   //      better nor worse than ICS1(F).
7738   unsigned StartArg = 0;
7739   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7740     StartArg = 1;
7741 
7742   // C++ [over.match.best]p1:
7743   //   A viable function F1 is defined to be a better function than another
7744   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7745   //   conversion sequence than ICSi(F2), and then...
7746   unsigned NumArgs = Cand1.NumConversions;
7747   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7748   bool HasBetterConversion = false;
7749   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7750     switch (CompareImplicitConversionSequences(S,
7751                                                Cand1.Conversions[ArgIdx],
7752                                                Cand2.Conversions[ArgIdx])) {
7753     case ImplicitConversionSequence::Better:
7754       // Cand1 has a better conversion sequence.
7755       HasBetterConversion = true;
7756       break;
7757 
7758     case ImplicitConversionSequence::Worse:
7759       // Cand1 can't be better than Cand2.
7760       return false;
7761 
7762     case ImplicitConversionSequence::Indistinguishable:
7763       // Do nothing.
7764       break;
7765     }
7766   }
7767 
7768   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7769   //       ICSj(F2), or, if not that,
7770   if (HasBetterConversion)
7771     return true;
7772 
7773   //     - F1 is a non-template function and F2 is a function template
7774   //       specialization, or, if not that,
7775   if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7776       Cand2.Function && Cand2.Function->getPrimaryTemplate())
7777     return true;
7778 
7779   //   -- F1 and F2 are function template specializations, and the function
7780   //      template for F1 is more specialized than the template for F2
7781   //      according to the partial ordering rules described in 14.5.5.2, or,
7782   //      if not that,
7783   if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7784       Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7785     if (FunctionTemplateDecl *BetterTemplate
7786           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7787                                          Cand2.Function->getPrimaryTemplate(),
7788                                          Loc,
7789                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7790                                                              : TPOC_Call,
7791                                          Cand1.ExplicitCallArguments))
7792       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7793   }
7794 
7795   //   -- the context is an initialization by user-defined conversion
7796   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7797   //      from the return type of F1 to the destination type (i.e.,
7798   //      the type of the entity being initialized) is a better
7799   //      conversion sequence than the standard conversion sequence
7800   //      from the return type of F2 to the destination type.
7801   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7802       isa<CXXConversionDecl>(Cand1.Function) &&
7803       isa<CXXConversionDecl>(Cand2.Function)) {
7804     // First check whether we prefer one of the conversion functions over the
7805     // other. This only distinguishes the results in non-standard, extension
7806     // cases such as the conversion from a lambda closure type to a function
7807     // pointer or block.
7808     ImplicitConversionSequence::CompareKind FuncResult
7809       = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7810     if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7811       return FuncResult;
7812 
7813     switch (CompareStandardConversionSequences(S,
7814                                                Cand1.FinalConversion,
7815                                                Cand2.FinalConversion)) {
7816     case ImplicitConversionSequence::Better:
7817       // Cand1 has a better conversion sequence.
7818       return true;
7819 
7820     case ImplicitConversionSequence::Worse:
7821       // Cand1 can't be better than Cand2.
7822       return false;
7823 
7824     case ImplicitConversionSequence::Indistinguishable:
7825       // Do nothing
7826       break;
7827     }
7828   }
7829 
7830   return false;
7831 }
7832 
7833 /// \brief Computes the best viable function (C++ 13.3.3)
7834 /// within an overload candidate set.
7835 ///
7836 /// \param Loc The location of the function name (or operator symbol) for
7837 /// which overload resolution occurs.
7838 ///
7839 /// \param Best If overload resolution was successful or found a deleted
7840 /// function, \p Best points to the candidate function found.
7841 ///
7842 /// \returns The result of overload resolution.
7843 OverloadingResult
7844 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
7845                                          iterator &Best,
7846                                          bool UserDefinedConversion) {
7847   // Find the best viable function.
7848   Best = end();
7849   for (iterator Cand = begin(); Cand != end(); ++Cand) {
7850     if (Cand->Viable)
7851       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
7852                                                      UserDefinedConversion))
7853         Best = Cand;
7854   }
7855 
7856   // If we didn't find any viable functions, abort.
7857   if (Best == end())
7858     return OR_No_Viable_Function;
7859 
7860   // Make sure that this function is better than every other viable
7861   // function. If not, we have an ambiguity.
7862   for (iterator Cand = begin(); Cand != end(); ++Cand) {
7863     if (Cand->Viable &&
7864         Cand != Best &&
7865         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
7866                                    UserDefinedConversion)) {
7867       Best = end();
7868       return OR_Ambiguous;
7869     }
7870   }
7871 
7872   // Best is the best viable function.
7873   if (Best->Function &&
7874       (Best->Function->isDeleted() ||
7875        S.isFunctionConsideredUnavailable(Best->Function)))
7876     return OR_Deleted;
7877 
7878   return OR_Success;
7879 }
7880 
7881 namespace {
7882 
7883 enum OverloadCandidateKind {
7884   oc_function,
7885   oc_method,
7886   oc_constructor,
7887   oc_function_template,
7888   oc_method_template,
7889   oc_constructor_template,
7890   oc_implicit_default_constructor,
7891   oc_implicit_copy_constructor,
7892   oc_implicit_move_constructor,
7893   oc_implicit_copy_assignment,
7894   oc_implicit_move_assignment,
7895   oc_implicit_inherited_constructor
7896 };
7897 
7898 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7899                                                 FunctionDecl *Fn,
7900                                                 std::string &Description) {
7901   bool isTemplate = false;
7902 
7903   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7904     isTemplate = true;
7905     Description = S.getTemplateArgumentBindingsText(
7906       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7907   }
7908 
7909   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
7910     if (!Ctor->isImplicit())
7911       return isTemplate ? oc_constructor_template : oc_constructor;
7912 
7913     if (Ctor->getInheritedConstructor())
7914       return oc_implicit_inherited_constructor;
7915 
7916     if (Ctor->isDefaultConstructor())
7917       return oc_implicit_default_constructor;
7918 
7919     if (Ctor->isMoveConstructor())
7920       return oc_implicit_move_constructor;
7921 
7922     assert(Ctor->isCopyConstructor() &&
7923            "unexpected sort of implicit constructor");
7924     return oc_implicit_copy_constructor;
7925   }
7926 
7927   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7928     // This actually gets spelled 'candidate function' for now, but
7929     // it doesn't hurt to split it out.
7930     if (!Meth->isImplicit())
7931       return isTemplate ? oc_method_template : oc_method;
7932 
7933     if (Meth->isMoveAssignmentOperator())
7934       return oc_implicit_move_assignment;
7935 
7936     if (Meth->isCopyAssignmentOperator())
7937       return oc_implicit_copy_assignment;
7938 
7939     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7940     return oc_method;
7941   }
7942 
7943   return isTemplate ? oc_function_template : oc_function;
7944 }
7945 
7946 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7947   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7948   if (!Ctor) return;
7949 
7950   Ctor = Ctor->getInheritedConstructor();
7951   if (!Ctor) return;
7952 
7953   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7954 }
7955 
7956 } // end anonymous namespace
7957 
7958 // Notes the location of an overload candidate.
7959 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
7960   std::string FnDesc;
7961   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
7962   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7963                              << (unsigned) K << FnDesc;
7964   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7965   Diag(Fn->getLocation(), PD);
7966   MaybeEmitInheritedConstructorNote(*this, Fn);
7967 }
7968 
7969 //Notes the location of all overload candidates designated through
7970 // OverloadedExpr
7971 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
7972   assert(OverloadedExpr->getType() == Context.OverloadTy);
7973 
7974   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7975   OverloadExpr *OvlExpr = Ovl.Expression;
7976 
7977   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7978                             IEnd = OvlExpr->decls_end();
7979        I != IEnd; ++I) {
7980     if (FunctionTemplateDecl *FunTmpl =
7981                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
7982       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
7983     } else if (FunctionDecl *Fun
7984                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
7985       NoteOverloadCandidate(Fun, DestType);
7986     }
7987   }
7988 }
7989 
7990 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
7991 /// "lead" diagnostic; it will be given two arguments, the source and
7992 /// target types of the conversion.
7993 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7994                                  Sema &S,
7995                                  SourceLocation CaretLoc,
7996                                  const PartialDiagnostic &PDiag) const {
7997   S.Diag(CaretLoc, PDiag)
7998     << Ambiguous.getFromType() << Ambiguous.getToType();
7999   for (AmbiguousConversionSequence::const_iterator
8000          I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8001     S.NoteOverloadCandidate(*I);
8002   }
8003 }
8004 
8005 namespace {
8006 
8007 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8008   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8009   assert(Conv.isBad());
8010   assert(Cand->Function && "for now, candidate must be a function");
8011   FunctionDecl *Fn = Cand->Function;
8012 
8013   // There's a conversion slot for the object argument if this is a
8014   // non-constructor method.  Note that 'I' corresponds the
8015   // conversion-slot index.
8016   bool isObjectArgument = false;
8017   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8018     if (I == 0)
8019       isObjectArgument = true;
8020     else
8021       I--;
8022   }
8023 
8024   std::string FnDesc;
8025   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8026 
8027   Expr *FromExpr = Conv.Bad.FromExpr;
8028   QualType FromTy = Conv.Bad.getFromType();
8029   QualType ToTy = Conv.Bad.getToType();
8030 
8031   if (FromTy == S.Context.OverloadTy) {
8032     assert(FromExpr && "overload set argument came from implicit argument?");
8033     Expr *E = FromExpr->IgnoreParens();
8034     if (isa<UnaryOperator>(E))
8035       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8036     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8037 
8038     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8039       << (unsigned) FnKind << FnDesc
8040       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8041       << ToTy << Name << I+1;
8042     MaybeEmitInheritedConstructorNote(S, Fn);
8043     return;
8044   }
8045 
8046   // Do some hand-waving analysis to see if the non-viability is due
8047   // to a qualifier mismatch.
8048   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8049   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8050   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8051     CToTy = RT->getPointeeType();
8052   else {
8053     // TODO: detect and diagnose the full richness of const mismatches.
8054     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8055       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8056         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8057   }
8058 
8059   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8060       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8061     Qualifiers FromQs = CFromTy.getQualifiers();
8062     Qualifiers ToQs = CToTy.getQualifiers();
8063 
8064     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8065       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8066         << (unsigned) FnKind << FnDesc
8067         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8068         << FromTy
8069         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8070         << (unsigned) isObjectArgument << I+1;
8071       MaybeEmitInheritedConstructorNote(S, Fn);
8072       return;
8073     }
8074 
8075     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8076       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8077         << (unsigned) FnKind << FnDesc
8078         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8079         << FromTy
8080         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8081         << (unsigned) isObjectArgument << I+1;
8082       MaybeEmitInheritedConstructorNote(S, Fn);
8083       return;
8084     }
8085 
8086     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8087       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8088       << (unsigned) FnKind << FnDesc
8089       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8090       << FromTy
8091       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8092       << (unsigned) isObjectArgument << I+1;
8093       MaybeEmitInheritedConstructorNote(S, Fn);
8094       return;
8095     }
8096 
8097     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8098     assert(CVR && "unexpected qualifiers mismatch");
8099 
8100     if (isObjectArgument) {
8101       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8102         << (unsigned) FnKind << FnDesc
8103         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8104         << FromTy << (CVR - 1);
8105     } else {
8106       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8107         << (unsigned) FnKind << FnDesc
8108         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8109         << FromTy << (CVR - 1) << I+1;
8110     }
8111     MaybeEmitInheritedConstructorNote(S, Fn);
8112     return;
8113   }
8114 
8115   // Special diagnostic for failure to convert an initializer list, since
8116   // telling the user that it has type void is not useful.
8117   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8118     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8119       << (unsigned) FnKind << FnDesc
8120       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8121       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8122     MaybeEmitInheritedConstructorNote(S, Fn);
8123     return;
8124   }
8125 
8126   // Diagnose references or pointers to incomplete types differently,
8127   // since it's far from impossible that the incompleteness triggered
8128   // the failure.
8129   QualType TempFromTy = FromTy.getNonReferenceType();
8130   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8131     TempFromTy = PTy->getPointeeType();
8132   if (TempFromTy->isIncompleteType()) {
8133     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8134       << (unsigned) FnKind << FnDesc
8135       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8136       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8137     MaybeEmitInheritedConstructorNote(S, Fn);
8138     return;
8139   }
8140 
8141   // Diagnose base -> derived pointer conversions.
8142   unsigned BaseToDerivedConversion = 0;
8143   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8144     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8145       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8146                                                FromPtrTy->getPointeeType()) &&
8147           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8148           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8149           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8150                           FromPtrTy->getPointeeType()))
8151         BaseToDerivedConversion = 1;
8152     }
8153   } else if (const ObjCObjectPointerType *FromPtrTy
8154                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8155     if (const ObjCObjectPointerType *ToPtrTy
8156                                         = ToTy->getAs<ObjCObjectPointerType>())
8157       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8158         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8159           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8160                                                 FromPtrTy->getPointeeType()) &&
8161               FromIface->isSuperClassOf(ToIface))
8162             BaseToDerivedConversion = 2;
8163   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8164     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8165         !FromTy->isIncompleteType() &&
8166         !ToRefTy->getPointeeType()->isIncompleteType() &&
8167         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8168       BaseToDerivedConversion = 3;
8169     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8170                ToTy.getNonReferenceType().getCanonicalType() ==
8171                FromTy.getNonReferenceType().getCanonicalType()) {
8172       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8173         << (unsigned) FnKind << FnDesc
8174         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8175         << (unsigned) isObjectArgument << I + 1;
8176       MaybeEmitInheritedConstructorNote(S, Fn);
8177       return;
8178     }
8179   }
8180 
8181   if (BaseToDerivedConversion) {
8182     S.Diag(Fn->getLocation(),
8183            diag::note_ovl_candidate_bad_base_to_derived_conv)
8184       << (unsigned) FnKind << FnDesc
8185       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8186       << (BaseToDerivedConversion - 1)
8187       << FromTy << ToTy << I+1;
8188     MaybeEmitInheritedConstructorNote(S, Fn);
8189     return;
8190   }
8191 
8192   if (isa<ObjCObjectPointerType>(CFromTy) &&
8193       isa<PointerType>(CToTy)) {
8194       Qualifiers FromQs = CFromTy.getQualifiers();
8195       Qualifiers ToQs = CToTy.getQualifiers();
8196       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8197         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8198         << (unsigned) FnKind << FnDesc
8199         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8200         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8201         MaybeEmitInheritedConstructorNote(S, Fn);
8202         return;
8203       }
8204   }
8205 
8206   // Emit the generic diagnostic and, optionally, add the hints to it.
8207   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8208   FDiag << (unsigned) FnKind << FnDesc
8209     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8210     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8211     << (unsigned) (Cand->Fix.Kind);
8212 
8213   // If we can fix the conversion, suggest the FixIts.
8214   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8215        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8216     FDiag << *HI;
8217   S.Diag(Fn->getLocation(), FDiag);
8218 
8219   MaybeEmitInheritedConstructorNote(S, Fn);
8220 }
8221 
8222 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8223                            unsigned NumFormalArgs) {
8224   // TODO: treat calls to a missing default constructor as a special case
8225 
8226   FunctionDecl *Fn = Cand->Function;
8227   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8228 
8229   unsigned MinParams = Fn->getMinRequiredArguments();
8230 
8231   // With invalid overloaded operators, it's possible that we think we
8232   // have an arity mismatch when it fact it looks like we have the
8233   // right number of arguments, because only overloaded operators have
8234   // the weird behavior of overloading member and non-member functions.
8235   // Just don't report anything.
8236   if (Fn->isInvalidDecl() &&
8237       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8238     return;
8239 
8240   // at least / at most / exactly
8241   unsigned mode, modeCount;
8242   if (NumFormalArgs < MinParams) {
8243     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8244            (Cand->FailureKind == ovl_fail_bad_deduction &&
8245             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8246     if (MinParams != FnTy->getNumArgs() ||
8247         FnTy->isVariadic() || FnTy->isTemplateVariadic())
8248       mode = 0; // "at least"
8249     else
8250       mode = 2; // "exactly"
8251     modeCount = MinParams;
8252   } else {
8253     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8254            (Cand->FailureKind == ovl_fail_bad_deduction &&
8255             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8256     if (MinParams != FnTy->getNumArgs())
8257       mode = 1; // "at most"
8258     else
8259       mode = 2; // "exactly"
8260     modeCount = FnTy->getNumArgs();
8261   }
8262 
8263   std::string Description;
8264   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8265 
8266   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8267     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8268       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8269       << Fn->getParamDecl(0) << NumFormalArgs;
8270   else
8271     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8272       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8273       << modeCount << NumFormalArgs;
8274   MaybeEmitInheritedConstructorNote(S, Fn);
8275 }
8276 
8277 /// Diagnose a failed template-argument deduction.
8278 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8279                           unsigned NumArgs) {
8280   FunctionDecl *Fn = Cand->Function; // pattern
8281 
8282   TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
8283   NamedDecl *ParamD;
8284   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8285   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8286   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8287   switch (Cand->DeductionFailure.Result) {
8288   case Sema::TDK_Success:
8289     llvm_unreachable("TDK_success while diagnosing bad deduction");
8290 
8291   case Sema::TDK_Incomplete: {
8292     assert(ParamD && "no parameter found for incomplete deduction result");
8293     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8294       << ParamD->getDeclName();
8295     MaybeEmitInheritedConstructorNote(S, Fn);
8296     return;
8297   }
8298 
8299   case Sema::TDK_Underqualified: {
8300     assert(ParamD && "no parameter found for bad qualifiers deduction result");
8301     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8302 
8303     QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8304 
8305     // Param will have been canonicalized, but it should just be a
8306     // qualified version of ParamD, so move the qualifiers to that.
8307     QualifierCollector Qs;
8308     Qs.strip(Param);
8309     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8310     assert(S.Context.hasSameType(Param, NonCanonParam));
8311 
8312     // Arg has also been canonicalized, but there's nothing we can do
8313     // about that.  It also doesn't matter as much, because it won't
8314     // have any template parameters in it (because deduction isn't
8315     // done on dependent types).
8316     QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8317 
8318     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8319       << ParamD->getDeclName() << Arg << NonCanonParam;
8320     MaybeEmitInheritedConstructorNote(S, Fn);
8321     return;
8322   }
8323 
8324   case Sema::TDK_Inconsistent: {
8325     assert(ParamD && "no parameter found for inconsistent deduction result");
8326     int which = 0;
8327     if (isa<TemplateTypeParmDecl>(ParamD))
8328       which = 0;
8329     else if (isa<NonTypeTemplateParmDecl>(ParamD))
8330       which = 1;
8331     else {
8332       which = 2;
8333     }
8334 
8335     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8336       << which << ParamD->getDeclName()
8337       << *Cand->DeductionFailure.getFirstArg()
8338       << *Cand->DeductionFailure.getSecondArg();
8339     MaybeEmitInheritedConstructorNote(S, Fn);
8340     return;
8341   }
8342 
8343   case Sema::TDK_InvalidExplicitArguments:
8344     assert(ParamD && "no parameter found for invalid explicit arguments");
8345     if (ParamD->getDeclName())
8346       S.Diag(Fn->getLocation(),
8347              diag::note_ovl_candidate_explicit_arg_mismatch_named)
8348         << ParamD->getDeclName();
8349     else {
8350       int index = 0;
8351       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8352         index = TTP->getIndex();
8353       else if (NonTypeTemplateParmDecl *NTTP
8354                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8355         index = NTTP->getIndex();
8356       else
8357         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8358       S.Diag(Fn->getLocation(),
8359              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8360         << (index + 1);
8361     }
8362     MaybeEmitInheritedConstructorNote(S, Fn);
8363     return;
8364 
8365   case Sema::TDK_TooManyArguments:
8366   case Sema::TDK_TooFewArguments:
8367     DiagnoseArityMismatch(S, Cand, NumArgs);
8368     return;
8369 
8370   case Sema::TDK_InstantiationDepth:
8371     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8372     MaybeEmitInheritedConstructorNote(S, Fn);
8373     return;
8374 
8375   case Sema::TDK_SubstitutionFailure: {
8376     // Format the template argument list into the argument string.
8377     llvm::SmallString<128> TemplateArgString;
8378     if (TemplateArgumentList *Args =
8379           Cand->DeductionFailure.getTemplateArgumentList()) {
8380       TemplateArgString = " ";
8381       TemplateArgString += S.getTemplateArgumentBindingsText(
8382           Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8383     }
8384 
8385     // If this candidate was disabled by enable_if, say so.
8386     PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8387     if (PDiag && PDiag->second.getDiagID() ==
8388           diag::err_typename_nested_not_found_enable_if) {
8389       // FIXME: Use the source range of the condition, and the fully-qualified
8390       //        name of the enable_if template. These are both present in PDiag.
8391       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8392         << "'enable_if'" << TemplateArgString;
8393       return;
8394     }
8395 
8396     // Format the SFINAE diagnostic into the argument string.
8397     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8398     //        formatted message in another diagnostic.
8399     llvm::SmallString<128> SFINAEArgString;
8400     SourceRange R;
8401     if (PDiag) {
8402       SFINAEArgString = ": ";
8403       R = SourceRange(PDiag->first, PDiag->first);
8404       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8405     }
8406 
8407     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8408       << TemplateArgString << SFINAEArgString << R;
8409     MaybeEmitInheritedConstructorNote(S, Fn);
8410     return;
8411   }
8412 
8413   // TODO: diagnose these individually, then kill off
8414   // note_ovl_candidate_bad_deduction, which is uselessly vague.
8415   case Sema::TDK_NonDeducedMismatch:
8416   case Sema::TDK_FailedOverloadResolution:
8417     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8418     MaybeEmitInheritedConstructorNote(S, Fn);
8419     return;
8420   }
8421 }
8422 
8423 /// CUDA: diagnose an invalid call across targets.
8424 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8425   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8426   FunctionDecl *Callee = Cand->Function;
8427 
8428   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8429                            CalleeTarget = S.IdentifyCUDATarget(Callee);
8430 
8431   std::string FnDesc;
8432   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8433 
8434   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8435       << (unsigned) FnKind << CalleeTarget << CallerTarget;
8436 }
8437 
8438 /// Generates a 'note' diagnostic for an overload candidate.  We've
8439 /// already generated a primary error at the call site.
8440 ///
8441 /// It really does need to be a single diagnostic with its caret
8442 /// pointed at the candidate declaration.  Yes, this creates some
8443 /// major challenges of technical writing.  Yes, this makes pointing
8444 /// out problems with specific arguments quite awkward.  It's still
8445 /// better than generating twenty screens of text for every failed
8446 /// overload.
8447 ///
8448 /// It would be great to be able to express per-candidate problems
8449 /// more richly for those diagnostic clients that cared, but we'd
8450 /// still have to be just as careful with the default diagnostics.
8451 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8452                            unsigned NumArgs) {
8453   FunctionDecl *Fn = Cand->Function;
8454 
8455   // Note deleted candidates, but only if they're viable.
8456   if (Cand->Viable && (Fn->isDeleted() ||
8457       S.isFunctionConsideredUnavailable(Fn))) {
8458     std::string FnDesc;
8459     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8460 
8461     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8462       << FnKind << FnDesc
8463       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8464     MaybeEmitInheritedConstructorNote(S, Fn);
8465     return;
8466   }
8467 
8468   // We don't really have anything else to say about viable candidates.
8469   if (Cand->Viable) {
8470     S.NoteOverloadCandidate(Fn);
8471     return;
8472   }
8473 
8474   switch (Cand->FailureKind) {
8475   case ovl_fail_too_many_arguments:
8476   case ovl_fail_too_few_arguments:
8477     return DiagnoseArityMismatch(S, Cand, NumArgs);
8478 
8479   case ovl_fail_bad_deduction:
8480     return DiagnoseBadDeduction(S, Cand, NumArgs);
8481 
8482   case ovl_fail_trivial_conversion:
8483   case ovl_fail_bad_final_conversion:
8484   case ovl_fail_final_conversion_not_exact:
8485     return S.NoteOverloadCandidate(Fn);
8486 
8487   case ovl_fail_bad_conversion: {
8488     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8489     for (unsigned N = Cand->NumConversions; I != N; ++I)
8490       if (Cand->Conversions[I].isBad())
8491         return DiagnoseBadConversion(S, Cand, I);
8492 
8493     // FIXME: this currently happens when we're called from SemaInit
8494     // when user-conversion overload fails.  Figure out how to handle
8495     // those conditions and diagnose them well.
8496     return S.NoteOverloadCandidate(Fn);
8497   }
8498 
8499   case ovl_fail_bad_target:
8500     return DiagnoseBadTarget(S, Cand);
8501   }
8502 }
8503 
8504 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8505   // Desugar the type of the surrogate down to a function type,
8506   // retaining as many typedefs as possible while still showing
8507   // the function type (and, therefore, its parameter types).
8508   QualType FnType = Cand->Surrogate->getConversionType();
8509   bool isLValueReference = false;
8510   bool isRValueReference = false;
8511   bool isPointer = false;
8512   if (const LValueReferenceType *FnTypeRef =
8513         FnType->getAs<LValueReferenceType>()) {
8514     FnType = FnTypeRef->getPointeeType();
8515     isLValueReference = true;
8516   } else if (const RValueReferenceType *FnTypeRef =
8517                FnType->getAs<RValueReferenceType>()) {
8518     FnType = FnTypeRef->getPointeeType();
8519     isRValueReference = true;
8520   }
8521   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8522     FnType = FnTypePtr->getPointeeType();
8523     isPointer = true;
8524   }
8525   // Desugar down to a function type.
8526   FnType = QualType(FnType->getAs<FunctionType>(), 0);
8527   // Reconstruct the pointer/reference as appropriate.
8528   if (isPointer) FnType = S.Context.getPointerType(FnType);
8529   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8530   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8531 
8532   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8533     << FnType;
8534   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8535 }
8536 
8537 void NoteBuiltinOperatorCandidate(Sema &S,
8538                                   const char *Opc,
8539                                   SourceLocation OpLoc,
8540                                   OverloadCandidate *Cand) {
8541   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8542   std::string TypeStr("operator");
8543   TypeStr += Opc;
8544   TypeStr += "(";
8545   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8546   if (Cand->NumConversions == 1) {
8547     TypeStr += ")";
8548     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8549   } else {
8550     TypeStr += ", ";
8551     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8552     TypeStr += ")";
8553     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8554   }
8555 }
8556 
8557 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8558                                   OverloadCandidate *Cand) {
8559   unsigned NoOperands = Cand->NumConversions;
8560   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8561     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8562     if (ICS.isBad()) break; // all meaningless after first invalid
8563     if (!ICS.isAmbiguous()) continue;
8564 
8565     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8566                               S.PDiag(diag::note_ambiguous_type_conversion));
8567   }
8568 }
8569 
8570 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8571   if (Cand->Function)
8572     return Cand->Function->getLocation();
8573   if (Cand->IsSurrogate)
8574     return Cand->Surrogate->getLocation();
8575   return SourceLocation();
8576 }
8577 
8578 static unsigned
8579 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8580   switch ((Sema::TemplateDeductionResult)DFI.Result) {
8581   case Sema::TDK_Success:
8582     llvm_unreachable("TDK_success while diagnosing bad deduction");
8583 
8584   case Sema::TDK_Invalid:
8585   case Sema::TDK_Incomplete:
8586     return 1;
8587 
8588   case Sema::TDK_Underqualified:
8589   case Sema::TDK_Inconsistent:
8590     return 2;
8591 
8592   case Sema::TDK_SubstitutionFailure:
8593   case Sema::TDK_NonDeducedMismatch:
8594     return 3;
8595 
8596   case Sema::TDK_InstantiationDepth:
8597   case Sema::TDK_FailedOverloadResolution:
8598     return 4;
8599 
8600   case Sema::TDK_InvalidExplicitArguments:
8601     return 5;
8602 
8603   case Sema::TDK_TooManyArguments:
8604   case Sema::TDK_TooFewArguments:
8605     return 6;
8606   }
8607   llvm_unreachable("Unhandled deduction result");
8608 }
8609 
8610 struct CompareOverloadCandidatesForDisplay {
8611   Sema &S;
8612   CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8613 
8614   bool operator()(const OverloadCandidate *L,
8615                   const OverloadCandidate *R) {
8616     // Fast-path this check.
8617     if (L == R) return false;
8618 
8619     // Order first by viability.
8620     if (L->Viable) {
8621       if (!R->Viable) return true;
8622 
8623       // TODO: introduce a tri-valued comparison for overload
8624       // candidates.  Would be more worthwhile if we had a sort
8625       // that could exploit it.
8626       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8627       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8628     } else if (R->Viable)
8629       return false;
8630 
8631     assert(L->Viable == R->Viable);
8632 
8633     // Criteria by which we can sort non-viable candidates:
8634     if (!L->Viable) {
8635       // 1. Arity mismatches come after other candidates.
8636       if (L->FailureKind == ovl_fail_too_many_arguments ||
8637           L->FailureKind == ovl_fail_too_few_arguments)
8638         return false;
8639       if (R->FailureKind == ovl_fail_too_many_arguments ||
8640           R->FailureKind == ovl_fail_too_few_arguments)
8641         return true;
8642 
8643       // 2. Bad conversions come first and are ordered by the number
8644       // of bad conversions and quality of good conversions.
8645       if (L->FailureKind == ovl_fail_bad_conversion) {
8646         if (R->FailureKind != ovl_fail_bad_conversion)
8647           return true;
8648 
8649         // The conversion that can be fixed with a smaller number of changes,
8650         // comes first.
8651         unsigned numLFixes = L->Fix.NumConversionsFixed;
8652         unsigned numRFixes = R->Fix.NumConversionsFixed;
8653         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8654         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8655         if (numLFixes != numRFixes) {
8656           if (numLFixes < numRFixes)
8657             return true;
8658           else
8659             return false;
8660         }
8661 
8662         // If there's any ordering between the defined conversions...
8663         // FIXME: this might not be transitive.
8664         assert(L->NumConversions == R->NumConversions);
8665 
8666         int leftBetter = 0;
8667         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8668         for (unsigned E = L->NumConversions; I != E; ++I) {
8669           switch (CompareImplicitConversionSequences(S,
8670                                                      L->Conversions[I],
8671                                                      R->Conversions[I])) {
8672           case ImplicitConversionSequence::Better:
8673             leftBetter++;
8674             break;
8675 
8676           case ImplicitConversionSequence::Worse:
8677             leftBetter--;
8678             break;
8679 
8680           case ImplicitConversionSequence::Indistinguishable:
8681             break;
8682           }
8683         }
8684         if (leftBetter > 0) return true;
8685         if (leftBetter < 0) return false;
8686 
8687       } else if (R->FailureKind == ovl_fail_bad_conversion)
8688         return false;
8689 
8690       if (L->FailureKind == ovl_fail_bad_deduction) {
8691         if (R->FailureKind != ovl_fail_bad_deduction)
8692           return true;
8693 
8694         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8695           return RankDeductionFailure(L->DeductionFailure)
8696                < RankDeductionFailure(R->DeductionFailure);
8697       } else if (R->FailureKind == ovl_fail_bad_deduction)
8698         return false;
8699 
8700       // TODO: others?
8701     }
8702 
8703     // Sort everything else by location.
8704     SourceLocation LLoc = GetLocationForCandidate(L);
8705     SourceLocation RLoc = GetLocationForCandidate(R);
8706 
8707     // Put candidates without locations (e.g. builtins) at the end.
8708     if (LLoc.isInvalid()) return false;
8709     if (RLoc.isInvalid()) return true;
8710 
8711     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8712   }
8713 };
8714 
8715 /// CompleteNonViableCandidate - Normally, overload resolution only
8716 /// computes up to the first. Produces the FixIt set if possible.
8717 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8718                                 llvm::ArrayRef<Expr *> Args) {
8719   assert(!Cand->Viable);
8720 
8721   // Don't do anything on failures other than bad conversion.
8722   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8723 
8724   // We only want the FixIts if all the arguments can be corrected.
8725   bool Unfixable = false;
8726   // Use a implicit copy initialization to check conversion fixes.
8727   Cand->Fix.setConversionChecker(TryCopyInitialization);
8728 
8729   // Skip forward to the first bad conversion.
8730   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
8731   unsigned ConvCount = Cand->NumConversions;
8732   while (true) {
8733     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8734     ConvIdx++;
8735     if (Cand->Conversions[ConvIdx - 1].isBad()) {
8736       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
8737       break;
8738     }
8739   }
8740 
8741   if (ConvIdx == ConvCount)
8742     return;
8743 
8744   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8745          "remaining conversion is initialized?");
8746 
8747   // FIXME: this should probably be preserved from the overload
8748   // operation somehow.
8749   bool SuppressUserConversions = false;
8750 
8751   const FunctionProtoType* Proto;
8752   unsigned ArgIdx = ConvIdx;
8753 
8754   if (Cand->IsSurrogate) {
8755     QualType ConvType
8756       = Cand->Surrogate->getConversionType().getNonReferenceType();
8757     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8758       ConvType = ConvPtrType->getPointeeType();
8759     Proto = ConvType->getAs<FunctionProtoType>();
8760     ArgIdx--;
8761   } else if (Cand->Function) {
8762     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8763     if (isa<CXXMethodDecl>(Cand->Function) &&
8764         !isa<CXXConstructorDecl>(Cand->Function))
8765       ArgIdx--;
8766   } else {
8767     // Builtin binary operator with a bad first conversion.
8768     assert(ConvCount <= 3);
8769     for (; ConvIdx != ConvCount; ++ConvIdx)
8770       Cand->Conversions[ConvIdx]
8771         = TryCopyInitialization(S, Args[ConvIdx],
8772                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
8773                                 SuppressUserConversions,
8774                                 /*InOverloadResolution*/ true,
8775                                 /*AllowObjCWritebackConversion=*/
8776                                   S.getLangOpts().ObjCAutoRefCount);
8777     return;
8778   }
8779 
8780   // Fill in the rest of the conversions.
8781   unsigned NumArgsInProto = Proto->getNumArgs();
8782   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
8783     if (ArgIdx < NumArgsInProto) {
8784       Cand->Conversions[ConvIdx]
8785         = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
8786                                 SuppressUserConversions,
8787                                 /*InOverloadResolution=*/true,
8788                                 /*AllowObjCWritebackConversion=*/
8789                                   S.getLangOpts().ObjCAutoRefCount);
8790       // Store the FixIt in the candidate if it exists.
8791       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
8792         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
8793     }
8794     else
8795       Cand->Conversions[ConvIdx].setEllipsis();
8796   }
8797 }
8798 
8799 } // end anonymous namespace
8800 
8801 /// PrintOverloadCandidates - When overload resolution fails, prints
8802 /// diagnostic messages containing the candidates in the candidate
8803 /// set.
8804 void OverloadCandidateSet::NoteCandidates(Sema &S,
8805                                           OverloadCandidateDisplayKind OCD,
8806                                           llvm::ArrayRef<Expr *> Args,
8807                                           const char *Opc,
8808                                           SourceLocation OpLoc) {
8809   // Sort the candidates by viability and position.  Sorting directly would
8810   // be prohibitive, so we make a set of pointers and sort those.
8811   SmallVector<OverloadCandidate*, 32> Cands;
8812   if (OCD == OCD_AllCandidates) Cands.reserve(size());
8813   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
8814     if (Cand->Viable)
8815       Cands.push_back(Cand);
8816     else if (OCD == OCD_AllCandidates) {
8817       CompleteNonViableCandidate(S, Cand, Args);
8818       if (Cand->Function || Cand->IsSurrogate)
8819         Cands.push_back(Cand);
8820       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
8821       // want to list every possible builtin candidate.
8822     }
8823   }
8824 
8825   std::sort(Cands.begin(), Cands.end(),
8826             CompareOverloadCandidatesForDisplay(S));
8827 
8828   bool ReportedAmbiguousConversions = false;
8829 
8830   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
8831   const DiagnosticsEngine::OverloadsShown ShowOverloads =
8832       S.Diags.getShowOverloads();
8833   unsigned CandsShown = 0;
8834   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8835     OverloadCandidate *Cand = *I;
8836 
8837     // Set an arbitrary limit on the number of candidate functions we'll spam
8838     // the user with.  FIXME: This limit should depend on details of the
8839     // candidate list.
8840     if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
8841       break;
8842     }
8843     ++CandsShown;
8844 
8845     if (Cand->Function)
8846       NoteFunctionCandidate(S, Cand, Args.size());
8847     else if (Cand->IsSurrogate)
8848       NoteSurrogateCandidate(S, Cand);
8849     else {
8850       assert(Cand->Viable &&
8851              "Non-viable built-in candidates are not added to Cands.");
8852       // Generally we only see ambiguities including viable builtin
8853       // operators if overload resolution got screwed up by an
8854       // ambiguous user-defined conversion.
8855       //
8856       // FIXME: It's quite possible for different conversions to see
8857       // different ambiguities, though.
8858       if (!ReportedAmbiguousConversions) {
8859         NoteAmbiguousUserConversions(S, OpLoc, Cand);
8860         ReportedAmbiguousConversions = true;
8861       }
8862 
8863       // If this is a viable builtin, print it.
8864       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
8865     }
8866   }
8867 
8868   if (I != E)
8869     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
8870 }
8871 
8872 // [PossiblyAFunctionType]  -->   [Return]
8873 // NonFunctionType --> NonFunctionType
8874 // R (A) --> R(A)
8875 // R (*)(A) --> R (A)
8876 // R (&)(A) --> R (A)
8877 // R (S::*)(A) --> R (A)
8878 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8879   QualType Ret = PossiblyAFunctionType;
8880   if (const PointerType *ToTypePtr =
8881     PossiblyAFunctionType->getAs<PointerType>())
8882     Ret = ToTypePtr->getPointeeType();
8883   else if (const ReferenceType *ToTypeRef =
8884     PossiblyAFunctionType->getAs<ReferenceType>())
8885     Ret = ToTypeRef->getPointeeType();
8886   else if (const MemberPointerType *MemTypePtr =
8887     PossiblyAFunctionType->getAs<MemberPointerType>())
8888     Ret = MemTypePtr->getPointeeType();
8889   Ret =
8890     Context.getCanonicalType(Ret).getUnqualifiedType();
8891   return Ret;
8892 }
8893 
8894 // A helper class to help with address of function resolution
8895 // - allows us to avoid passing around all those ugly parameters
8896 class AddressOfFunctionResolver
8897 {
8898   Sema& S;
8899   Expr* SourceExpr;
8900   const QualType& TargetType;
8901   QualType TargetFunctionType; // Extracted function type from target type
8902 
8903   bool Complain;
8904   //DeclAccessPair& ResultFunctionAccessPair;
8905   ASTContext& Context;
8906 
8907   bool TargetTypeIsNonStaticMemberFunction;
8908   bool FoundNonTemplateFunction;
8909 
8910   OverloadExpr::FindResult OvlExprInfo;
8911   OverloadExpr *OvlExpr;
8912   TemplateArgumentListInfo OvlExplicitTemplateArgs;
8913   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
8914 
8915 public:
8916   AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8917                             const QualType& TargetType, bool Complain)
8918     : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8919       Complain(Complain), Context(S.getASTContext()),
8920       TargetTypeIsNonStaticMemberFunction(
8921                                     !!TargetType->getAs<MemberPointerType>()),
8922       FoundNonTemplateFunction(false),
8923       OvlExprInfo(OverloadExpr::find(SourceExpr)),
8924       OvlExpr(OvlExprInfo.Expression)
8925   {
8926     ExtractUnqualifiedFunctionTypeFromTargetType();
8927 
8928     if (!TargetFunctionType->isFunctionType()) {
8929       if (OvlExpr->hasExplicitTemplateArgs()) {
8930         DeclAccessPair dap;
8931         if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
8932                                             OvlExpr, false, &dap) ) {
8933 
8934           if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8935             if (!Method->isStatic()) {
8936               // If the target type is a non-function type and the function
8937               // found is a non-static member function, pretend as if that was
8938               // the target, it's the only possible type to end up with.
8939               TargetTypeIsNonStaticMemberFunction = true;
8940 
8941               // And skip adding the function if its not in the proper form.
8942               // We'll diagnose this due to an empty set of functions.
8943               if (!OvlExprInfo.HasFormOfMemberPointer)
8944                 return;
8945             }
8946           }
8947 
8948           Matches.push_back(std::make_pair(dap,Fn));
8949         }
8950       }
8951       return;
8952     }
8953 
8954     if (OvlExpr->hasExplicitTemplateArgs())
8955       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
8956 
8957     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8958       // C++ [over.over]p4:
8959       //   If more than one function is selected, [...]
8960       if (Matches.size() > 1) {
8961         if (FoundNonTemplateFunction)
8962           EliminateAllTemplateMatches();
8963         else
8964           EliminateAllExceptMostSpecializedTemplate();
8965       }
8966     }
8967   }
8968 
8969 private:
8970   bool isTargetTypeAFunction() const {
8971     return TargetFunctionType->isFunctionType();
8972   }
8973 
8974   // [ToType]     [Return]
8975 
8976   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8977   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8978   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8979   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8980     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8981   }
8982 
8983   // return true if any matching specializations were found
8984   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8985                                    const DeclAccessPair& CurAccessFunPair) {
8986     if (CXXMethodDecl *Method
8987               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8988       // Skip non-static function templates when converting to pointer, and
8989       // static when converting to member pointer.
8990       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8991         return false;
8992     }
8993     else if (TargetTypeIsNonStaticMemberFunction)
8994       return false;
8995 
8996     // C++ [over.over]p2:
8997     //   If the name is a function template, template argument deduction is
8998     //   done (14.8.2.2), and if the argument deduction succeeds, the
8999     //   resulting template argument list is used to generate a single
9000     //   function template specialization, which is added to the set of
9001     //   overloaded functions considered.
9002     FunctionDecl *Specialization = 0;
9003     TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
9004     if (Sema::TemplateDeductionResult Result
9005           = S.DeduceTemplateArguments(FunctionTemplate,
9006                                       &OvlExplicitTemplateArgs,
9007                                       TargetFunctionType, Specialization,
9008                                       Info)) {
9009       // FIXME: make a note of the failed deduction for diagnostics.
9010       (void)Result;
9011       return false;
9012     }
9013 
9014     // Template argument deduction ensures that we have an exact match.
9015     // This function template specicalization works.
9016     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9017     assert(TargetFunctionType
9018                       == Context.getCanonicalType(Specialization->getType()));
9019     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9020     return true;
9021   }
9022 
9023   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9024                                       const DeclAccessPair& CurAccessFunPair) {
9025     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9026       // Skip non-static functions when converting to pointer, and static
9027       // when converting to member pointer.
9028       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9029         return false;
9030     }
9031     else if (TargetTypeIsNonStaticMemberFunction)
9032       return false;
9033 
9034     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9035       if (S.getLangOpts().CUDA)
9036         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9037           if (S.CheckCUDATarget(Caller, FunDecl))
9038             return false;
9039 
9040       QualType ResultTy;
9041       if (Context.hasSameUnqualifiedType(TargetFunctionType,
9042                                          FunDecl->getType()) ||
9043           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9044                                  ResultTy)) {
9045         Matches.push_back(std::make_pair(CurAccessFunPair,
9046           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9047         FoundNonTemplateFunction = true;
9048         return true;
9049       }
9050     }
9051 
9052     return false;
9053   }
9054 
9055   bool FindAllFunctionsThatMatchTargetTypeExactly() {
9056     bool Ret = false;
9057 
9058     // If the overload expression doesn't have the form of a pointer to
9059     // member, don't try to convert it to a pointer-to-member type.
9060     if (IsInvalidFormOfPointerToMemberFunction())
9061       return false;
9062 
9063     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9064                                E = OvlExpr->decls_end();
9065          I != E; ++I) {
9066       // Look through any using declarations to find the underlying function.
9067       NamedDecl *Fn = (*I)->getUnderlyingDecl();
9068 
9069       // C++ [over.over]p3:
9070       //   Non-member functions and static member functions match
9071       //   targets of type "pointer-to-function" or "reference-to-function."
9072       //   Nonstatic member functions match targets of
9073       //   type "pointer-to-member-function."
9074       // Note that according to DR 247, the containing class does not matter.
9075       if (FunctionTemplateDecl *FunctionTemplate
9076                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
9077         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9078           Ret = true;
9079       }
9080       // If we have explicit template arguments supplied, skip non-templates.
9081       else if (!OvlExpr->hasExplicitTemplateArgs() &&
9082                AddMatchingNonTemplateFunction(Fn, I.getPair()))
9083         Ret = true;
9084     }
9085     assert(Ret || Matches.empty());
9086     return Ret;
9087   }
9088 
9089   void EliminateAllExceptMostSpecializedTemplate() {
9090     //   [...] and any given function template specialization F1 is
9091     //   eliminated if the set contains a second function template
9092     //   specialization whose function template is more specialized
9093     //   than the function template of F1 according to the partial
9094     //   ordering rules of 14.5.5.2.
9095 
9096     // The algorithm specified above is quadratic. We instead use a
9097     // two-pass algorithm (similar to the one used to identify the
9098     // best viable function in an overload set) that identifies the
9099     // best function template (if it exists).
9100 
9101     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9102     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9103       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9104 
9105     UnresolvedSetIterator Result =
9106       S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9107                            TPOC_Other, 0, SourceExpr->getLocStart(),
9108                            S.PDiag(),
9109                            S.PDiag(diag::err_addr_ovl_ambiguous)
9110                              << Matches[0].second->getDeclName(),
9111                            S.PDiag(diag::note_ovl_candidate)
9112                              << (unsigned) oc_function_template,
9113                            Complain, TargetFunctionType);
9114 
9115     if (Result != MatchesCopy.end()) {
9116       // Make it the first and only element
9117       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9118       Matches[0].second = cast<FunctionDecl>(*Result);
9119       Matches.resize(1);
9120     }
9121   }
9122 
9123   void EliminateAllTemplateMatches() {
9124     //   [...] any function template specializations in the set are
9125     //   eliminated if the set also contains a non-template function, [...]
9126     for (unsigned I = 0, N = Matches.size(); I != N; ) {
9127       if (Matches[I].second->getPrimaryTemplate() == 0)
9128         ++I;
9129       else {
9130         Matches[I] = Matches[--N];
9131         Matches.set_size(N);
9132       }
9133     }
9134   }
9135 
9136 public:
9137   void ComplainNoMatchesFound() const {
9138     assert(Matches.empty());
9139     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9140         << OvlExpr->getName() << TargetFunctionType
9141         << OvlExpr->getSourceRange();
9142     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9143   }
9144 
9145   bool IsInvalidFormOfPointerToMemberFunction() const {
9146     return TargetTypeIsNonStaticMemberFunction &&
9147       !OvlExprInfo.HasFormOfMemberPointer;
9148   }
9149 
9150   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9151       // TODO: Should we condition this on whether any functions might
9152       // have matched, or is it more appropriate to do that in callers?
9153       // TODO: a fixit wouldn't hurt.
9154       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9155         << TargetType << OvlExpr->getSourceRange();
9156   }
9157 
9158   void ComplainOfInvalidConversion() const {
9159     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9160       << OvlExpr->getName() << TargetType;
9161   }
9162 
9163   void ComplainMultipleMatchesFound() const {
9164     assert(Matches.size() > 1);
9165     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9166       << OvlExpr->getName()
9167       << OvlExpr->getSourceRange();
9168     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9169   }
9170 
9171   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9172 
9173   int getNumMatches() const { return Matches.size(); }
9174 
9175   FunctionDecl* getMatchingFunctionDecl() const {
9176     if (Matches.size() != 1) return 0;
9177     return Matches[0].second;
9178   }
9179 
9180   const DeclAccessPair* getMatchingFunctionAccessPair() const {
9181     if (Matches.size() != 1) return 0;
9182     return &Matches[0].first;
9183   }
9184 };
9185 
9186 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9187 /// an overloaded function (C++ [over.over]), where @p From is an
9188 /// expression with overloaded function type and @p ToType is the type
9189 /// we're trying to resolve to. For example:
9190 ///
9191 /// @code
9192 /// int f(double);
9193 /// int f(int);
9194 ///
9195 /// int (*pfd)(double) = f; // selects f(double)
9196 /// @endcode
9197 ///
9198 /// This routine returns the resulting FunctionDecl if it could be
9199 /// resolved, and NULL otherwise. When @p Complain is true, this
9200 /// routine will emit diagnostics if there is an error.
9201 FunctionDecl *
9202 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9203                                          QualType TargetType,
9204                                          bool Complain,
9205                                          DeclAccessPair &FoundResult,
9206                                          bool *pHadMultipleCandidates) {
9207   assert(AddressOfExpr->getType() == Context.OverloadTy);
9208 
9209   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9210                                      Complain);
9211   int NumMatches = Resolver.getNumMatches();
9212   FunctionDecl* Fn = 0;
9213   if (NumMatches == 0 && Complain) {
9214     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9215       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9216     else
9217       Resolver.ComplainNoMatchesFound();
9218   }
9219   else if (NumMatches > 1 && Complain)
9220     Resolver.ComplainMultipleMatchesFound();
9221   else if (NumMatches == 1) {
9222     Fn = Resolver.getMatchingFunctionDecl();
9223     assert(Fn);
9224     FoundResult = *Resolver.getMatchingFunctionAccessPair();
9225     MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
9226     if (Complain)
9227       CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9228   }
9229 
9230   if (pHadMultipleCandidates)
9231     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9232   return Fn;
9233 }
9234 
9235 /// \brief Given an expression that refers to an overloaded function, try to
9236 /// resolve that overloaded function expression down to a single function.
9237 ///
9238 /// This routine can only resolve template-ids that refer to a single function
9239 /// template, where that template-id refers to a single template whose template
9240 /// arguments are either provided by the template-id or have defaults,
9241 /// as described in C++0x [temp.arg.explicit]p3.
9242 FunctionDecl *
9243 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9244                                                   bool Complain,
9245                                                   DeclAccessPair *FoundResult) {
9246   // C++ [over.over]p1:
9247   //   [...] [Note: any redundant set of parentheses surrounding the
9248   //   overloaded function name is ignored (5.1). ]
9249   // C++ [over.over]p1:
9250   //   [...] The overloaded function name can be preceded by the &
9251   //   operator.
9252 
9253   // If we didn't actually find any template-ids, we're done.
9254   if (!ovl->hasExplicitTemplateArgs())
9255     return 0;
9256 
9257   TemplateArgumentListInfo ExplicitTemplateArgs;
9258   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9259 
9260   // Look through all of the overloaded functions, searching for one
9261   // whose type matches exactly.
9262   FunctionDecl *Matched = 0;
9263   for (UnresolvedSetIterator I = ovl->decls_begin(),
9264          E = ovl->decls_end(); I != E; ++I) {
9265     // C++0x [temp.arg.explicit]p3:
9266     //   [...] In contexts where deduction is done and fails, or in contexts
9267     //   where deduction is not done, if a template argument list is
9268     //   specified and it, along with any default template arguments,
9269     //   identifies a single function template specialization, then the
9270     //   template-id is an lvalue for the function template specialization.
9271     FunctionTemplateDecl *FunctionTemplate
9272       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9273 
9274     // C++ [over.over]p2:
9275     //   If the name is a function template, template argument deduction is
9276     //   done (14.8.2.2), and if the argument deduction succeeds, the
9277     //   resulting template argument list is used to generate a single
9278     //   function template specialization, which is added to the set of
9279     //   overloaded functions considered.
9280     FunctionDecl *Specialization = 0;
9281     TemplateDeductionInfo Info(Context, ovl->getNameLoc());
9282     if (TemplateDeductionResult Result
9283           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9284                                     Specialization, Info)) {
9285       // FIXME: make a note of the failed deduction for diagnostics.
9286       (void)Result;
9287       continue;
9288     }
9289 
9290     assert(Specialization && "no specialization and no error?");
9291 
9292     // Multiple matches; we can't resolve to a single declaration.
9293     if (Matched) {
9294       if (Complain) {
9295         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9296           << ovl->getName();
9297         NoteAllOverloadCandidates(ovl);
9298       }
9299       return 0;
9300     }
9301 
9302     Matched = Specialization;
9303     if (FoundResult) *FoundResult = I.getPair();
9304   }
9305 
9306   return Matched;
9307 }
9308 
9309 
9310 
9311 
9312 // Resolve and fix an overloaded expression that can be resolved
9313 // because it identifies a single function template specialization.
9314 //
9315 // Last three arguments should only be supplied if Complain = true
9316 //
9317 // Return true if it was logically possible to so resolve the
9318 // expression, regardless of whether or not it succeeded.  Always
9319 // returns true if 'complain' is set.
9320 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9321                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
9322                    bool complain, const SourceRange& OpRangeForComplaining,
9323                                            QualType DestTypeForComplaining,
9324                                             unsigned DiagIDForComplaining) {
9325   assert(SrcExpr.get()->getType() == Context.OverloadTy);
9326 
9327   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9328 
9329   DeclAccessPair found;
9330   ExprResult SingleFunctionExpression;
9331   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9332                            ovl.Expression, /*complain*/ false, &found)) {
9333     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9334       SrcExpr = ExprError();
9335       return true;
9336     }
9337 
9338     // It is only correct to resolve to an instance method if we're
9339     // resolving a form that's permitted to be a pointer to member.
9340     // Otherwise we'll end up making a bound member expression, which
9341     // is illegal in all the contexts we resolve like this.
9342     if (!ovl.HasFormOfMemberPointer &&
9343         isa<CXXMethodDecl>(fn) &&
9344         cast<CXXMethodDecl>(fn)->isInstance()) {
9345       if (!complain) return false;
9346 
9347       Diag(ovl.Expression->getExprLoc(),
9348            diag::err_bound_member_function)
9349         << 0 << ovl.Expression->getSourceRange();
9350 
9351       // TODO: I believe we only end up here if there's a mix of
9352       // static and non-static candidates (otherwise the expression
9353       // would have 'bound member' type, not 'overload' type).
9354       // Ideally we would note which candidate was chosen and why
9355       // the static candidates were rejected.
9356       SrcExpr = ExprError();
9357       return true;
9358     }
9359 
9360     // Fix the expression to refer to 'fn'.
9361     SingleFunctionExpression =
9362       Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9363 
9364     // If desired, do function-to-pointer decay.
9365     if (doFunctionPointerConverion) {
9366       SingleFunctionExpression =
9367         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9368       if (SingleFunctionExpression.isInvalid()) {
9369         SrcExpr = ExprError();
9370         return true;
9371       }
9372     }
9373   }
9374 
9375   if (!SingleFunctionExpression.isUsable()) {
9376     if (complain) {
9377       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9378         << ovl.Expression->getName()
9379         << DestTypeForComplaining
9380         << OpRangeForComplaining
9381         << ovl.Expression->getQualifierLoc().getSourceRange();
9382       NoteAllOverloadCandidates(SrcExpr.get());
9383 
9384       SrcExpr = ExprError();
9385       return true;
9386     }
9387 
9388     return false;
9389   }
9390 
9391   SrcExpr = SingleFunctionExpression;
9392   return true;
9393 }
9394 
9395 /// \brief Add a single candidate to the overload set.
9396 static void AddOverloadedCallCandidate(Sema &S,
9397                                        DeclAccessPair FoundDecl,
9398                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9399                                        llvm::ArrayRef<Expr *> Args,
9400                                        OverloadCandidateSet &CandidateSet,
9401                                        bool PartialOverloading,
9402                                        bool KnownValid) {
9403   NamedDecl *Callee = FoundDecl.getDecl();
9404   if (isa<UsingShadowDecl>(Callee))
9405     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9406 
9407   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9408     if (ExplicitTemplateArgs) {
9409       assert(!KnownValid && "Explicit template arguments?");
9410       return;
9411     }
9412     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9413                            PartialOverloading);
9414     return;
9415   }
9416 
9417   if (FunctionTemplateDecl *FuncTemplate
9418       = dyn_cast<FunctionTemplateDecl>(Callee)) {
9419     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9420                                    ExplicitTemplateArgs, Args, CandidateSet);
9421     return;
9422   }
9423 
9424   assert(!KnownValid && "unhandled case in overloaded call candidate");
9425 }
9426 
9427 /// \brief Add the overload candidates named by callee and/or found by argument
9428 /// dependent lookup to the given overload set.
9429 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9430                                        llvm::ArrayRef<Expr *> Args,
9431                                        OverloadCandidateSet &CandidateSet,
9432                                        bool PartialOverloading) {
9433 
9434 #ifndef NDEBUG
9435   // Verify that ArgumentDependentLookup is consistent with the rules
9436   // in C++0x [basic.lookup.argdep]p3:
9437   //
9438   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9439   //   and let Y be the lookup set produced by argument dependent
9440   //   lookup (defined as follows). If X contains
9441   //
9442   //     -- a declaration of a class member, or
9443   //
9444   //     -- a block-scope function declaration that is not a
9445   //        using-declaration, or
9446   //
9447   //     -- a declaration that is neither a function or a function
9448   //        template
9449   //
9450   //   then Y is empty.
9451 
9452   if (ULE->requiresADL()) {
9453     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9454            E = ULE->decls_end(); I != E; ++I) {
9455       assert(!(*I)->getDeclContext()->isRecord());
9456       assert(isa<UsingShadowDecl>(*I) ||
9457              !(*I)->getDeclContext()->isFunctionOrMethod());
9458       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9459     }
9460   }
9461 #endif
9462 
9463   // It would be nice to avoid this copy.
9464   TemplateArgumentListInfo TABuffer;
9465   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9466   if (ULE->hasExplicitTemplateArgs()) {
9467     ULE->copyTemplateArgumentsInto(TABuffer);
9468     ExplicitTemplateArgs = &TABuffer;
9469   }
9470 
9471   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9472          E = ULE->decls_end(); I != E; ++I)
9473     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9474                                CandidateSet, PartialOverloading,
9475                                /*KnownValid*/ true);
9476 
9477   if (ULE->requiresADL())
9478     AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9479                                          ULE->getExprLoc(),
9480                                          Args, ExplicitTemplateArgs,
9481                                          CandidateSet, PartialOverloading,
9482                                          ULE->isStdAssociatedNamespace());
9483 }
9484 
9485 /// Attempt to recover from an ill-formed use of a non-dependent name in a
9486 /// template, where the non-dependent name was declared after the template
9487 /// was defined. This is common in code written for a compilers which do not
9488 /// correctly implement two-stage name lookup.
9489 ///
9490 /// Returns true if a viable candidate was found and a diagnostic was issued.
9491 static bool
9492 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9493                        const CXXScopeSpec &SS, LookupResult &R,
9494                        TemplateArgumentListInfo *ExplicitTemplateArgs,
9495                        llvm::ArrayRef<Expr *> Args) {
9496   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9497     return false;
9498 
9499   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9500     if (DC->isTransparentContext())
9501       continue;
9502 
9503     SemaRef.LookupQualifiedName(R, DC);
9504 
9505     if (!R.empty()) {
9506       R.suppressDiagnostics();
9507 
9508       if (isa<CXXRecordDecl>(DC)) {
9509         // Don't diagnose names we find in classes; we get much better
9510         // diagnostics for these from DiagnoseEmptyLookup.
9511         R.clear();
9512         return false;
9513       }
9514 
9515       OverloadCandidateSet Candidates(FnLoc);
9516       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9517         AddOverloadedCallCandidate(SemaRef, I.getPair(),
9518                                    ExplicitTemplateArgs, Args,
9519                                    Candidates, false, /*KnownValid*/ false);
9520 
9521       OverloadCandidateSet::iterator Best;
9522       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9523         // No viable functions. Don't bother the user with notes for functions
9524         // which don't work and shouldn't be found anyway.
9525         R.clear();
9526         return false;
9527       }
9528 
9529       // Find the namespaces where ADL would have looked, and suggest
9530       // declaring the function there instead.
9531       Sema::AssociatedNamespaceSet AssociatedNamespaces;
9532       Sema::AssociatedClassSet AssociatedClasses;
9533       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
9534                                                  AssociatedNamespaces,
9535                                                  AssociatedClasses);
9536       // Never suggest declaring a function within namespace 'std'.
9537       Sema::AssociatedNamespaceSet SuggestedNamespaces;
9538       if (DeclContext *Std = SemaRef.getStdNamespace()) {
9539         for (Sema::AssociatedNamespaceSet::iterator
9540                it = AssociatedNamespaces.begin(),
9541                end = AssociatedNamespaces.end(); it != end; ++it) {
9542           if (!Std->Encloses(*it))
9543             SuggestedNamespaces.insert(*it);
9544         }
9545       } else {
9546         // Lacking the 'std::' namespace, use all of the associated namespaces.
9547         SuggestedNamespaces = AssociatedNamespaces;
9548       }
9549 
9550       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9551         << R.getLookupName();
9552       if (SuggestedNamespaces.empty()) {
9553         SemaRef.Diag(Best->Function->getLocation(),
9554                      diag::note_not_found_by_two_phase_lookup)
9555           << R.getLookupName() << 0;
9556       } else if (SuggestedNamespaces.size() == 1) {
9557         SemaRef.Diag(Best->Function->getLocation(),
9558                      diag::note_not_found_by_two_phase_lookup)
9559           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9560       } else {
9561         // FIXME: It would be useful to list the associated namespaces here,
9562         // but the diagnostics infrastructure doesn't provide a way to produce
9563         // a localized representation of a list of items.
9564         SemaRef.Diag(Best->Function->getLocation(),
9565                      diag::note_not_found_by_two_phase_lookup)
9566           << R.getLookupName() << 2;
9567       }
9568 
9569       // Try to recover by calling this function.
9570       return true;
9571     }
9572 
9573     R.clear();
9574   }
9575 
9576   return false;
9577 }
9578 
9579 /// Attempt to recover from ill-formed use of a non-dependent operator in a
9580 /// template, where the non-dependent operator was declared after the template
9581 /// was defined.
9582 ///
9583 /// Returns true if a viable candidate was found and a diagnostic was issued.
9584 static bool
9585 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9586                                SourceLocation OpLoc,
9587                                llvm::ArrayRef<Expr *> Args) {
9588   DeclarationName OpName =
9589     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9590   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9591   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9592                                 /*ExplicitTemplateArgs=*/0, Args);
9593 }
9594 
9595 namespace {
9596 // Callback to limit the allowed keywords and to only accept typo corrections
9597 // that are keywords or whose decls refer to functions (or template functions)
9598 // that accept the given number of arguments.
9599 class RecoveryCallCCC : public CorrectionCandidateCallback {
9600  public:
9601   RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9602       : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9603     WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
9604     WantRemainingKeywords = false;
9605   }
9606 
9607   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9608     if (!candidate.getCorrectionDecl())
9609       return candidate.isKeyword();
9610 
9611     for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9612            DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9613       FunctionDecl *FD = 0;
9614       NamedDecl *ND = (*DI)->getUnderlyingDecl();
9615       if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9616         FD = FTD->getTemplatedDecl();
9617       if (!HasExplicitTemplateArgs && !FD) {
9618         if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9619           // If the Decl is neither a function nor a template function,
9620           // determine if it is a pointer or reference to a function. If so,
9621           // check against the number of arguments expected for the pointee.
9622           QualType ValType = cast<ValueDecl>(ND)->getType();
9623           if (ValType->isAnyPointerType() || ValType->isReferenceType())
9624             ValType = ValType->getPointeeType();
9625           if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9626             if (FPT->getNumArgs() == NumArgs)
9627               return true;
9628         }
9629       }
9630       if (FD && FD->getNumParams() >= NumArgs &&
9631           FD->getMinRequiredArguments() <= NumArgs)
9632         return true;
9633     }
9634     return false;
9635   }
9636 
9637  private:
9638   unsigned NumArgs;
9639   bool HasExplicitTemplateArgs;
9640 };
9641 
9642 // Callback that effectively disabled typo correction
9643 class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9644  public:
9645   NoTypoCorrectionCCC() {
9646     WantTypeSpecifiers = false;
9647     WantExpressionKeywords = false;
9648     WantCXXNamedCasts = false;
9649     WantRemainingKeywords = false;
9650   }
9651 
9652   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9653     return false;
9654   }
9655 };
9656 }
9657 
9658 /// Attempts to recover from a call where no functions were found.
9659 ///
9660 /// Returns true if new candidates were found.
9661 static ExprResult
9662 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9663                       UnresolvedLookupExpr *ULE,
9664                       SourceLocation LParenLoc,
9665                       llvm::MutableArrayRef<Expr *> Args,
9666                       SourceLocation RParenLoc,
9667                       bool EmptyLookup, bool AllowTypoCorrection) {
9668 
9669   CXXScopeSpec SS;
9670   SS.Adopt(ULE->getQualifierLoc());
9671   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9672 
9673   TemplateArgumentListInfo TABuffer;
9674   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9675   if (ULE->hasExplicitTemplateArgs()) {
9676     ULE->copyTemplateArgumentsInto(TABuffer);
9677     ExplicitTemplateArgs = &TABuffer;
9678   }
9679 
9680   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9681                  Sema::LookupOrdinaryName);
9682   RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
9683   NoTypoCorrectionCCC RejectAll;
9684   CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9685       (CorrectionCandidateCallback*)&Validator :
9686       (CorrectionCandidateCallback*)&RejectAll;
9687   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9688                               ExplicitTemplateArgs, Args) &&
9689       (!EmptyLookup ||
9690        SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
9691                                    ExplicitTemplateArgs, Args)))
9692     return ExprError();
9693 
9694   assert(!R.empty() && "lookup results empty despite recovery");
9695 
9696   // Build an implicit member call if appropriate.  Just drop the
9697   // casts and such from the call, we don't really care.
9698   ExprResult NewFn = ExprError();
9699   if ((*R.begin())->isCXXClassMember())
9700     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9701                                                     R, ExplicitTemplateArgs);
9702   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
9703     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9704                                         ExplicitTemplateArgs);
9705   else
9706     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9707 
9708   if (NewFn.isInvalid())
9709     return ExprError();
9710 
9711   // This shouldn't cause an infinite loop because we're giving it
9712   // an expression with viable lookup results, which should never
9713   // end up here.
9714   return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
9715                                MultiExprArg(Args.data(), Args.size()),
9716                                RParenLoc);
9717 }
9718 
9719 /// \brief Constructs and populates an OverloadedCandidateSet from
9720 /// the given function.
9721 /// \returns true when an the ExprResult output parameter has been set.
9722 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9723                                   UnresolvedLookupExpr *ULE,
9724                                   Expr **Args, unsigned NumArgs,
9725                                   SourceLocation RParenLoc,
9726                                   OverloadCandidateSet *CandidateSet,
9727                                   ExprResult *Result) {
9728 #ifndef NDEBUG
9729   if (ULE->requiresADL()) {
9730     // To do ADL, we must have found an unqualified name.
9731     assert(!ULE->getQualifier() && "qualified name with ADL");
9732 
9733     // We don't perform ADL for implicit declarations of builtins.
9734     // Verify that this was correctly set up.
9735     FunctionDecl *F;
9736     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9737         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9738         F->getBuiltinID() && F->isImplicit())
9739       llvm_unreachable("performing ADL for builtin");
9740 
9741     // We don't perform ADL in C.
9742     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
9743   } else
9744     assert(!ULE->isStdAssociatedNamespace() &&
9745            "std is associated namespace but not doing ADL");
9746 #endif
9747 
9748   UnbridgedCastsSet UnbridgedCasts;
9749   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9750     *Result = ExprError();
9751     return true;
9752   }
9753 
9754   // Add the functions denoted by the callee to the set of candidate
9755   // functions, including those from argument-dependent lookup.
9756   AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9757                               *CandidateSet);
9758 
9759   // If we found nothing, try to recover.
9760   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9761   // out if it fails.
9762   if (CandidateSet->empty()) {
9763     // In Microsoft mode, if we are inside a template class member function then
9764     // create a type dependent CallExpr. The goal is to postpone name lookup
9765     // to instantiation time to be able to search into type dependent base
9766     // classes.
9767     if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
9768         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
9769       CallExpr *CE = new (Context) CallExpr(Context, Fn,
9770                                             llvm::makeArrayRef(Args, NumArgs),
9771                                             Context.DependentTy, VK_RValue,
9772                                             RParenLoc);
9773       CE->setTypeDependent(true);
9774       *Result = Owned(CE);
9775       return true;
9776     }
9777     return false;
9778   }
9779 
9780   UnbridgedCasts.restore();
9781   return false;
9782 }
9783 
9784 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9785 /// the completed call expression. If overload resolution fails, emits
9786 /// diagnostics and returns ExprError()
9787 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9788                                            UnresolvedLookupExpr *ULE,
9789                                            SourceLocation LParenLoc,
9790                                            Expr **Args, unsigned NumArgs,
9791                                            SourceLocation RParenLoc,
9792                                            Expr *ExecConfig,
9793                                            OverloadCandidateSet *CandidateSet,
9794                                            OverloadCandidateSet::iterator *Best,
9795                                            OverloadingResult OverloadResult,
9796                                            bool AllowTypoCorrection) {
9797   if (CandidateSet->empty())
9798     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9799                                  llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9800                                  RParenLoc, /*EmptyLookup=*/true,
9801                                  AllowTypoCorrection);
9802 
9803   switch (OverloadResult) {
9804   case OR_Success: {
9805     FunctionDecl *FDecl = (*Best)->Function;
9806     SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9807     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9808     SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9809     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9810     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9811                                          RParenLoc, ExecConfig);
9812   }
9813 
9814   case OR_No_Viable_Function: {
9815     // Try to recover by looking for viable functions which the user might
9816     // have meant to call.
9817     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9818                                   llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9819                                                 RParenLoc,
9820                                                 /*EmptyLookup=*/false,
9821                                                 AllowTypoCorrection);
9822     if (!Recovery.isInvalid())
9823       return Recovery;
9824 
9825     SemaRef.Diag(Fn->getLocStart(),
9826          diag::err_ovl_no_viable_function_in_call)
9827       << ULE->getName() << Fn->getSourceRange();
9828     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9829                                  llvm::makeArrayRef(Args, NumArgs));
9830     break;
9831   }
9832 
9833   case OR_Ambiguous:
9834     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
9835       << ULE->getName() << Fn->getSourceRange();
9836     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9837                                  llvm::makeArrayRef(Args, NumArgs));
9838     break;
9839 
9840   case OR_Deleted: {
9841     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9842       << (*Best)->Function->isDeleted()
9843       << ULE->getName()
9844       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9845       << Fn->getSourceRange();
9846     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9847                                  llvm::makeArrayRef(Args, NumArgs));
9848 
9849     // We emitted an error for the unvailable/deleted function call but keep
9850     // the call in the AST.
9851     FunctionDecl *FDecl = (*Best)->Function;
9852     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9853     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9854                                  RParenLoc, ExecConfig);
9855   }
9856   }
9857 
9858   // Overload resolution failed.
9859   return ExprError();
9860 }
9861 
9862 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
9863 /// (which eventually refers to the declaration Func) and the call
9864 /// arguments Args/NumArgs, attempt to resolve the function call down
9865 /// to a specific function. If overload resolution succeeds, returns
9866 /// the call expression produced by overload resolution.
9867 /// Otherwise, emits diagnostics and returns ExprError.
9868 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9869                                          UnresolvedLookupExpr *ULE,
9870                                          SourceLocation LParenLoc,
9871                                          Expr **Args, unsigned NumArgs,
9872                                          SourceLocation RParenLoc,
9873                                          Expr *ExecConfig,
9874                                          bool AllowTypoCorrection) {
9875   OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9876   ExprResult result;
9877 
9878   if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9879                              &CandidateSet, &result))
9880     return result;
9881 
9882   OverloadCandidateSet::iterator Best;
9883   OverloadingResult OverloadResult =
9884       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9885 
9886   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9887                                   RParenLoc, ExecConfig, &CandidateSet,
9888                                   &Best, OverloadResult,
9889                                   AllowTypoCorrection);
9890 }
9891 
9892 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
9893   return Functions.size() > 1 ||
9894     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9895 }
9896 
9897 /// \brief Create a unary operation that may resolve to an overloaded
9898 /// operator.
9899 ///
9900 /// \param OpLoc The location of the operator itself (e.g., '*').
9901 ///
9902 /// \param OpcIn The UnaryOperator::Opcode that describes this
9903 /// operator.
9904 ///
9905 /// \param Fns The set of non-member functions that will be
9906 /// considered by overload resolution. The caller needs to build this
9907 /// set based on the context using, e.g.,
9908 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9909 /// set should not contain any member functions; those will be added
9910 /// by CreateOverloadedUnaryOp().
9911 ///
9912 /// \param Input The input argument.
9913 ExprResult
9914 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9915                               const UnresolvedSetImpl &Fns,
9916                               Expr *Input) {
9917   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
9918 
9919   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9920   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9921   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9922   // TODO: provide better source location info.
9923   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
9924 
9925   if (checkPlaceholderForOverload(*this, Input))
9926     return ExprError();
9927 
9928   Expr *Args[2] = { Input, 0 };
9929   unsigned NumArgs = 1;
9930 
9931   // For post-increment and post-decrement, add the implicit '0' as
9932   // the second argument, so that we know this is a post-increment or
9933   // post-decrement.
9934   if (Opc == UO_PostInc || Opc == UO_PostDec) {
9935     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
9936     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9937                                      SourceLocation());
9938     NumArgs = 2;
9939   }
9940 
9941   if (Input->isTypeDependent()) {
9942     if (Fns.empty())
9943       return Owned(new (Context) UnaryOperator(Input,
9944                                                Opc,
9945                                                Context.DependentTy,
9946                                                VK_RValue, OK_Ordinary,
9947                                                OpLoc));
9948 
9949     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
9950     UnresolvedLookupExpr *Fn
9951       = UnresolvedLookupExpr::Create(Context, NamingClass,
9952                                      NestedNameSpecifierLoc(), OpNameInfo,
9953                                      /*ADL*/ true, IsOverloaded(Fns),
9954                                      Fns.begin(), Fns.end());
9955     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
9956                                               llvm::makeArrayRef(Args, NumArgs),
9957                                                    Context.DependentTy,
9958                                                    VK_RValue,
9959                                                    OpLoc));
9960   }
9961 
9962   // Build an empty overload set.
9963   OverloadCandidateSet CandidateSet(OpLoc);
9964 
9965   // Add the candidates from the given function set.
9966   AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9967                         false);
9968 
9969   // Add operator candidates that are member functions.
9970   AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9971 
9972   // Add candidates from ADL.
9973   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9974                                        OpLoc, llvm::makeArrayRef(Args, NumArgs),
9975                                        /*ExplicitTemplateArgs*/ 0,
9976                                        CandidateSet);
9977 
9978   // Add builtin operator candidates.
9979   AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9980 
9981   bool HadMultipleCandidates = (CandidateSet.size() > 1);
9982 
9983   // Perform overload resolution.
9984   OverloadCandidateSet::iterator Best;
9985   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
9986   case OR_Success: {
9987     // We found a built-in operator or an overloaded operator.
9988     FunctionDecl *FnDecl = Best->Function;
9989 
9990     if (FnDecl) {
9991       // We matched an overloaded operator. Build a call to that
9992       // operator.
9993 
9994       MarkFunctionReferenced(OpLoc, FnDecl);
9995 
9996       // Convert the arguments.
9997       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
9998         CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
9999 
10000         ExprResult InputRes =
10001           PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10002                                               Best->FoundDecl, Method);
10003         if (InputRes.isInvalid())
10004           return ExprError();
10005         Input = InputRes.take();
10006       } else {
10007         // Convert the arguments.
10008         ExprResult InputInit
10009           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10010                                                       Context,
10011                                                       FnDecl->getParamDecl(0)),
10012                                       SourceLocation(),
10013                                       Input);
10014         if (InputInit.isInvalid())
10015           return ExprError();
10016         Input = InputInit.take();
10017       }
10018 
10019       DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10020 
10021       // Determine the result type.
10022       QualType ResultTy = FnDecl->getResultType();
10023       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10024       ResultTy = ResultTy.getNonLValueExprType(Context);
10025 
10026       // Build the actual expression node.
10027       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10028                                                 HadMultipleCandidates, OpLoc);
10029       if (FnExpr.isInvalid())
10030         return ExprError();
10031 
10032       Args[0] = Input;
10033       CallExpr *TheCall =
10034         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10035                                           llvm::makeArrayRef(Args, NumArgs),
10036                                           ResultTy, VK, OpLoc);
10037 
10038       if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10039                               FnDecl))
10040         return ExprError();
10041 
10042       return MaybeBindToTemporary(TheCall);
10043     } else {
10044       // We matched a built-in operator. Convert the arguments, then
10045       // break out so that we will build the appropriate built-in
10046       // operator node.
10047       ExprResult InputRes =
10048         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10049                                   Best->Conversions[0], AA_Passing);
10050       if (InputRes.isInvalid())
10051         return ExprError();
10052       Input = InputRes.take();
10053       break;
10054     }
10055   }
10056 
10057   case OR_No_Viable_Function:
10058     // This is an erroneous use of an operator which can be overloaded by
10059     // a non-member function. Check for non-member operators which were
10060     // defined too late to be candidates.
10061     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10062                                        llvm::makeArrayRef(Args, NumArgs)))
10063       // FIXME: Recover by calling the found function.
10064       return ExprError();
10065 
10066     // No viable function; fall through to handling this as a
10067     // built-in operator, which will produce an error message for us.
10068     break;
10069 
10070   case OR_Ambiguous:
10071     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10072         << UnaryOperator::getOpcodeStr(Opc)
10073         << Input->getType()
10074         << Input->getSourceRange();
10075     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10076                                 llvm::makeArrayRef(Args, NumArgs),
10077                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10078     return ExprError();
10079 
10080   case OR_Deleted:
10081     Diag(OpLoc, diag::err_ovl_deleted_oper)
10082       << Best->Function->isDeleted()
10083       << UnaryOperator::getOpcodeStr(Opc)
10084       << getDeletedOrUnavailableSuffix(Best->Function)
10085       << Input->getSourceRange();
10086     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10087                                 llvm::makeArrayRef(Args, NumArgs),
10088                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10089     return ExprError();
10090   }
10091 
10092   // Either we found no viable overloaded operator or we matched a
10093   // built-in operator. In either case, fall through to trying to
10094   // build a built-in operation.
10095   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10096 }
10097 
10098 /// \brief Create a binary operation that may resolve to an overloaded
10099 /// operator.
10100 ///
10101 /// \param OpLoc The location of the operator itself (e.g., '+').
10102 ///
10103 /// \param OpcIn The BinaryOperator::Opcode that describes this
10104 /// operator.
10105 ///
10106 /// \param Fns The set of non-member functions that will be
10107 /// considered by overload resolution. The caller needs to build this
10108 /// set based on the context using, e.g.,
10109 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10110 /// set should not contain any member functions; those will be added
10111 /// by CreateOverloadedBinOp().
10112 ///
10113 /// \param LHS Left-hand argument.
10114 /// \param RHS Right-hand argument.
10115 ExprResult
10116 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10117                             unsigned OpcIn,
10118                             const UnresolvedSetImpl &Fns,
10119                             Expr *LHS, Expr *RHS) {
10120   Expr *Args[2] = { LHS, RHS };
10121   LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10122 
10123   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10124   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10125   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10126 
10127   // If either side is type-dependent, create an appropriate dependent
10128   // expression.
10129   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10130     if (Fns.empty()) {
10131       // If there are no functions to store, just build a dependent
10132       // BinaryOperator or CompoundAssignment.
10133       if (Opc <= BO_Assign || Opc > BO_OrAssign)
10134         return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10135                                                   Context.DependentTy,
10136                                                   VK_RValue, OK_Ordinary,
10137                                                   OpLoc));
10138 
10139       return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10140                                                         Context.DependentTy,
10141                                                         VK_LValue,
10142                                                         OK_Ordinary,
10143                                                         Context.DependentTy,
10144                                                         Context.DependentTy,
10145                                                         OpLoc));
10146     }
10147 
10148     // FIXME: save results of ADL from here?
10149     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10150     // TODO: provide better source location info in DNLoc component.
10151     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10152     UnresolvedLookupExpr *Fn
10153       = UnresolvedLookupExpr::Create(Context, NamingClass,
10154                                      NestedNameSpecifierLoc(), OpNameInfo,
10155                                      /*ADL*/ true, IsOverloaded(Fns),
10156                                      Fns.begin(), Fns.end());
10157     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
10158                                                    Args,
10159                                                    Context.DependentTy,
10160                                                    VK_RValue,
10161                                                    OpLoc));
10162   }
10163 
10164   // Always do placeholder-like conversions on the RHS.
10165   if (checkPlaceholderForOverload(*this, Args[1]))
10166     return ExprError();
10167 
10168   // Do placeholder-like conversion on the LHS; note that we should
10169   // not get here with a PseudoObject LHS.
10170   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10171   if (checkPlaceholderForOverload(*this, Args[0]))
10172     return ExprError();
10173 
10174   // If this is the assignment operator, we only perform overload resolution
10175   // if the left-hand side is a class or enumeration type. This is actually
10176   // a hack. The standard requires that we do overload resolution between the
10177   // various built-in candidates, but as DR507 points out, this can lead to
10178   // problems. So we do it this way, which pretty much follows what GCC does.
10179   // Note that we go the traditional code path for compound assignment forms.
10180   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10181     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10182 
10183   // If this is the .* operator, which is not overloadable, just
10184   // create a built-in binary operator.
10185   if (Opc == BO_PtrMemD)
10186     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10187 
10188   // Build an empty overload set.
10189   OverloadCandidateSet CandidateSet(OpLoc);
10190 
10191   // Add the candidates from the given function set.
10192   AddFunctionCandidates(Fns, Args, CandidateSet, false);
10193 
10194   // Add operator candidates that are member functions.
10195   AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10196 
10197   // Add candidates from ADL.
10198   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10199                                        OpLoc, Args,
10200                                        /*ExplicitTemplateArgs*/ 0,
10201                                        CandidateSet);
10202 
10203   // Add builtin operator candidates.
10204   AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10205 
10206   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10207 
10208   // Perform overload resolution.
10209   OverloadCandidateSet::iterator Best;
10210   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10211     case OR_Success: {
10212       // We found a built-in operator or an overloaded operator.
10213       FunctionDecl *FnDecl = Best->Function;
10214 
10215       if (FnDecl) {
10216         // We matched an overloaded operator. Build a call to that
10217         // operator.
10218 
10219         MarkFunctionReferenced(OpLoc, FnDecl);
10220 
10221         // Convert the arguments.
10222         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10223           // Best->Access is only meaningful for class members.
10224           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10225 
10226           ExprResult Arg1 =
10227             PerformCopyInitialization(
10228               InitializedEntity::InitializeParameter(Context,
10229                                                      FnDecl->getParamDecl(0)),
10230               SourceLocation(), Owned(Args[1]));
10231           if (Arg1.isInvalid())
10232             return ExprError();
10233 
10234           ExprResult Arg0 =
10235             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10236                                                 Best->FoundDecl, Method);
10237           if (Arg0.isInvalid())
10238             return ExprError();
10239           Args[0] = Arg0.takeAs<Expr>();
10240           Args[1] = RHS = Arg1.takeAs<Expr>();
10241         } else {
10242           // Convert the arguments.
10243           ExprResult Arg0 = PerformCopyInitialization(
10244             InitializedEntity::InitializeParameter(Context,
10245                                                    FnDecl->getParamDecl(0)),
10246             SourceLocation(), Owned(Args[0]));
10247           if (Arg0.isInvalid())
10248             return ExprError();
10249 
10250           ExprResult Arg1 =
10251             PerformCopyInitialization(
10252               InitializedEntity::InitializeParameter(Context,
10253                                                      FnDecl->getParamDecl(1)),
10254               SourceLocation(), Owned(Args[1]));
10255           if (Arg1.isInvalid())
10256             return ExprError();
10257           Args[0] = LHS = Arg0.takeAs<Expr>();
10258           Args[1] = RHS = Arg1.takeAs<Expr>();
10259         }
10260 
10261         DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10262 
10263         // Determine the result type.
10264         QualType ResultTy = FnDecl->getResultType();
10265         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10266         ResultTy = ResultTy.getNonLValueExprType(Context);
10267 
10268         // Build the actual expression node.
10269         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10270                                                   HadMultipleCandidates, OpLoc);
10271         if (FnExpr.isInvalid())
10272           return ExprError();
10273 
10274         CXXOperatorCallExpr *TheCall =
10275           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10276                                             Args, ResultTy, VK, OpLoc);
10277 
10278         if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10279                                 FnDecl))
10280           return ExprError();
10281 
10282         return MaybeBindToTemporary(TheCall);
10283       } else {
10284         // We matched a built-in operator. Convert the arguments, then
10285         // break out so that we will build the appropriate built-in
10286         // operator node.
10287         ExprResult ArgsRes0 =
10288           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10289                                     Best->Conversions[0], AA_Passing);
10290         if (ArgsRes0.isInvalid())
10291           return ExprError();
10292         Args[0] = ArgsRes0.take();
10293 
10294         ExprResult ArgsRes1 =
10295           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10296                                     Best->Conversions[1], AA_Passing);
10297         if (ArgsRes1.isInvalid())
10298           return ExprError();
10299         Args[1] = ArgsRes1.take();
10300         break;
10301       }
10302     }
10303 
10304     case OR_No_Viable_Function: {
10305       // C++ [over.match.oper]p9:
10306       //   If the operator is the operator , [...] and there are no
10307       //   viable functions, then the operator is assumed to be the
10308       //   built-in operator and interpreted according to clause 5.
10309       if (Opc == BO_Comma)
10310         break;
10311 
10312       // For class as left operand for assignment or compound assigment
10313       // operator do not fall through to handling in built-in, but report that
10314       // no overloaded assignment operator found
10315       ExprResult Result = ExprError();
10316       if (Args[0]->getType()->isRecordType() &&
10317           Opc >= BO_Assign && Opc <= BO_OrAssign) {
10318         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10319              << BinaryOperator::getOpcodeStr(Opc)
10320              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10321       } else {
10322         // This is an erroneous use of an operator which can be overloaded by
10323         // a non-member function. Check for non-member operators which were
10324         // defined too late to be candidates.
10325         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10326           // FIXME: Recover by calling the found function.
10327           return ExprError();
10328 
10329         // No viable function; try to create a built-in operation, which will
10330         // produce an error. Then, show the non-viable candidates.
10331         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10332       }
10333       assert(Result.isInvalid() &&
10334              "C++ binary operator overloading is missing candidates!");
10335       if (Result.isInvalid())
10336         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10337                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
10338       return Result;
10339     }
10340 
10341     case OR_Ambiguous:
10342       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10343           << BinaryOperator::getOpcodeStr(Opc)
10344           << Args[0]->getType() << Args[1]->getType()
10345           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10346       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10347                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10348       return ExprError();
10349 
10350     case OR_Deleted:
10351       if (isImplicitlyDeleted(Best->Function)) {
10352         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10353         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10354           << getSpecialMember(Method)
10355           << BinaryOperator::getOpcodeStr(Opc)
10356           << getDeletedOrUnavailableSuffix(Best->Function);
10357 
10358         if (getSpecialMember(Method) != CXXInvalid) {
10359           // The user probably meant to call this special member. Just
10360           // explain why it's deleted.
10361           NoteDeletedFunction(Method);
10362           return ExprError();
10363         }
10364       } else {
10365         Diag(OpLoc, diag::err_ovl_deleted_oper)
10366           << Best->Function->isDeleted()
10367           << BinaryOperator::getOpcodeStr(Opc)
10368           << getDeletedOrUnavailableSuffix(Best->Function)
10369           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10370       }
10371       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10372                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10373       return ExprError();
10374   }
10375 
10376   // We matched a built-in operator; build it.
10377   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10378 }
10379 
10380 ExprResult
10381 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10382                                          SourceLocation RLoc,
10383                                          Expr *Base, Expr *Idx) {
10384   Expr *Args[2] = { Base, Idx };
10385   DeclarationName OpName =
10386       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10387 
10388   // If either side is type-dependent, create an appropriate dependent
10389   // expression.
10390   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10391 
10392     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10393     // CHECKME: no 'operator' keyword?
10394     DeclarationNameInfo OpNameInfo(OpName, LLoc);
10395     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10396     UnresolvedLookupExpr *Fn
10397       = UnresolvedLookupExpr::Create(Context, NamingClass,
10398                                      NestedNameSpecifierLoc(), OpNameInfo,
10399                                      /*ADL*/ true, /*Overloaded*/ false,
10400                                      UnresolvedSetIterator(),
10401                                      UnresolvedSetIterator());
10402     // Can't add any actual overloads yet
10403 
10404     return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10405                                                    Args,
10406                                                    Context.DependentTy,
10407                                                    VK_RValue,
10408                                                    RLoc));
10409   }
10410 
10411   // Handle placeholders on both operands.
10412   if (checkPlaceholderForOverload(*this, Args[0]))
10413     return ExprError();
10414   if (checkPlaceholderForOverload(*this, Args[1]))
10415     return ExprError();
10416 
10417   // Build an empty overload set.
10418   OverloadCandidateSet CandidateSet(LLoc);
10419 
10420   // Subscript can only be overloaded as a member function.
10421 
10422   // Add operator candidates that are member functions.
10423   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10424 
10425   // Add builtin operator candidates.
10426   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10427 
10428   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10429 
10430   // Perform overload resolution.
10431   OverloadCandidateSet::iterator Best;
10432   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10433     case OR_Success: {
10434       // We found a built-in operator or an overloaded operator.
10435       FunctionDecl *FnDecl = Best->Function;
10436 
10437       if (FnDecl) {
10438         // We matched an overloaded operator. Build a call to that
10439         // operator.
10440 
10441         MarkFunctionReferenced(LLoc, FnDecl);
10442 
10443         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10444         DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
10445 
10446         // Convert the arguments.
10447         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10448         ExprResult Arg0 =
10449           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10450                                               Best->FoundDecl, Method);
10451         if (Arg0.isInvalid())
10452           return ExprError();
10453         Args[0] = Arg0.take();
10454 
10455         // Convert the arguments.
10456         ExprResult InputInit
10457           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10458                                                       Context,
10459                                                       FnDecl->getParamDecl(0)),
10460                                       SourceLocation(),
10461                                       Owned(Args[1]));
10462         if (InputInit.isInvalid())
10463           return ExprError();
10464 
10465         Args[1] = InputInit.takeAs<Expr>();
10466 
10467         // Determine the result type
10468         QualType ResultTy = FnDecl->getResultType();
10469         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10470         ResultTy = ResultTy.getNonLValueExprType(Context);
10471 
10472         // Build the actual expression node.
10473         DeclarationNameInfo OpLocInfo(OpName, LLoc);
10474         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10475         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10476                                                   HadMultipleCandidates,
10477                                                   OpLocInfo.getLoc(),
10478                                                   OpLocInfo.getInfo());
10479         if (FnExpr.isInvalid())
10480           return ExprError();
10481 
10482         CXXOperatorCallExpr *TheCall =
10483           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10484                                             FnExpr.take(), Args,
10485                                             ResultTy, VK, RLoc);
10486 
10487         if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10488                                 FnDecl))
10489           return ExprError();
10490 
10491         return MaybeBindToTemporary(TheCall);
10492       } else {
10493         // We matched a built-in operator. Convert the arguments, then
10494         // break out so that we will build the appropriate built-in
10495         // operator node.
10496         ExprResult ArgsRes0 =
10497           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10498                                     Best->Conversions[0], AA_Passing);
10499         if (ArgsRes0.isInvalid())
10500           return ExprError();
10501         Args[0] = ArgsRes0.take();
10502 
10503         ExprResult ArgsRes1 =
10504           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10505                                     Best->Conversions[1], AA_Passing);
10506         if (ArgsRes1.isInvalid())
10507           return ExprError();
10508         Args[1] = ArgsRes1.take();
10509 
10510         break;
10511       }
10512     }
10513 
10514     case OR_No_Viable_Function: {
10515       if (CandidateSet.empty())
10516         Diag(LLoc, diag::err_ovl_no_oper)
10517           << Args[0]->getType() << /*subscript*/ 0
10518           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10519       else
10520         Diag(LLoc, diag::err_ovl_no_viable_subscript)
10521           << Args[0]->getType()
10522           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10523       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10524                                   "[]", LLoc);
10525       return ExprError();
10526     }
10527 
10528     case OR_Ambiguous:
10529       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10530           << "[]"
10531           << Args[0]->getType() << Args[1]->getType()
10532           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10533       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10534                                   "[]", LLoc);
10535       return ExprError();
10536 
10537     case OR_Deleted:
10538       Diag(LLoc, diag::err_ovl_deleted_oper)
10539         << Best->Function->isDeleted() << "[]"
10540         << getDeletedOrUnavailableSuffix(Best->Function)
10541         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10542       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10543                                   "[]", LLoc);
10544       return ExprError();
10545     }
10546 
10547   // We matched a built-in operator; build it.
10548   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10549 }
10550 
10551 /// BuildCallToMemberFunction - Build a call to a member
10552 /// function. MemExpr is the expression that refers to the member
10553 /// function (and includes the object parameter), Args/NumArgs are the
10554 /// arguments to the function call (not including the object
10555 /// parameter). The caller needs to validate that the member
10556 /// expression refers to a non-static member function or an overloaded
10557 /// member function.
10558 ExprResult
10559 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10560                                 SourceLocation LParenLoc, Expr **Args,
10561                                 unsigned NumArgs, SourceLocation RParenLoc) {
10562   assert(MemExprE->getType() == Context.BoundMemberTy ||
10563          MemExprE->getType() == Context.OverloadTy);
10564 
10565   // Dig out the member expression. This holds both the object
10566   // argument and the member function we're referring to.
10567   Expr *NakedMemExpr = MemExprE->IgnoreParens();
10568 
10569   // Determine whether this is a call to a pointer-to-member function.
10570   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10571     assert(op->getType() == Context.BoundMemberTy);
10572     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10573 
10574     QualType fnType =
10575       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10576 
10577     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10578     QualType resultType = proto->getCallResultType(Context);
10579     ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10580 
10581     // Check that the object type isn't more qualified than the
10582     // member function we're calling.
10583     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10584 
10585     QualType objectType = op->getLHS()->getType();
10586     if (op->getOpcode() == BO_PtrMemI)
10587       objectType = objectType->castAs<PointerType>()->getPointeeType();
10588     Qualifiers objectQuals = objectType.getQualifiers();
10589 
10590     Qualifiers difference = objectQuals - funcQuals;
10591     difference.removeObjCGCAttr();
10592     difference.removeAddressSpace();
10593     if (difference) {
10594       std::string qualsString = difference.getAsString();
10595       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10596         << fnType.getUnqualifiedType()
10597         << qualsString
10598         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10599     }
10600 
10601     CXXMemberCallExpr *call
10602       = new (Context) CXXMemberCallExpr(Context, MemExprE,
10603                                         llvm::makeArrayRef(Args, NumArgs),
10604                                         resultType, valueKind, RParenLoc);
10605 
10606     if (CheckCallReturnType(proto->getResultType(),
10607                             op->getRHS()->getLocStart(),
10608                             call, 0))
10609       return ExprError();
10610 
10611     if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10612       return ExprError();
10613 
10614     return MaybeBindToTemporary(call);
10615   }
10616 
10617   UnbridgedCastsSet UnbridgedCasts;
10618   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10619     return ExprError();
10620 
10621   MemberExpr *MemExpr;
10622   CXXMethodDecl *Method = 0;
10623   DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10624   NestedNameSpecifier *Qualifier = 0;
10625   if (isa<MemberExpr>(NakedMemExpr)) {
10626     MemExpr = cast<MemberExpr>(NakedMemExpr);
10627     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10628     FoundDecl = MemExpr->getFoundDecl();
10629     Qualifier = MemExpr->getQualifier();
10630     UnbridgedCasts.restore();
10631   } else {
10632     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10633     Qualifier = UnresExpr->getQualifier();
10634 
10635     QualType ObjectType = UnresExpr->getBaseType();
10636     Expr::Classification ObjectClassification
10637       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10638                             : UnresExpr->getBase()->Classify(Context);
10639 
10640     // Add overload candidates
10641     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10642 
10643     // FIXME: avoid copy.
10644     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10645     if (UnresExpr->hasExplicitTemplateArgs()) {
10646       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10647       TemplateArgs = &TemplateArgsBuffer;
10648     }
10649 
10650     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10651            E = UnresExpr->decls_end(); I != E; ++I) {
10652 
10653       NamedDecl *Func = *I;
10654       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10655       if (isa<UsingShadowDecl>(Func))
10656         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10657 
10658 
10659       // Microsoft supports direct constructor calls.
10660       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10661         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10662                              llvm::makeArrayRef(Args, NumArgs), CandidateSet);
10663       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10664         // If explicit template arguments were provided, we can't call a
10665         // non-template member function.
10666         if (TemplateArgs)
10667           continue;
10668 
10669         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10670                            ObjectClassification,
10671                            llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10672                            /*SuppressUserConversions=*/false);
10673       } else {
10674         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10675                                    I.getPair(), ActingDC, TemplateArgs,
10676                                    ObjectType,  ObjectClassification,
10677                                    llvm::makeArrayRef(Args, NumArgs),
10678                                    CandidateSet,
10679                                    /*SuppressUsedConversions=*/false);
10680       }
10681     }
10682 
10683     DeclarationName DeclName = UnresExpr->getMemberName();
10684 
10685     UnbridgedCasts.restore();
10686 
10687     OverloadCandidateSet::iterator Best;
10688     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10689                                             Best)) {
10690     case OR_Success:
10691       Method = cast<CXXMethodDecl>(Best->Function);
10692       MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
10693       FoundDecl = Best->FoundDecl;
10694       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10695       DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
10696       break;
10697 
10698     case OR_No_Viable_Function:
10699       Diag(UnresExpr->getMemberLoc(),
10700            diag::err_ovl_no_viable_member_function_in_call)
10701         << DeclName << MemExprE->getSourceRange();
10702       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10703                                   llvm::makeArrayRef(Args, NumArgs));
10704       // FIXME: Leaking incoming expressions!
10705       return ExprError();
10706 
10707     case OR_Ambiguous:
10708       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10709         << DeclName << MemExprE->getSourceRange();
10710       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10711                                   llvm::makeArrayRef(Args, NumArgs));
10712       // FIXME: Leaking incoming expressions!
10713       return ExprError();
10714 
10715     case OR_Deleted:
10716       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10717         << Best->Function->isDeleted()
10718         << DeclName
10719         << getDeletedOrUnavailableSuffix(Best->Function)
10720         << MemExprE->getSourceRange();
10721       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10722                                   llvm::makeArrayRef(Args, NumArgs));
10723       // FIXME: Leaking incoming expressions!
10724       return ExprError();
10725     }
10726 
10727     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10728 
10729     // If overload resolution picked a static member, build a
10730     // non-member call based on that function.
10731     if (Method->isStatic()) {
10732       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10733                                    Args, NumArgs, RParenLoc);
10734     }
10735 
10736     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10737   }
10738 
10739   QualType ResultType = Method->getResultType();
10740   ExprValueKind VK = Expr::getValueKindForType(ResultType);
10741   ResultType = ResultType.getNonLValueExprType(Context);
10742 
10743   assert(Method && "Member call to something that isn't a method?");
10744   CXXMemberCallExpr *TheCall =
10745     new (Context) CXXMemberCallExpr(Context, MemExprE,
10746                                     llvm::makeArrayRef(Args, NumArgs),
10747                                     ResultType, VK, RParenLoc);
10748 
10749   // Check for a valid return type.
10750   if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10751                           TheCall, Method))
10752     return ExprError();
10753 
10754   // Convert the object argument (for a non-static member function call).
10755   // We only need to do this if there was actually an overload; otherwise
10756   // it was done at lookup.
10757   if (!Method->isStatic()) {
10758     ExprResult ObjectArg =
10759       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10760                                           FoundDecl, Method);
10761     if (ObjectArg.isInvalid())
10762       return ExprError();
10763     MemExpr->setBase(ObjectArg.take());
10764   }
10765 
10766   // Convert the rest of the arguments
10767   const FunctionProtoType *Proto =
10768     Method->getType()->getAs<FunctionProtoType>();
10769   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10770                               RParenLoc))
10771     return ExprError();
10772 
10773   DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10774 
10775   if (CheckFunctionCall(Method, TheCall, Proto))
10776     return ExprError();
10777 
10778   if ((isa<CXXConstructorDecl>(CurContext) ||
10779        isa<CXXDestructorDecl>(CurContext)) &&
10780       TheCall->getMethodDecl()->isPure()) {
10781     const CXXMethodDecl *MD = TheCall->getMethodDecl();
10782 
10783     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10784       Diag(MemExpr->getLocStart(),
10785            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10786         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10787         << MD->getParent()->getDeclName();
10788 
10789       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10790     }
10791   }
10792   return MaybeBindToTemporary(TheCall);
10793 }
10794 
10795 /// BuildCallToObjectOfClassType - Build a call to an object of class
10796 /// type (C++ [over.call.object]), which can end up invoking an
10797 /// overloaded function call operator (@c operator()) or performing a
10798 /// user-defined conversion on the object argument.
10799 ExprResult
10800 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10801                                    SourceLocation LParenLoc,
10802                                    Expr **Args, unsigned NumArgs,
10803                                    SourceLocation RParenLoc) {
10804   if (checkPlaceholderForOverload(*this, Obj))
10805     return ExprError();
10806   ExprResult Object = Owned(Obj);
10807 
10808   UnbridgedCastsSet UnbridgedCasts;
10809   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10810     return ExprError();
10811 
10812   assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10813   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10814 
10815   // C++ [over.call.object]p1:
10816   //  If the primary-expression E in the function call syntax
10817   //  evaluates to a class object of type "cv T", then the set of
10818   //  candidate functions includes at least the function call
10819   //  operators of T. The function call operators of T are obtained by
10820   //  ordinary lookup of the name operator() in the context of
10821   //  (E).operator().
10822   OverloadCandidateSet CandidateSet(LParenLoc);
10823   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10824 
10825   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10826                           diag::err_incomplete_object_call, Object.get()))
10827     return true;
10828 
10829   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10830   LookupQualifiedName(R, Record->getDecl());
10831   R.suppressDiagnostics();
10832 
10833   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10834        Oper != OperEnd; ++Oper) {
10835     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10836                        Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
10837                        /*SuppressUserConversions=*/ false);
10838   }
10839 
10840   // C++ [over.call.object]p2:
10841   //   In addition, for each (non-explicit in C++0x) conversion function
10842   //   declared in T of the form
10843   //
10844   //        operator conversion-type-id () cv-qualifier;
10845   //
10846   //   where cv-qualifier is the same cv-qualification as, or a
10847   //   greater cv-qualification than, cv, and where conversion-type-id
10848   //   denotes the type "pointer to function of (P1,...,Pn) returning
10849   //   R", or the type "reference to pointer to function of
10850   //   (P1,...,Pn) returning R", or the type "reference to function
10851   //   of (P1,...,Pn) returning R", a surrogate call function [...]
10852   //   is also considered as a candidate function. Similarly,
10853   //   surrogate call functions are added to the set of candidate
10854   //   functions for each conversion function declared in an
10855   //   accessible base class provided the function is not hidden
10856   //   within T by another intervening declaration.
10857   const UnresolvedSetImpl *Conversions
10858     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
10859   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
10860          E = Conversions->end(); I != E; ++I) {
10861     NamedDecl *D = *I;
10862     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10863     if (isa<UsingShadowDecl>(D))
10864       D = cast<UsingShadowDecl>(D)->getTargetDecl();
10865 
10866     // Skip over templated conversion functions; they aren't
10867     // surrogates.
10868     if (isa<FunctionTemplateDecl>(D))
10869       continue;
10870 
10871     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
10872     if (!Conv->isExplicit()) {
10873       // Strip the reference type (if any) and then the pointer type (if
10874       // any) to get down to what might be a function type.
10875       QualType ConvType = Conv->getConversionType().getNonReferenceType();
10876       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10877         ConvType = ConvPtrType->getPointeeType();
10878 
10879       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10880       {
10881         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10882                               Object.get(), llvm::makeArrayRef(Args, NumArgs),
10883                               CandidateSet);
10884       }
10885     }
10886   }
10887 
10888   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10889 
10890   // Perform overload resolution.
10891   OverloadCandidateSet::iterator Best;
10892   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
10893                              Best)) {
10894   case OR_Success:
10895     // Overload resolution succeeded; we'll build the appropriate call
10896     // below.
10897     break;
10898 
10899   case OR_No_Viable_Function:
10900     if (CandidateSet.empty())
10901       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
10902         << Object.get()->getType() << /*call*/ 1
10903         << Object.get()->getSourceRange();
10904     else
10905       Diag(Object.get()->getLocStart(),
10906            diag::err_ovl_no_viable_object_call)
10907         << Object.get()->getType() << Object.get()->getSourceRange();
10908     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10909                                 llvm::makeArrayRef(Args, NumArgs));
10910     break;
10911 
10912   case OR_Ambiguous:
10913     Diag(Object.get()->getLocStart(),
10914          diag::err_ovl_ambiguous_object_call)
10915       << Object.get()->getType() << Object.get()->getSourceRange();
10916     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10917                                 llvm::makeArrayRef(Args, NumArgs));
10918     break;
10919 
10920   case OR_Deleted:
10921     Diag(Object.get()->getLocStart(),
10922          diag::err_ovl_deleted_object_call)
10923       << Best->Function->isDeleted()
10924       << Object.get()->getType()
10925       << getDeletedOrUnavailableSuffix(Best->Function)
10926       << Object.get()->getSourceRange();
10927     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10928                                 llvm::makeArrayRef(Args, NumArgs));
10929     break;
10930   }
10931 
10932   if (Best == CandidateSet.end())
10933     return true;
10934 
10935   UnbridgedCasts.restore();
10936 
10937   if (Best->Function == 0) {
10938     // Since there is no function declaration, this is one of the
10939     // surrogate candidates. Dig out the conversion function.
10940     CXXConversionDecl *Conv
10941       = cast<CXXConversionDecl>(
10942                          Best->Conversions[0].UserDefined.ConversionFunction);
10943 
10944     CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10945     DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10946 
10947     // We selected one of the surrogate functions that converts the
10948     // object parameter to a function pointer. Perform the conversion
10949     // on the object argument, then let ActOnCallExpr finish the job.
10950 
10951     // Create an implicit member expr to refer to the conversion operator.
10952     // and then call it.
10953     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10954                                              Conv, HadMultipleCandidates);
10955     if (Call.isInvalid())
10956       return ExprError();
10957     // Record usage of conversion in an implicit cast.
10958     Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10959                                           CK_UserDefinedConversion,
10960                                           Call.get(), 0, VK_RValue));
10961 
10962     return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
10963                          RParenLoc);
10964   }
10965 
10966   MarkFunctionReferenced(LParenLoc, Best->Function);
10967   CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10968   DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10969 
10970   // We found an overloaded operator(). Build a CXXOperatorCallExpr
10971   // that calls this method, using Object for the implicit object
10972   // parameter and passing along the remaining arguments.
10973   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10974   const FunctionProtoType *Proto =
10975     Method->getType()->getAs<FunctionProtoType>();
10976 
10977   unsigned NumArgsInProto = Proto->getNumArgs();
10978   unsigned NumArgsToCheck = NumArgs;
10979 
10980   // Build the full argument list for the method call (the
10981   // implicit object parameter is placed at the beginning of the
10982   // list).
10983   Expr **MethodArgs;
10984   if (NumArgs < NumArgsInProto) {
10985     NumArgsToCheck = NumArgsInProto;
10986     MethodArgs = new Expr*[NumArgsInProto + 1];
10987   } else {
10988     MethodArgs = new Expr*[NumArgs + 1];
10989   }
10990   MethodArgs[0] = Object.get();
10991   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10992     MethodArgs[ArgIdx + 1] = Args[ArgIdx];
10993 
10994   DeclarationNameInfo OpLocInfo(
10995                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10996   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
10997   ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10998                                            HadMultipleCandidates,
10999                                            OpLocInfo.getLoc(),
11000                                            OpLocInfo.getInfo());
11001   if (NewFn.isInvalid())
11002     return true;
11003 
11004   // Once we've built TheCall, all of the expressions are properly
11005   // owned.
11006   QualType ResultTy = Method->getResultType();
11007   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11008   ResultTy = ResultTy.getNonLValueExprType(Context);
11009 
11010   CXXOperatorCallExpr *TheCall =
11011     new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11012                                       llvm::makeArrayRef(MethodArgs, NumArgs+1),
11013                                       ResultTy, VK, RParenLoc);
11014   delete [] MethodArgs;
11015 
11016   if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11017                           Method))
11018     return true;
11019 
11020   // We may have default arguments. If so, we need to allocate more
11021   // slots in the call for them.
11022   if (NumArgs < NumArgsInProto)
11023     TheCall->setNumArgs(Context, NumArgsInProto + 1);
11024   else if (NumArgs > NumArgsInProto)
11025     NumArgsToCheck = NumArgsInProto;
11026 
11027   bool IsError = false;
11028 
11029   // Initialize the implicit object parameter.
11030   ExprResult ObjRes =
11031     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11032                                         Best->FoundDecl, Method);
11033   if (ObjRes.isInvalid())
11034     IsError = true;
11035   else
11036     Object = ObjRes;
11037   TheCall->setArg(0, Object.take());
11038 
11039   // Check the argument types.
11040   for (unsigned i = 0; i != NumArgsToCheck; i++) {
11041     Expr *Arg;
11042     if (i < NumArgs) {
11043       Arg = Args[i];
11044 
11045       // Pass the argument.
11046 
11047       ExprResult InputInit
11048         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11049                                                     Context,
11050                                                     Method->getParamDecl(i)),
11051                                     SourceLocation(), Arg);
11052 
11053       IsError |= InputInit.isInvalid();
11054       Arg = InputInit.takeAs<Expr>();
11055     } else {
11056       ExprResult DefArg
11057         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11058       if (DefArg.isInvalid()) {
11059         IsError = true;
11060         break;
11061       }
11062 
11063       Arg = DefArg.takeAs<Expr>();
11064     }
11065 
11066     TheCall->setArg(i + 1, Arg);
11067   }
11068 
11069   // If this is a variadic call, handle args passed through "...".
11070   if (Proto->isVariadic()) {
11071     // Promote the arguments (C99 6.5.2.2p7).
11072     for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
11073       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11074       IsError |= Arg.isInvalid();
11075       TheCall->setArg(i + 1, Arg.take());
11076     }
11077   }
11078 
11079   if (IsError) return true;
11080 
11081   DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11082 
11083   if (CheckFunctionCall(Method, TheCall, Proto))
11084     return true;
11085 
11086   return MaybeBindToTemporary(TheCall);
11087 }
11088 
11089 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11090 ///  (if one exists), where @c Base is an expression of class type and
11091 /// @c Member is the name of the member we're trying to find.
11092 ExprResult
11093 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
11094   assert(Base->getType()->isRecordType() &&
11095          "left-hand side must have class type");
11096 
11097   if (checkPlaceholderForOverload(*this, Base))
11098     return ExprError();
11099 
11100   SourceLocation Loc = Base->getExprLoc();
11101 
11102   // C++ [over.ref]p1:
11103   //
11104   //   [...] An expression x->m is interpreted as (x.operator->())->m
11105   //   for a class object x of type T if T::operator->() exists and if
11106   //   the operator is selected as the best match function by the
11107   //   overload resolution mechanism (13.3).
11108   DeclarationName OpName =
11109     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11110   OverloadCandidateSet CandidateSet(Loc);
11111   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11112 
11113   if (RequireCompleteType(Loc, Base->getType(),
11114                           diag::err_typecheck_incomplete_tag, Base))
11115     return ExprError();
11116 
11117   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11118   LookupQualifiedName(R, BaseRecord->getDecl());
11119   R.suppressDiagnostics();
11120 
11121   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11122        Oper != OperEnd; ++Oper) {
11123     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11124                        0, 0, CandidateSet, /*SuppressUserConversions=*/false);
11125   }
11126 
11127   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11128 
11129   // Perform overload resolution.
11130   OverloadCandidateSet::iterator Best;
11131   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11132   case OR_Success:
11133     // Overload resolution succeeded; we'll build the call below.
11134     break;
11135 
11136   case OR_No_Viable_Function:
11137     if (CandidateSet.empty())
11138       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11139         << Base->getType() << Base->getSourceRange();
11140     else
11141       Diag(OpLoc, diag::err_ovl_no_viable_oper)
11142         << "operator->" << Base->getSourceRange();
11143     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11144     return ExprError();
11145 
11146   case OR_Ambiguous:
11147     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11148       << "->" << Base->getType() << Base->getSourceRange();
11149     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11150     return ExprError();
11151 
11152   case OR_Deleted:
11153     Diag(OpLoc,  diag::err_ovl_deleted_oper)
11154       << Best->Function->isDeleted()
11155       << "->"
11156       << getDeletedOrUnavailableSuffix(Best->Function)
11157       << Base->getSourceRange();
11158     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11159     return ExprError();
11160   }
11161 
11162   MarkFunctionReferenced(OpLoc, Best->Function);
11163   CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11164   DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
11165 
11166   // Convert the object parameter.
11167   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11168   ExprResult BaseResult =
11169     PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11170                                         Best->FoundDecl, Method);
11171   if (BaseResult.isInvalid())
11172     return ExprError();
11173   Base = BaseResult.take();
11174 
11175   // Build the operator call.
11176   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
11177                                             HadMultipleCandidates, OpLoc);
11178   if (FnExpr.isInvalid())
11179     return ExprError();
11180 
11181   QualType ResultTy = Method->getResultType();
11182   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11183   ResultTy = ResultTy.getNonLValueExprType(Context);
11184   CXXOperatorCallExpr *TheCall =
11185     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11186                                       Base, ResultTy, VK, OpLoc);
11187 
11188   if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11189                           Method))
11190           return ExprError();
11191 
11192   return MaybeBindToTemporary(TheCall);
11193 }
11194 
11195 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11196 /// a literal operator described by the provided lookup results.
11197 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11198                                           DeclarationNameInfo &SuffixInfo,
11199                                           ArrayRef<Expr*> Args,
11200                                           SourceLocation LitEndLoc,
11201                                        TemplateArgumentListInfo *TemplateArgs) {
11202   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11203 
11204   OverloadCandidateSet CandidateSet(UDSuffixLoc);
11205   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11206                         TemplateArgs);
11207 
11208   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11209 
11210   // Perform overload resolution. This will usually be trivial, but might need
11211   // to perform substitutions for a literal operator template.
11212   OverloadCandidateSet::iterator Best;
11213   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11214   case OR_Success:
11215   case OR_Deleted:
11216     break;
11217 
11218   case OR_No_Viable_Function:
11219     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11220       << R.getLookupName();
11221     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11222     return ExprError();
11223 
11224   case OR_Ambiguous:
11225     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11226     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11227     return ExprError();
11228   }
11229 
11230   FunctionDecl *FD = Best->Function;
11231   MarkFunctionReferenced(UDSuffixLoc, FD);
11232   DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
11233 
11234   ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11235                                         SuffixInfo.getLoc(),
11236                                         SuffixInfo.getInfo());
11237   if (Fn.isInvalid())
11238     return true;
11239 
11240   // Check the argument types. This should almost always be a no-op, except
11241   // that array-to-pointer decay is applied to string literals.
11242   Expr *ConvArgs[2];
11243   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11244     ExprResult InputInit = PerformCopyInitialization(
11245       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11246       SourceLocation(), Args[ArgIdx]);
11247     if (InputInit.isInvalid())
11248       return true;
11249     ConvArgs[ArgIdx] = InputInit.take();
11250   }
11251 
11252   QualType ResultTy = FD->getResultType();
11253   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11254   ResultTy = ResultTy.getNonLValueExprType(Context);
11255 
11256   UserDefinedLiteral *UDL =
11257     new (Context) UserDefinedLiteral(Context, Fn.take(),
11258                                      llvm::makeArrayRef(ConvArgs, Args.size()),
11259                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
11260 
11261   if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11262     return ExprError();
11263 
11264   if (CheckFunctionCall(FD, UDL, NULL))
11265     return ExprError();
11266 
11267   return MaybeBindToTemporary(UDL);
11268 }
11269 
11270 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11271 /// given LookupResult is non-empty, it is assumed to describe a member which
11272 /// will be invoked. Otherwise, the function will be found via argument
11273 /// dependent lookup.
11274 /// CallExpr is set to a valid expression and FRS_Success returned on success,
11275 /// otherwise CallExpr is set to ExprError() and some non-success value
11276 /// is returned.
11277 Sema::ForRangeStatus
11278 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11279                                 SourceLocation RangeLoc, VarDecl *Decl,
11280                                 BeginEndFunction BEF,
11281                                 const DeclarationNameInfo &NameInfo,
11282                                 LookupResult &MemberLookup,
11283                                 OverloadCandidateSet *CandidateSet,
11284                                 Expr *Range, ExprResult *CallExpr) {
11285   CandidateSet->clear();
11286   if (!MemberLookup.empty()) {
11287     ExprResult MemberRef =
11288         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11289                                  /*IsPtr=*/false, CXXScopeSpec(),
11290                                  /*TemplateKWLoc=*/SourceLocation(),
11291                                  /*FirstQualifierInScope=*/0,
11292                                  MemberLookup,
11293                                  /*TemplateArgs=*/0);
11294     if (MemberRef.isInvalid()) {
11295       *CallExpr = ExprError();
11296       Diag(Range->getLocStart(), diag::note_in_for_range)
11297           << RangeLoc << BEF << Range->getType();
11298       return FRS_DiagnosticIssued;
11299     }
11300     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11301     if (CallExpr->isInvalid()) {
11302       *CallExpr = ExprError();
11303       Diag(Range->getLocStart(), diag::note_in_for_range)
11304           << RangeLoc << BEF << Range->getType();
11305       return FRS_DiagnosticIssued;
11306     }
11307   } else {
11308     UnresolvedSet<0> FoundNames;
11309     // C++11 [stmt.ranged]p1: For the purposes of this name lookup, namespace
11310     // std is an associated namespace.
11311     UnresolvedLookupExpr *Fn =
11312       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11313                                    NestedNameSpecifierLoc(), NameInfo,
11314                                    /*NeedsADL=*/true, /*Overloaded=*/false,
11315                                    FoundNames.begin(), FoundNames.end(),
11316                                    /*LookInStdNamespace=*/true);
11317 
11318     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11319                                                     CandidateSet, CallExpr);
11320     if (CandidateSet->empty() || CandidateSetError) {
11321       *CallExpr = ExprError();
11322       return FRS_NoViableFunction;
11323     }
11324     OverloadCandidateSet::iterator Best;
11325     OverloadingResult OverloadResult =
11326         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11327 
11328     if (OverloadResult == OR_No_Viable_Function) {
11329       *CallExpr = ExprError();
11330       return FRS_NoViableFunction;
11331     }
11332     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11333                                          Loc, 0, CandidateSet, &Best,
11334                                          OverloadResult,
11335                                          /*AllowTypoCorrection=*/false);
11336     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11337       *CallExpr = ExprError();
11338       Diag(Range->getLocStart(), diag::note_in_for_range)
11339           << RangeLoc << BEF << Range->getType();
11340       return FRS_DiagnosticIssued;
11341     }
11342   }
11343   return FRS_Success;
11344 }
11345 
11346 
11347 /// FixOverloadedFunctionReference - E is an expression that refers to
11348 /// a C++ overloaded function (possibly with some parentheses and
11349 /// perhaps a '&' around it). We have resolved the overloaded function
11350 /// to the function declaration Fn, so patch up the expression E to
11351 /// refer (possibly indirectly) to Fn. Returns the new expr.
11352 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11353                                            FunctionDecl *Fn) {
11354   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11355     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11356                                                    Found, Fn);
11357     if (SubExpr == PE->getSubExpr())
11358       return PE;
11359 
11360     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11361   }
11362 
11363   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11364     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11365                                                    Found, Fn);
11366     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11367                                SubExpr->getType()) &&
11368            "Implicit cast type cannot be determined from overload");
11369     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11370     if (SubExpr == ICE->getSubExpr())
11371       return ICE;
11372 
11373     return ImplicitCastExpr::Create(Context, ICE->getType(),
11374                                     ICE->getCastKind(),
11375                                     SubExpr, 0,
11376                                     ICE->getValueKind());
11377   }
11378 
11379   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11380     assert(UnOp->getOpcode() == UO_AddrOf &&
11381            "Can only take the address of an overloaded function");
11382     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11383       if (Method->isStatic()) {
11384         // Do nothing: static member functions aren't any different
11385         // from non-member functions.
11386       } else {
11387         // Fix the sub expression, which really has to be an
11388         // UnresolvedLookupExpr holding an overloaded member function
11389         // or template.
11390         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11391                                                        Found, Fn);
11392         if (SubExpr == UnOp->getSubExpr())
11393           return UnOp;
11394 
11395         assert(isa<DeclRefExpr>(SubExpr)
11396                && "fixed to something other than a decl ref");
11397         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11398                && "fixed to a member ref with no nested name qualifier");
11399 
11400         // We have taken the address of a pointer to member
11401         // function. Perform the computation here so that we get the
11402         // appropriate pointer to member type.
11403         QualType ClassType
11404           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11405         QualType MemPtrType
11406           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11407 
11408         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11409                                            VK_RValue, OK_Ordinary,
11410                                            UnOp->getOperatorLoc());
11411       }
11412     }
11413     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11414                                                    Found, Fn);
11415     if (SubExpr == UnOp->getSubExpr())
11416       return UnOp;
11417 
11418     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11419                                      Context.getPointerType(SubExpr->getType()),
11420                                        VK_RValue, OK_Ordinary,
11421                                        UnOp->getOperatorLoc());
11422   }
11423 
11424   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11425     // FIXME: avoid copy.
11426     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11427     if (ULE->hasExplicitTemplateArgs()) {
11428       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11429       TemplateArgs = &TemplateArgsBuffer;
11430     }
11431 
11432     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11433                                            ULE->getQualifierLoc(),
11434                                            ULE->getTemplateKeywordLoc(),
11435                                            Fn,
11436                                            /*enclosing*/ false, // FIXME?
11437                                            ULE->getNameLoc(),
11438                                            Fn->getType(),
11439                                            VK_LValue,
11440                                            Found.getDecl(),
11441                                            TemplateArgs);
11442     MarkDeclRefReferenced(DRE);
11443     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11444     return DRE;
11445   }
11446 
11447   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11448     // FIXME: avoid copy.
11449     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11450     if (MemExpr->hasExplicitTemplateArgs()) {
11451       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11452       TemplateArgs = &TemplateArgsBuffer;
11453     }
11454 
11455     Expr *Base;
11456 
11457     // If we're filling in a static method where we used to have an
11458     // implicit member access, rewrite to a simple decl ref.
11459     if (MemExpr->isImplicitAccess()) {
11460       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11461         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11462                                                MemExpr->getQualifierLoc(),
11463                                                MemExpr->getTemplateKeywordLoc(),
11464                                                Fn,
11465                                                /*enclosing*/ false,
11466                                                MemExpr->getMemberLoc(),
11467                                                Fn->getType(),
11468                                                VK_LValue,
11469                                                Found.getDecl(),
11470                                                TemplateArgs);
11471         MarkDeclRefReferenced(DRE);
11472         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11473         return DRE;
11474       } else {
11475         SourceLocation Loc = MemExpr->getMemberLoc();
11476         if (MemExpr->getQualifier())
11477           Loc = MemExpr->getQualifierLoc().getBeginLoc();
11478         CheckCXXThisCapture(Loc);
11479         Base = new (Context) CXXThisExpr(Loc,
11480                                          MemExpr->getBaseType(),
11481                                          /*isImplicit=*/true);
11482       }
11483     } else
11484       Base = MemExpr->getBase();
11485 
11486     ExprValueKind valueKind;
11487     QualType type;
11488     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11489       valueKind = VK_LValue;
11490       type = Fn->getType();
11491     } else {
11492       valueKind = VK_RValue;
11493       type = Context.BoundMemberTy;
11494     }
11495 
11496     MemberExpr *ME = MemberExpr::Create(Context, Base,
11497                                         MemExpr->isArrow(),
11498                                         MemExpr->getQualifierLoc(),
11499                                         MemExpr->getTemplateKeywordLoc(),
11500                                         Fn,
11501                                         Found,
11502                                         MemExpr->getMemberNameInfo(),
11503                                         TemplateArgs,
11504                                         type, valueKind, OK_Ordinary);
11505     ME->setHadMultipleCandidates(true);
11506     return ME;
11507   }
11508 
11509   llvm_unreachable("Invalid reference to overloaded function");
11510 }
11511 
11512 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11513                                                 DeclAccessPair Found,
11514                                                 FunctionDecl *Fn) {
11515   return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11516 }
11517 
11518 } // end namespace clang
11519