1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallString.h"
34 #include <algorithm>
35 
36 namespace clang {
37 using namespace sema;
38 
39 /// A convenience routine for creating a decayed reference to a function.
40 static ExprResult
41 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42                       bool HadMultipleCandidates,
43                       SourceLocation Loc = SourceLocation(),
44                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
45   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
46     return ExprError();
47   // If FoundDecl is different from Fn (such as if one is a template
48   // and the other a specialization), make sure DiagnoseUseOfDecl is
49   // called on both.
50   // FIXME: This would be more comprehensively addressed by modifying
51   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
52   // being used.
53   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
54     return ExprError();
55   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
56                                                  VK_LValue, Loc, LocInfo);
57   if (HadMultipleCandidates)
58     DRE->setHadMultipleCandidates(true);
59 
60   S.MarkDeclRefReferenced(DRE);
61 
62   ExprResult E = S.Owned(DRE);
63   E = S.DefaultFunctionArrayConversion(E.take());
64   if (E.isInvalid())
65     return ExprError();
66   return E;
67 }
68 
69 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
70                                  bool InOverloadResolution,
71                                  StandardConversionSequence &SCS,
72                                  bool CStyle,
73                                  bool AllowObjCWritebackConversion);
74 
75 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
76                                                  QualType &ToType,
77                                                  bool InOverloadResolution,
78                                                  StandardConversionSequence &SCS,
79                                                  bool CStyle);
80 static OverloadingResult
81 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
82                         UserDefinedConversionSequence& User,
83                         OverloadCandidateSet& Conversions,
84                         bool AllowExplicit);
85 
86 
87 static ImplicitConversionSequence::CompareKind
88 CompareStandardConversionSequences(Sema &S,
89                                    const StandardConversionSequence& SCS1,
90                                    const StandardConversionSequence& SCS2);
91 
92 static ImplicitConversionSequence::CompareKind
93 CompareQualificationConversions(Sema &S,
94                                 const StandardConversionSequence& SCS1,
95                                 const StandardConversionSequence& SCS2);
96 
97 static ImplicitConversionSequence::CompareKind
98 CompareDerivedToBaseConversions(Sema &S,
99                                 const StandardConversionSequence& SCS1,
100                                 const StandardConversionSequence& SCS2);
101 
102 
103 
104 /// GetConversionCategory - Retrieve the implicit conversion
105 /// category corresponding to the given implicit conversion kind.
106 ImplicitConversionCategory
107 GetConversionCategory(ImplicitConversionKind Kind) {
108   static const ImplicitConversionCategory
109     Category[(int)ICK_Num_Conversion_Kinds] = {
110     ICC_Identity,
111     ICC_Lvalue_Transformation,
112     ICC_Lvalue_Transformation,
113     ICC_Lvalue_Transformation,
114     ICC_Identity,
115     ICC_Qualification_Adjustment,
116     ICC_Promotion,
117     ICC_Promotion,
118     ICC_Promotion,
119     ICC_Conversion,
120     ICC_Conversion,
121     ICC_Conversion,
122     ICC_Conversion,
123     ICC_Conversion,
124     ICC_Conversion,
125     ICC_Conversion,
126     ICC_Conversion,
127     ICC_Conversion,
128     ICC_Conversion,
129     ICC_Conversion,
130     ICC_Conversion,
131     ICC_Conversion
132   };
133   return Category[(int)Kind];
134 }
135 
136 /// GetConversionRank - Retrieve the implicit conversion rank
137 /// corresponding to the given implicit conversion kind.
138 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
139   static const ImplicitConversionRank
140     Rank[(int)ICK_Num_Conversion_Kinds] = {
141     ICR_Exact_Match,
142     ICR_Exact_Match,
143     ICR_Exact_Match,
144     ICR_Exact_Match,
145     ICR_Exact_Match,
146     ICR_Exact_Match,
147     ICR_Promotion,
148     ICR_Promotion,
149     ICR_Promotion,
150     ICR_Conversion,
151     ICR_Conversion,
152     ICR_Conversion,
153     ICR_Conversion,
154     ICR_Conversion,
155     ICR_Conversion,
156     ICR_Conversion,
157     ICR_Conversion,
158     ICR_Conversion,
159     ICR_Conversion,
160     ICR_Conversion,
161     ICR_Complex_Real_Conversion,
162     ICR_Conversion,
163     ICR_Conversion,
164     ICR_Writeback_Conversion
165   };
166   return Rank[(int)Kind];
167 }
168 
169 /// GetImplicitConversionName - Return the name of this kind of
170 /// implicit conversion.
171 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
172   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
173     "No conversion",
174     "Lvalue-to-rvalue",
175     "Array-to-pointer",
176     "Function-to-pointer",
177     "Noreturn adjustment",
178     "Qualification",
179     "Integral promotion",
180     "Floating point promotion",
181     "Complex promotion",
182     "Integral conversion",
183     "Floating conversion",
184     "Complex conversion",
185     "Floating-integral conversion",
186     "Pointer conversion",
187     "Pointer-to-member conversion",
188     "Boolean conversion",
189     "Compatible-types conversion",
190     "Derived-to-base conversion",
191     "Vector conversion",
192     "Vector splat",
193     "Complex-real conversion",
194     "Block Pointer conversion",
195     "Transparent Union Conversion"
196     "Writeback conversion"
197   };
198   return Name[Kind];
199 }
200 
201 /// StandardConversionSequence - Set the standard conversion
202 /// sequence to the identity conversion.
203 void StandardConversionSequence::setAsIdentityConversion() {
204   First = ICK_Identity;
205   Second = ICK_Identity;
206   Third = ICK_Identity;
207   DeprecatedStringLiteralToCharPtr = false;
208   QualificationIncludesObjCLifetime = false;
209   ReferenceBinding = false;
210   DirectBinding = false;
211   IsLvalueReference = true;
212   BindsToFunctionLvalue = false;
213   BindsToRvalue = false;
214   BindsImplicitObjectArgumentWithoutRefQualifier = false;
215   ObjCLifetimeConversionBinding = false;
216   CopyConstructor = 0;
217 }
218 
219 /// getRank - Retrieve the rank of this standard conversion sequence
220 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
221 /// implicit conversions.
222 ImplicitConversionRank StandardConversionSequence::getRank() const {
223   ImplicitConversionRank Rank = ICR_Exact_Match;
224   if  (GetConversionRank(First) > Rank)
225     Rank = GetConversionRank(First);
226   if  (GetConversionRank(Second) > Rank)
227     Rank = GetConversionRank(Second);
228   if  (GetConversionRank(Third) > Rank)
229     Rank = GetConversionRank(Third);
230   return Rank;
231 }
232 
233 /// isPointerConversionToBool - Determines whether this conversion is
234 /// a conversion of a pointer or pointer-to-member to bool. This is
235 /// used as part of the ranking of standard conversion sequences
236 /// (C++ 13.3.3.2p4).
237 bool StandardConversionSequence::isPointerConversionToBool() const {
238   // Note that FromType has not necessarily been transformed by the
239   // array-to-pointer or function-to-pointer implicit conversions, so
240   // check for their presence as well as checking whether FromType is
241   // a pointer.
242   if (getToType(1)->isBooleanType() &&
243       (getFromType()->isPointerType() ||
244        getFromType()->isObjCObjectPointerType() ||
245        getFromType()->isBlockPointerType() ||
246        getFromType()->isNullPtrType() ||
247        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
248     return true;
249 
250   return false;
251 }
252 
253 /// isPointerConversionToVoidPointer - Determines whether this
254 /// conversion is a conversion of a pointer to a void pointer. This is
255 /// used as part of the ranking of standard conversion sequences (C++
256 /// 13.3.3.2p4).
257 bool
258 StandardConversionSequence::
259 isPointerConversionToVoidPointer(ASTContext& Context) const {
260   QualType FromType = getFromType();
261   QualType ToType = getToType(1);
262 
263   // Note that FromType has not necessarily been transformed by the
264   // array-to-pointer implicit conversion, so check for its presence
265   // and redo the conversion to get a pointer.
266   if (First == ICK_Array_To_Pointer)
267     FromType = Context.getArrayDecayedType(FromType);
268 
269   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
270     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
271       return ToPtrType->getPointeeType()->isVoidType();
272 
273   return false;
274 }
275 
276 /// Skip any implicit casts which could be either part of a narrowing conversion
277 /// or after one in an implicit conversion.
278 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
279   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280     switch (ICE->getCastKind()) {
281     case CK_NoOp:
282     case CK_IntegralCast:
283     case CK_IntegralToBoolean:
284     case CK_IntegralToFloating:
285     case CK_FloatingToIntegral:
286     case CK_FloatingToBoolean:
287     case CK_FloatingCast:
288       Converted = ICE->getSubExpr();
289       continue;
290 
291     default:
292       return Converted;
293     }
294   }
295 
296   return Converted;
297 }
298 
299 /// Check if this standard conversion sequence represents a narrowing
300 /// conversion, according to C++11 [dcl.init.list]p7.
301 ///
302 /// \param Ctx  The AST context.
303 /// \param Converted  The result of applying this standard conversion sequence.
304 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
305 ///        value of the expression prior to the narrowing conversion.
306 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
307 ///        type of the expression prior to the narrowing conversion.
308 NarrowingKind
309 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
310                                              const Expr *Converted,
311                                              APValue &ConstantValue,
312                                              QualType &ConstantType) const {
313   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
314 
315   // C++11 [dcl.init.list]p7:
316   //   A narrowing conversion is an implicit conversion ...
317   QualType FromType = getToType(0);
318   QualType ToType = getToType(1);
319   switch (Second) {
320   // -- from a floating-point type to an integer type, or
321   //
322   // -- from an integer type or unscoped enumeration type to a floating-point
323   //    type, except where the source is a constant expression and the actual
324   //    value after conversion will fit into the target type and will produce
325   //    the original value when converted back to the original type, or
326   case ICK_Floating_Integral:
327     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328       return NK_Type_Narrowing;
329     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330       llvm::APSInt IntConstantValue;
331       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
332       if (Initializer &&
333           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
334         // Convert the integer to the floating type.
335         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
336         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
337                                 llvm::APFloat::rmNearestTiesToEven);
338         // And back.
339         llvm::APSInt ConvertedValue = IntConstantValue;
340         bool ignored;
341         Result.convertToInteger(ConvertedValue,
342                                 llvm::APFloat::rmTowardZero, &ignored);
343         // If the resulting value is different, this was a narrowing conversion.
344         if (IntConstantValue != ConvertedValue) {
345           ConstantValue = APValue(IntConstantValue);
346           ConstantType = Initializer->getType();
347           return NK_Constant_Narrowing;
348         }
349       } else {
350         // Variables are always narrowings.
351         return NK_Variable_Narrowing;
352       }
353     }
354     return NK_Not_Narrowing;
355 
356   // -- from long double to double or float, or from double to float, except
357   //    where the source is a constant expression and the actual value after
358   //    conversion is within the range of values that can be represented (even
359   //    if it cannot be represented exactly), or
360   case ICK_Floating_Conversion:
361     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
362         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
363       // FromType is larger than ToType.
364       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
365       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
366         // Constant!
367         assert(ConstantValue.isFloat());
368         llvm::APFloat FloatVal = ConstantValue.getFloat();
369         // Convert the source value into the target type.
370         bool ignored;
371         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
372           Ctx.getFloatTypeSemantics(ToType),
373           llvm::APFloat::rmNearestTiesToEven, &ignored);
374         // If there was no overflow, the source value is within the range of
375         // values that can be represented.
376         if (ConvertStatus & llvm::APFloat::opOverflow) {
377           ConstantType = Initializer->getType();
378           return NK_Constant_Narrowing;
379         }
380       } else {
381         return NK_Variable_Narrowing;
382       }
383     }
384     return NK_Not_Narrowing;
385 
386   // -- from an integer type or unscoped enumeration type to an integer type
387   //    that cannot represent all the values of the original type, except where
388   //    the source is a constant expression and the actual value after
389   //    conversion will fit into the target type and will produce the original
390   //    value when converted back to the original type.
391   case ICK_Boolean_Conversion:  // Bools are integers too.
392     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
393       // Boolean conversions can be from pointers and pointers to members
394       // [conv.bool], and those aren't considered narrowing conversions.
395       return NK_Not_Narrowing;
396     }  // Otherwise, fall through to the integral case.
397   case ICK_Integral_Conversion: {
398     assert(FromType->isIntegralOrUnscopedEnumerationType());
399     assert(ToType->isIntegralOrUnscopedEnumerationType());
400     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
401     const unsigned FromWidth = Ctx.getIntWidth(FromType);
402     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
403     const unsigned ToWidth = Ctx.getIntWidth(ToType);
404 
405     if (FromWidth > ToWidth ||
406         (FromWidth == ToWidth && FromSigned != ToSigned) ||
407         (FromSigned && !ToSigned)) {
408       // Not all values of FromType can be represented in ToType.
409       llvm::APSInt InitializerValue;
410       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
411       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
412         // Such conversions on variables are always narrowing.
413         return NK_Variable_Narrowing;
414       }
415       bool Narrowing = false;
416       if (FromWidth < ToWidth) {
417         // Negative -> unsigned is narrowing. Otherwise, more bits is never
418         // narrowing.
419         if (InitializerValue.isSigned() && InitializerValue.isNegative())
420           Narrowing = true;
421       } else {
422         // Add a bit to the InitializerValue so we don't have to worry about
423         // signed vs. unsigned comparisons.
424         InitializerValue = InitializerValue.extend(
425           InitializerValue.getBitWidth() + 1);
426         // Convert the initializer to and from the target width and signed-ness.
427         llvm::APSInt ConvertedValue = InitializerValue;
428         ConvertedValue = ConvertedValue.trunc(ToWidth);
429         ConvertedValue.setIsSigned(ToSigned);
430         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
431         ConvertedValue.setIsSigned(InitializerValue.isSigned());
432         // If the result is different, this was a narrowing conversion.
433         if (ConvertedValue != InitializerValue)
434           Narrowing = true;
435       }
436       if (Narrowing) {
437         ConstantType = Initializer->getType();
438         ConstantValue = APValue(InitializerValue);
439         return NK_Constant_Narrowing;
440       }
441     }
442     return NK_Not_Narrowing;
443   }
444 
445   default:
446     // Other kinds of conversions are not narrowings.
447     return NK_Not_Narrowing;
448   }
449 }
450 
451 /// DebugPrint - Print this standard conversion sequence to standard
452 /// error. Useful for debugging overloading issues.
453 void StandardConversionSequence::DebugPrint() const {
454   raw_ostream &OS = llvm::errs();
455   bool PrintedSomething = false;
456   if (First != ICK_Identity) {
457     OS << GetImplicitConversionName(First);
458     PrintedSomething = true;
459   }
460 
461   if (Second != ICK_Identity) {
462     if (PrintedSomething) {
463       OS << " -> ";
464     }
465     OS << GetImplicitConversionName(Second);
466 
467     if (CopyConstructor) {
468       OS << " (by copy constructor)";
469     } else if (DirectBinding) {
470       OS << " (direct reference binding)";
471     } else if (ReferenceBinding) {
472       OS << " (reference binding)";
473     }
474     PrintedSomething = true;
475   }
476 
477   if (Third != ICK_Identity) {
478     if (PrintedSomething) {
479       OS << " -> ";
480     }
481     OS << GetImplicitConversionName(Third);
482     PrintedSomething = true;
483   }
484 
485   if (!PrintedSomething) {
486     OS << "No conversions required";
487   }
488 }
489 
490 /// DebugPrint - Print this user-defined conversion sequence to standard
491 /// error. Useful for debugging overloading issues.
492 void UserDefinedConversionSequence::DebugPrint() const {
493   raw_ostream &OS = llvm::errs();
494   if (Before.First || Before.Second || Before.Third) {
495     Before.DebugPrint();
496     OS << " -> ";
497   }
498   if (ConversionFunction)
499     OS << '\'' << *ConversionFunction << '\'';
500   else
501     OS << "aggregate initialization";
502   if (After.First || After.Second || After.Third) {
503     OS << " -> ";
504     After.DebugPrint();
505   }
506 }
507 
508 /// DebugPrint - Print this implicit conversion sequence to standard
509 /// error. Useful for debugging overloading issues.
510 void ImplicitConversionSequence::DebugPrint() const {
511   raw_ostream &OS = llvm::errs();
512   switch (ConversionKind) {
513   case StandardConversion:
514     OS << "Standard conversion: ";
515     Standard.DebugPrint();
516     break;
517   case UserDefinedConversion:
518     OS << "User-defined conversion: ";
519     UserDefined.DebugPrint();
520     break;
521   case EllipsisConversion:
522     OS << "Ellipsis conversion";
523     break;
524   case AmbiguousConversion:
525     OS << "Ambiguous conversion";
526     break;
527   case BadConversion:
528     OS << "Bad conversion";
529     break;
530   }
531 
532   OS << "\n";
533 }
534 
535 void AmbiguousConversionSequence::construct() {
536   new (&conversions()) ConversionSet();
537 }
538 
539 void AmbiguousConversionSequence::destruct() {
540   conversions().~ConversionSet();
541 }
542 
543 void
544 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
545   FromTypePtr = O.FromTypePtr;
546   ToTypePtr = O.ToTypePtr;
547   new (&conversions()) ConversionSet(O.conversions());
548 }
549 
550 namespace {
551   // Structure used by DeductionFailureInfo to store
552   // template argument information.
553   struct DFIArguments {
554     TemplateArgument FirstArg;
555     TemplateArgument SecondArg;
556   };
557   // Structure used by DeductionFailureInfo to store
558   // template parameter and template argument information.
559   struct DFIParamWithArguments : DFIArguments {
560     TemplateParameter Param;
561   };
562 }
563 
564 /// \brief Convert from Sema's representation of template deduction information
565 /// to the form used in overload-candidate information.
566 DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
567                                               Sema::TemplateDeductionResult TDK,
568                                               TemplateDeductionInfo &Info) {
569   DeductionFailureInfo Result;
570   Result.Result = static_cast<unsigned>(TDK);
571   Result.HasDiagnostic = false;
572   Result.Data = 0;
573   switch (TDK) {
574   case Sema::TDK_Success:
575   case Sema::TDK_Invalid:
576   case Sema::TDK_InstantiationDepth:
577   case Sema::TDK_TooManyArguments:
578   case Sema::TDK_TooFewArguments:
579     break;
580 
581   case Sema::TDK_Incomplete:
582   case Sema::TDK_InvalidExplicitArguments:
583     Result.Data = Info.Param.getOpaqueValue();
584     break;
585 
586   case Sema::TDK_NonDeducedMismatch: {
587     // FIXME: Should allocate from normal heap so that we can free this later.
588     DFIArguments *Saved = new (Context) DFIArguments;
589     Saved->FirstArg = Info.FirstArg;
590     Saved->SecondArg = Info.SecondArg;
591     Result.Data = Saved;
592     break;
593   }
594 
595   case Sema::TDK_Inconsistent:
596   case Sema::TDK_Underqualified: {
597     // FIXME: Should allocate from normal heap so that we can free this later.
598     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
599     Saved->Param = Info.Param;
600     Saved->FirstArg = Info.FirstArg;
601     Saved->SecondArg = Info.SecondArg;
602     Result.Data = Saved;
603     break;
604   }
605 
606   case Sema::TDK_SubstitutionFailure:
607     Result.Data = Info.take();
608     if (Info.hasSFINAEDiagnostic()) {
609       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
610           SourceLocation(), PartialDiagnostic::NullDiagnostic());
611       Info.takeSFINAEDiagnostic(*Diag);
612       Result.HasDiagnostic = true;
613     }
614     break;
615 
616   case Sema::TDK_FailedOverloadResolution:
617     Result.Data = Info.Expression;
618     break;
619 
620   case Sema::TDK_MiscellaneousDeductionFailure:
621     break;
622   }
623 
624   return Result;
625 }
626 
627 void DeductionFailureInfo::Destroy() {
628   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
629   case Sema::TDK_Success:
630   case Sema::TDK_Invalid:
631   case Sema::TDK_InstantiationDepth:
632   case Sema::TDK_Incomplete:
633   case Sema::TDK_TooManyArguments:
634   case Sema::TDK_TooFewArguments:
635   case Sema::TDK_InvalidExplicitArguments:
636   case Sema::TDK_FailedOverloadResolution:
637     break;
638 
639   case Sema::TDK_Inconsistent:
640   case Sema::TDK_Underqualified:
641   case Sema::TDK_NonDeducedMismatch:
642     // FIXME: Destroy the data?
643     Data = 0;
644     break;
645 
646   case Sema::TDK_SubstitutionFailure:
647     // FIXME: Destroy the template argument list?
648     Data = 0;
649     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
650       Diag->~PartialDiagnosticAt();
651       HasDiagnostic = false;
652     }
653     break;
654 
655   // Unhandled
656   case Sema::TDK_MiscellaneousDeductionFailure:
657     break;
658   }
659 }
660 
661 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
662   if (HasDiagnostic)
663     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
664   return 0;
665 }
666 
667 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
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_SubstitutionFailure:
675   case Sema::TDK_NonDeducedMismatch:
676   case Sema::TDK_FailedOverloadResolution:
677     return TemplateParameter();
678 
679   case Sema::TDK_Incomplete:
680   case Sema::TDK_InvalidExplicitArguments:
681     return TemplateParameter::getFromOpaqueValue(Data);
682 
683   case Sema::TDK_Inconsistent:
684   case Sema::TDK_Underqualified:
685     return static_cast<DFIParamWithArguments*>(Data)->Param;
686 
687   // Unhandled
688   case Sema::TDK_MiscellaneousDeductionFailure:
689     break;
690   }
691 
692   return TemplateParameter();
693 }
694 
695 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
696   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
697   case Sema::TDK_Success:
698   case Sema::TDK_Invalid:
699   case Sema::TDK_InstantiationDepth:
700   case Sema::TDK_TooManyArguments:
701   case Sema::TDK_TooFewArguments:
702   case Sema::TDK_Incomplete:
703   case Sema::TDK_InvalidExplicitArguments:
704   case Sema::TDK_Inconsistent:
705   case Sema::TDK_Underqualified:
706   case Sema::TDK_NonDeducedMismatch:
707   case Sema::TDK_FailedOverloadResolution:
708     return 0;
709 
710   case Sema::TDK_SubstitutionFailure:
711     return static_cast<TemplateArgumentList*>(Data);
712 
713   // Unhandled
714   case Sema::TDK_MiscellaneousDeductionFailure:
715     break;
716   }
717 
718   return 0;
719 }
720 
721 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
722   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
723   case Sema::TDK_Success:
724   case Sema::TDK_Invalid:
725   case Sema::TDK_InstantiationDepth:
726   case Sema::TDK_Incomplete:
727   case Sema::TDK_TooManyArguments:
728   case Sema::TDK_TooFewArguments:
729   case Sema::TDK_InvalidExplicitArguments:
730   case Sema::TDK_SubstitutionFailure:
731   case Sema::TDK_FailedOverloadResolution:
732     return 0;
733 
734   case Sema::TDK_Inconsistent:
735   case Sema::TDK_Underqualified:
736   case Sema::TDK_NonDeducedMismatch:
737     return &static_cast<DFIArguments*>(Data)->FirstArg;
738 
739   // Unhandled
740   case Sema::TDK_MiscellaneousDeductionFailure:
741     break;
742   }
743 
744   return 0;
745 }
746 
747 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
748   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
749   case Sema::TDK_Success:
750   case Sema::TDK_Invalid:
751   case Sema::TDK_InstantiationDepth:
752   case Sema::TDK_Incomplete:
753   case Sema::TDK_TooManyArguments:
754   case Sema::TDK_TooFewArguments:
755   case Sema::TDK_InvalidExplicitArguments:
756   case Sema::TDK_SubstitutionFailure:
757   case Sema::TDK_FailedOverloadResolution:
758     return 0;
759 
760   case Sema::TDK_Inconsistent:
761   case Sema::TDK_Underqualified:
762   case Sema::TDK_NonDeducedMismatch:
763     return &static_cast<DFIArguments*>(Data)->SecondArg;
764 
765   // Unhandled
766   case Sema::TDK_MiscellaneousDeductionFailure:
767     break;
768   }
769 
770   return 0;
771 }
772 
773 Expr *DeductionFailureInfo::getExpr() {
774   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
775         Sema::TDK_FailedOverloadResolution)
776     return static_cast<Expr*>(Data);
777 
778   return 0;
779 }
780 
781 void OverloadCandidateSet::destroyCandidates() {
782   for (iterator i = begin(), e = end(); i != e; ++i) {
783     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
784       i->Conversions[ii].~ImplicitConversionSequence();
785     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
786       i->DeductionFailure.Destroy();
787   }
788 }
789 
790 void OverloadCandidateSet::clear() {
791   destroyCandidates();
792   NumInlineSequences = 0;
793   Candidates.clear();
794   Functions.clear();
795 }
796 
797 namespace {
798   class UnbridgedCastsSet {
799     struct Entry {
800       Expr **Addr;
801       Expr *Saved;
802     };
803     SmallVector<Entry, 2> Entries;
804 
805   public:
806     void save(Sema &S, Expr *&E) {
807       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
808       Entry entry = { &E, E };
809       Entries.push_back(entry);
810       E = S.stripARCUnbridgedCast(E);
811     }
812 
813     void restore() {
814       for (SmallVectorImpl<Entry>::iterator
815              i = Entries.begin(), e = Entries.end(); i != e; ++i)
816         *i->Addr = i->Saved;
817     }
818   };
819 }
820 
821 /// checkPlaceholderForOverload - Do any interesting placeholder-like
822 /// preprocessing on the given expression.
823 ///
824 /// \param unbridgedCasts a collection to which to add unbridged casts;
825 ///   without this, they will be immediately diagnosed as errors
826 ///
827 /// Return true on unrecoverable error.
828 static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
829                                         UnbridgedCastsSet *unbridgedCasts = 0) {
830   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
831     // We can't handle overloaded expressions here because overload
832     // resolution might reasonably tweak them.
833     if (placeholder->getKind() == BuiltinType::Overload) return false;
834 
835     // If the context potentially accepts unbridged ARC casts, strip
836     // the unbridged cast and add it to the collection for later restoration.
837     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
838         unbridgedCasts) {
839       unbridgedCasts->save(S, E);
840       return false;
841     }
842 
843     // Go ahead and check everything else.
844     ExprResult result = S.CheckPlaceholderExpr(E);
845     if (result.isInvalid())
846       return true;
847 
848     E = result.take();
849     return false;
850   }
851 
852   // Nothing to do.
853   return false;
854 }
855 
856 /// checkArgPlaceholdersForOverload - Check a set of call operands for
857 /// placeholders.
858 static bool checkArgPlaceholdersForOverload(Sema &S,
859                                             MultiExprArg Args,
860                                             UnbridgedCastsSet &unbridged) {
861   for (unsigned i = 0, e = Args.size(); i != e; ++i)
862     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
863       return true;
864 
865   return false;
866 }
867 
868 // IsOverload - Determine whether the given New declaration is an
869 // overload of the declarations in Old. This routine returns false if
870 // New and Old cannot be overloaded, e.g., if New has the same
871 // signature as some function in Old (C++ 1.3.10) or if the Old
872 // declarations aren't functions (or function templates) at all. When
873 // it does return false, MatchedDecl will point to the decl that New
874 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
875 // top of the underlying declaration.
876 //
877 // Example: Given the following input:
878 //
879 //   void f(int, float); // #1
880 //   void f(int, int); // #2
881 //   int f(int, int); // #3
882 //
883 // When we process #1, there is no previous declaration of "f",
884 // so IsOverload will not be used.
885 //
886 // When we process #2, Old contains only the FunctionDecl for #1.  By
887 // comparing the parameter types, we see that #1 and #2 are overloaded
888 // (since they have different signatures), so this routine returns
889 // false; MatchedDecl is unchanged.
890 //
891 // When we process #3, Old is an overload set containing #1 and #2. We
892 // compare the signatures of #3 to #1 (they're overloaded, so we do
893 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
894 // identical (return types of functions are not part of the
895 // signature), IsOverload returns false and MatchedDecl will be set to
896 // point to the FunctionDecl for #2.
897 //
898 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
899 // into a class by a using declaration.  The rules for whether to hide
900 // shadow declarations ignore some properties which otherwise figure
901 // into a function template's signature.
902 Sema::OverloadKind
903 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
904                     NamedDecl *&Match, bool NewIsUsingDecl) {
905   for (LookupResult::iterator I = Old.begin(), E = Old.end();
906          I != E; ++I) {
907     NamedDecl *OldD = *I;
908 
909     bool OldIsUsingDecl = false;
910     if (isa<UsingShadowDecl>(OldD)) {
911       OldIsUsingDecl = true;
912 
913       // We can always introduce two using declarations into the same
914       // context, even if they have identical signatures.
915       if (NewIsUsingDecl) continue;
916 
917       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
918     }
919 
920     // If either declaration was introduced by a using declaration,
921     // we'll need to use slightly different rules for matching.
922     // Essentially, these rules are the normal rules, except that
923     // function templates hide function templates with different
924     // return types or template parameter lists.
925     bool UseMemberUsingDeclRules =
926       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
927       !New->getFriendObjectKind();
928 
929     if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
930       if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
931         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
932           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
933           continue;
934         }
935 
936         Match = *I;
937         return Ovl_Match;
938       }
939     } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
940       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
941         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
942           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
943           continue;
944         }
945 
946         if (!shouldLinkPossiblyHiddenDecl(*I, New))
947           continue;
948 
949         Match = *I;
950         return Ovl_Match;
951       }
952     } else if (isa<UsingDecl>(OldD)) {
953       // We can overload with these, which can show up when doing
954       // redeclaration checks for UsingDecls.
955       assert(Old.getLookupKind() == LookupUsingDeclName);
956     } else if (isa<TagDecl>(OldD)) {
957       // We can always overload with tags by hiding them.
958     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
959       // Optimistically assume that an unresolved using decl will
960       // overload; if it doesn't, we'll have to diagnose during
961       // template instantiation.
962     } else {
963       // (C++ 13p1):
964       //   Only function declarations can be overloaded; object and type
965       //   declarations cannot be overloaded.
966       Match = *I;
967       return Ovl_NonFunction;
968     }
969   }
970 
971   return Ovl_Overload;
972 }
973 
974 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
975                       bool UseUsingDeclRules) {
976   // C++ [basic.start.main]p2: This function shall not be overloaded.
977   if (New->isMain())
978     return false;
979 
980   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
981   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
982 
983   // C++ [temp.fct]p2:
984   //   A function template can be overloaded with other function templates
985   //   and with normal (non-template) functions.
986   if ((OldTemplate == 0) != (NewTemplate == 0))
987     return true;
988 
989   // Is the function New an overload of the function Old?
990   QualType OldQType = Context.getCanonicalType(Old->getType());
991   QualType NewQType = Context.getCanonicalType(New->getType());
992 
993   // Compare the signatures (C++ 1.3.10) of the two functions to
994   // determine whether they are overloads. If we find any mismatch
995   // in the signature, they are overloads.
996 
997   // If either of these functions is a K&R-style function (no
998   // prototype), then we consider them to have matching signatures.
999   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1000       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1001     return false;
1002 
1003   const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1004   const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
1005 
1006   // The signature of a function includes the types of its
1007   // parameters (C++ 1.3.10), which includes the presence or absence
1008   // of the ellipsis; see C++ DR 357).
1009   if (OldQType != NewQType &&
1010       (OldType->getNumArgs() != NewType->getNumArgs() ||
1011        OldType->isVariadic() != NewType->isVariadic() ||
1012        !FunctionArgTypesAreEqual(OldType, NewType)))
1013     return true;
1014 
1015   // C++ [temp.over.link]p4:
1016   //   The signature of a function template consists of its function
1017   //   signature, its return type and its template parameter list. The names
1018   //   of the template parameters are significant only for establishing the
1019   //   relationship between the template parameters and the rest of the
1020   //   signature.
1021   //
1022   // We check the return type and template parameter lists for function
1023   // templates first; the remaining checks follow.
1024   //
1025   // However, we don't consider either of these when deciding whether
1026   // a member introduced by a shadow declaration is hidden.
1027   if (!UseUsingDeclRules && NewTemplate &&
1028       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1029                                        OldTemplate->getTemplateParameters(),
1030                                        false, TPL_TemplateMatch) ||
1031        OldType->getResultType() != NewType->getResultType()))
1032     return true;
1033 
1034   // If the function is a class member, its signature includes the
1035   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1036   //
1037   // As part of this, also check whether one of the member functions
1038   // is static, in which case they are not overloads (C++
1039   // 13.1p2). While not part of the definition of the signature,
1040   // this check is important to determine whether these functions
1041   // can be overloaded.
1042   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1043   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1044   if (OldMethod && NewMethod &&
1045       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1046     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1047       if (!UseUsingDeclRules &&
1048           (OldMethod->getRefQualifier() == RQ_None ||
1049            NewMethod->getRefQualifier() == RQ_None)) {
1050         // C++0x [over.load]p2:
1051         //   - Member function declarations with the same name and the same
1052         //     parameter-type-list as well as member function template
1053         //     declarations with the same name, the same parameter-type-list, and
1054         //     the same template parameter lists cannot be overloaded if any of
1055         //     them, but not all, have a ref-qualifier (8.3.5).
1056         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1057           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1058         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1059       }
1060       return true;
1061     }
1062 
1063     // We may not have applied the implicit const for a constexpr member
1064     // function yet (because we haven't yet resolved whether this is a static
1065     // or non-static member function). Add it now, on the assumption that this
1066     // is a redeclaration of OldMethod.
1067     unsigned NewQuals = NewMethod->getTypeQualifiers();
1068     if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
1069         !isa<CXXConstructorDecl>(NewMethod))
1070       NewQuals |= Qualifiers::Const;
1071     if (OldMethod->getTypeQualifiers() != NewQuals)
1072       return true;
1073   }
1074 
1075   // The signatures match; this is not an overload.
1076   return false;
1077 }
1078 
1079 /// \brief Checks availability of the function depending on the current
1080 /// function context. Inside an unavailable function, unavailability is ignored.
1081 ///
1082 /// \returns true if \arg FD is unavailable and current context is inside
1083 /// an available function, false otherwise.
1084 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1085   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1086 }
1087 
1088 /// \brief Tries a user-defined conversion from From to ToType.
1089 ///
1090 /// Produces an implicit conversion sequence for when a standard conversion
1091 /// is not an option. See TryImplicitConversion for more information.
1092 static ImplicitConversionSequence
1093 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1094                          bool SuppressUserConversions,
1095                          bool AllowExplicit,
1096                          bool InOverloadResolution,
1097                          bool CStyle,
1098                          bool AllowObjCWritebackConversion) {
1099   ImplicitConversionSequence ICS;
1100 
1101   if (SuppressUserConversions) {
1102     // We're not in the case above, so there is no conversion that
1103     // we can perform.
1104     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1105     return ICS;
1106   }
1107 
1108   // Attempt user-defined conversion.
1109   OverloadCandidateSet Conversions(From->getExprLoc());
1110   OverloadingResult UserDefResult
1111     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1112                               AllowExplicit);
1113 
1114   if (UserDefResult == OR_Success) {
1115     ICS.setUserDefined();
1116     // C++ [over.ics.user]p4:
1117     //   A conversion of an expression of class type to the same class
1118     //   type is given Exact Match rank, and a conversion of an
1119     //   expression of class type to a base class of that type is
1120     //   given Conversion rank, in spite of the fact that a copy
1121     //   constructor (i.e., a user-defined conversion function) is
1122     //   called for those cases.
1123     if (CXXConstructorDecl *Constructor
1124           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1125       QualType FromCanon
1126         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1127       QualType ToCanon
1128         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1129       if (Constructor->isCopyConstructor() &&
1130           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1131         // Turn this into a "standard" conversion sequence, so that it
1132         // gets ranked with standard conversion sequences.
1133         ICS.setStandard();
1134         ICS.Standard.setAsIdentityConversion();
1135         ICS.Standard.setFromType(From->getType());
1136         ICS.Standard.setAllToTypes(ToType);
1137         ICS.Standard.CopyConstructor = Constructor;
1138         if (ToCanon != FromCanon)
1139           ICS.Standard.Second = ICK_Derived_To_Base;
1140       }
1141     }
1142 
1143     // C++ [over.best.ics]p4:
1144     //   However, when considering the argument of a user-defined
1145     //   conversion function that is a candidate by 13.3.1.3 when
1146     //   invoked for the copying of the temporary in the second step
1147     //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1148     //   13.3.1.6 in all cases, only standard conversion sequences and
1149     //   ellipsis conversion sequences are allowed.
1150     if (SuppressUserConversions && ICS.isUserDefined()) {
1151       ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1152     }
1153   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1154     ICS.setAmbiguous();
1155     ICS.Ambiguous.setFromType(From->getType());
1156     ICS.Ambiguous.setToType(ToType);
1157     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1158          Cand != Conversions.end(); ++Cand)
1159       if (Cand->Viable)
1160         ICS.Ambiguous.addConversion(Cand->Function);
1161   } else {
1162     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1163   }
1164 
1165   return ICS;
1166 }
1167 
1168 /// TryImplicitConversion - Attempt to perform an implicit conversion
1169 /// from the given expression (Expr) to the given type (ToType). This
1170 /// function returns an implicit conversion sequence that can be used
1171 /// to perform the initialization. Given
1172 ///
1173 ///   void f(float f);
1174 ///   void g(int i) { f(i); }
1175 ///
1176 /// this routine would produce an implicit conversion sequence to
1177 /// describe the initialization of f from i, which will be a standard
1178 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1179 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1180 //
1181 /// Note that this routine only determines how the conversion can be
1182 /// performed; it does not actually perform the conversion. As such,
1183 /// it will not produce any diagnostics if no conversion is available,
1184 /// but will instead return an implicit conversion sequence of kind
1185 /// "BadConversion".
1186 ///
1187 /// If @p SuppressUserConversions, then user-defined conversions are
1188 /// not permitted.
1189 /// If @p AllowExplicit, then explicit user-defined conversions are
1190 /// permitted.
1191 ///
1192 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1193 /// writeback conversion, which allows __autoreleasing id* parameters to
1194 /// be initialized with __strong id* or __weak id* arguments.
1195 static ImplicitConversionSequence
1196 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1197                       bool SuppressUserConversions,
1198                       bool AllowExplicit,
1199                       bool InOverloadResolution,
1200                       bool CStyle,
1201                       bool AllowObjCWritebackConversion) {
1202   ImplicitConversionSequence ICS;
1203   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1204                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1205     ICS.setStandard();
1206     return ICS;
1207   }
1208 
1209   if (!S.getLangOpts().CPlusPlus) {
1210     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1211     return ICS;
1212   }
1213 
1214   // C++ [over.ics.user]p4:
1215   //   A conversion of an expression of class type to the same class
1216   //   type is given Exact Match rank, and a conversion of an
1217   //   expression of class type to a base class of that type is
1218   //   given Conversion rank, in spite of the fact that a copy/move
1219   //   constructor (i.e., a user-defined conversion function) is
1220   //   called for those cases.
1221   QualType FromType = From->getType();
1222   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1223       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1224        S.IsDerivedFrom(FromType, ToType))) {
1225     ICS.setStandard();
1226     ICS.Standard.setAsIdentityConversion();
1227     ICS.Standard.setFromType(FromType);
1228     ICS.Standard.setAllToTypes(ToType);
1229 
1230     // We don't actually check at this point whether there is a valid
1231     // copy/move constructor, since overloading just assumes that it
1232     // exists. When we actually perform initialization, we'll find the
1233     // appropriate constructor to copy the returned object, if needed.
1234     ICS.Standard.CopyConstructor = 0;
1235 
1236     // Determine whether this is considered a derived-to-base conversion.
1237     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1238       ICS.Standard.Second = ICK_Derived_To_Base;
1239 
1240     return ICS;
1241   }
1242 
1243   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1244                                   AllowExplicit, InOverloadResolution, CStyle,
1245                                   AllowObjCWritebackConversion);
1246 }
1247 
1248 ImplicitConversionSequence
1249 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1250                             bool SuppressUserConversions,
1251                             bool AllowExplicit,
1252                             bool InOverloadResolution,
1253                             bool CStyle,
1254                             bool AllowObjCWritebackConversion) {
1255   return clang::TryImplicitConversion(*this, From, ToType,
1256                                       SuppressUserConversions, AllowExplicit,
1257                                       InOverloadResolution, CStyle,
1258                                       AllowObjCWritebackConversion);
1259 }
1260 
1261 /// PerformImplicitConversion - Perform an implicit conversion of the
1262 /// expression From to the type ToType. Returns the
1263 /// converted expression. Flavor is the kind of conversion we're
1264 /// performing, used in the error message. If @p AllowExplicit,
1265 /// explicit user-defined conversions are permitted.
1266 ExprResult
1267 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1268                                 AssignmentAction Action, bool AllowExplicit) {
1269   ImplicitConversionSequence ICS;
1270   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1271 }
1272 
1273 ExprResult
1274 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1275                                 AssignmentAction Action, bool AllowExplicit,
1276                                 ImplicitConversionSequence& ICS) {
1277   if (checkPlaceholderForOverload(*this, From))
1278     return ExprError();
1279 
1280   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1281   bool AllowObjCWritebackConversion
1282     = getLangOpts().ObjCAutoRefCount &&
1283       (Action == AA_Passing || Action == AA_Sending);
1284 
1285   ICS = clang::TryImplicitConversion(*this, From, ToType,
1286                                      /*SuppressUserConversions=*/false,
1287                                      AllowExplicit,
1288                                      /*InOverloadResolution=*/false,
1289                                      /*CStyle=*/false,
1290                                      AllowObjCWritebackConversion);
1291   return PerformImplicitConversion(From, ToType, ICS, Action);
1292 }
1293 
1294 /// \brief Determine whether the conversion from FromType to ToType is a valid
1295 /// conversion that strips "noreturn" off the nested function type.
1296 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1297                                 QualType &ResultTy) {
1298   if (Context.hasSameUnqualifiedType(FromType, ToType))
1299     return false;
1300 
1301   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1302   // where F adds one of the following at most once:
1303   //   - a pointer
1304   //   - a member pointer
1305   //   - a block pointer
1306   CanQualType CanTo = Context.getCanonicalType(ToType);
1307   CanQualType CanFrom = Context.getCanonicalType(FromType);
1308   Type::TypeClass TyClass = CanTo->getTypeClass();
1309   if (TyClass != CanFrom->getTypeClass()) return false;
1310   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1311     if (TyClass == Type::Pointer) {
1312       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1313       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1314     } else if (TyClass == Type::BlockPointer) {
1315       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1316       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1317     } else if (TyClass == Type::MemberPointer) {
1318       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1319       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1320     } else {
1321       return false;
1322     }
1323 
1324     TyClass = CanTo->getTypeClass();
1325     if (TyClass != CanFrom->getTypeClass()) return false;
1326     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1327       return false;
1328   }
1329 
1330   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1331   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1332   if (!EInfo.getNoReturn()) return false;
1333 
1334   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1335   assert(QualType(FromFn, 0).isCanonical());
1336   if (QualType(FromFn, 0) != CanTo) return false;
1337 
1338   ResultTy = ToType;
1339   return true;
1340 }
1341 
1342 /// \brief Determine whether the conversion from FromType to ToType is a valid
1343 /// vector conversion.
1344 ///
1345 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1346 /// conversion.
1347 static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1348                                QualType ToType, ImplicitConversionKind &ICK) {
1349   // We need at least one of these types to be a vector type to have a vector
1350   // conversion.
1351   if (!ToType->isVectorType() && !FromType->isVectorType())
1352     return false;
1353 
1354   // Identical types require no conversions.
1355   if (Context.hasSameUnqualifiedType(FromType, ToType))
1356     return false;
1357 
1358   // There are no conversions between extended vector types, only identity.
1359   if (ToType->isExtVectorType()) {
1360     // There are no conversions between extended vector types other than the
1361     // identity conversion.
1362     if (FromType->isExtVectorType())
1363       return false;
1364 
1365     // Vector splat from any arithmetic type to a vector.
1366     if (FromType->isArithmeticType()) {
1367       ICK = ICK_Vector_Splat;
1368       return true;
1369     }
1370   }
1371 
1372   // We can perform the conversion between vector types in the following cases:
1373   // 1)vector types are equivalent AltiVec and GCC vector types
1374   // 2)lax vector conversions are permitted and the vector types are of the
1375   //   same size
1376   if (ToType->isVectorType() && FromType->isVectorType()) {
1377     if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1378         (Context.getLangOpts().LaxVectorConversions &&
1379          (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1380       ICK = ICK_Vector_Conversion;
1381       return true;
1382     }
1383   }
1384 
1385   return false;
1386 }
1387 
1388 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1389                                 bool InOverloadResolution,
1390                                 StandardConversionSequence &SCS,
1391                                 bool CStyle);
1392 
1393 /// IsStandardConversion - Determines whether there is a standard
1394 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1395 /// expression From to the type ToType. Standard conversion sequences
1396 /// only consider non-class types; for conversions that involve class
1397 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1398 /// contain the standard conversion sequence required to perform this
1399 /// conversion and this routine will return true. Otherwise, this
1400 /// routine will return false and the value of SCS is unspecified.
1401 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1402                                  bool InOverloadResolution,
1403                                  StandardConversionSequence &SCS,
1404                                  bool CStyle,
1405                                  bool AllowObjCWritebackConversion) {
1406   QualType FromType = From->getType();
1407 
1408   // Standard conversions (C++ [conv])
1409   SCS.setAsIdentityConversion();
1410   SCS.DeprecatedStringLiteralToCharPtr = false;
1411   SCS.IncompatibleObjC = false;
1412   SCS.setFromType(FromType);
1413   SCS.CopyConstructor = 0;
1414 
1415   // There are no standard conversions for class types in C++, so
1416   // abort early. When overloading in C, however, we do permit
1417   if (FromType->isRecordType() || ToType->isRecordType()) {
1418     if (S.getLangOpts().CPlusPlus)
1419       return false;
1420 
1421     // When we're overloading in C, we allow, as standard conversions,
1422   }
1423 
1424   // The first conversion can be an lvalue-to-rvalue conversion,
1425   // array-to-pointer conversion, or function-to-pointer conversion
1426   // (C++ 4p1).
1427 
1428   if (FromType == S.Context.OverloadTy) {
1429     DeclAccessPair AccessPair;
1430     if (FunctionDecl *Fn
1431           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1432                                                  AccessPair)) {
1433       // We were able to resolve the address of the overloaded function,
1434       // so we can convert to the type of that function.
1435       FromType = Fn->getType();
1436 
1437       // we can sometimes resolve &foo<int> regardless of ToType, so check
1438       // if the type matches (identity) or we are converting to bool
1439       if (!S.Context.hasSameUnqualifiedType(
1440                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1441         QualType resultTy;
1442         // if the function type matches except for [[noreturn]], it's ok
1443         if (!S.IsNoReturnConversion(FromType,
1444               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1445           // otherwise, only a boolean conversion is standard
1446           if (!ToType->isBooleanType())
1447             return false;
1448       }
1449 
1450       // Check if the "from" expression is taking the address of an overloaded
1451       // function and recompute the FromType accordingly. Take advantage of the
1452       // fact that non-static member functions *must* have such an address-of
1453       // expression.
1454       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1455       if (Method && !Method->isStatic()) {
1456         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1457                "Non-unary operator on non-static member address");
1458         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1459                == UO_AddrOf &&
1460                "Non-address-of operator on non-static member address");
1461         const Type *ClassType
1462           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1463         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1464       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1465         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1466                UO_AddrOf &&
1467                "Non-address-of operator for overloaded function expression");
1468         FromType = S.Context.getPointerType(FromType);
1469       }
1470 
1471       // Check that we've computed the proper type after overload resolution.
1472       assert(S.Context.hasSameType(
1473         FromType,
1474         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1475     } else {
1476       return false;
1477     }
1478   }
1479   // Lvalue-to-rvalue conversion (C++11 4.1):
1480   //   A glvalue (3.10) of a non-function, non-array type T can
1481   //   be converted to a prvalue.
1482   bool argIsLValue = From->isGLValue();
1483   if (argIsLValue &&
1484       !FromType->isFunctionType() && !FromType->isArrayType() &&
1485       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1486     SCS.First = ICK_Lvalue_To_Rvalue;
1487 
1488     // C11 6.3.2.1p2:
1489     //   ... if the lvalue has atomic type, the value has the non-atomic version
1490     //   of the type of the lvalue ...
1491     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1492       FromType = Atomic->getValueType();
1493 
1494     // If T is a non-class type, the type of the rvalue is the
1495     // cv-unqualified version of T. Otherwise, the type of the rvalue
1496     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1497     // just strip the qualifiers because they don't matter.
1498     FromType = FromType.getUnqualifiedType();
1499   } else if (FromType->isArrayType()) {
1500     // Array-to-pointer conversion (C++ 4.2)
1501     SCS.First = ICK_Array_To_Pointer;
1502 
1503     // An lvalue or rvalue of type "array of N T" or "array of unknown
1504     // bound of T" can be converted to an rvalue of type "pointer to
1505     // T" (C++ 4.2p1).
1506     FromType = S.Context.getArrayDecayedType(FromType);
1507 
1508     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1509       // This conversion is deprecated. (C++ D.4).
1510       SCS.DeprecatedStringLiteralToCharPtr = true;
1511 
1512       // For the purpose of ranking in overload resolution
1513       // (13.3.3.1.1), this conversion is considered an
1514       // array-to-pointer conversion followed by a qualification
1515       // conversion (4.4). (C++ 4.2p2)
1516       SCS.Second = ICK_Identity;
1517       SCS.Third = ICK_Qualification;
1518       SCS.QualificationIncludesObjCLifetime = false;
1519       SCS.setAllToTypes(FromType);
1520       return true;
1521     }
1522   } else if (FromType->isFunctionType() && argIsLValue) {
1523     // Function-to-pointer conversion (C++ 4.3).
1524     SCS.First = ICK_Function_To_Pointer;
1525 
1526     // An lvalue of function type T can be converted to an rvalue of
1527     // type "pointer to T." The result is a pointer to the
1528     // function. (C++ 4.3p1).
1529     FromType = S.Context.getPointerType(FromType);
1530   } else {
1531     // We don't require any conversions for the first step.
1532     SCS.First = ICK_Identity;
1533   }
1534   SCS.setToType(0, FromType);
1535 
1536   // The second conversion can be an integral promotion, floating
1537   // point promotion, integral conversion, floating point conversion,
1538   // floating-integral conversion, pointer conversion,
1539   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1540   // For overloading in C, this can also be a "compatible-type"
1541   // conversion.
1542   bool IncompatibleObjC = false;
1543   ImplicitConversionKind SecondICK = ICK_Identity;
1544   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1545     // The unqualified versions of the types are the same: there's no
1546     // conversion to do.
1547     SCS.Second = ICK_Identity;
1548   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1549     // Integral promotion (C++ 4.5).
1550     SCS.Second = ICK_Integral_Promotion;
1551     FromType = ToType.getUnqualifiedType();
1552   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1553     // Floating point promotion (C++ 4.6).
1554     SCS.Second = ICK_Floating_Promotion;
1555     FromType = ToType.getUnqualifiedType();
1556   } else if (S.IsComplexPromotion(FromType, ToType)) {
1557     // Complex promotion (Clang extension)
1558     SCS.Second = ICK_Complex_Promotion;
1559     FromType = ToType.getUnqualifiedType();
1560   } else if (ToType->isBooleanType() &&
1561              (FromType->isArithmeticType() ||
1562               FromType->isAnyPointerType() ||
1563               FromType->isBlockPointerType() ||
1564               FromType->isMemberPointerType() ||
1565               FromType->isNullPtrType())) {
1566     // Boolean conversions (C++ 4.12).
1567     SCS.Second = ICK_Boolean_Conversion;
1568     FromType = S.Context.BoolTy;
1569   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1570              ToType->isIntegralType(S.Context)) {
1571     // Integral conversions (C++ 4.7).
1572     SCS.Second = ICK_Integral_Conversion;
1573     FromType = ToType.getUnqualifiedType();
1574   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1575     // Complex conversions (C99 6.3.1.6)
1576     SCS.Second = ICK_Complex_Conversion;
1577     FromType = ToType.getUnqualifiedType();
1578   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1579              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1580     // Complex-real conversions (C99 6.3.1.7)
1581     SCS.Second = ICK_Complex_Real;
1582     FromType = ToType.getUnqualifiedType();
1583   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1584     // Floating point conversions (C++ 4.8).
1585     SCS.Second = ICK_Floating_Conversion;
1586     FromType = ToType.getUnqualifiedType();
1587   } else if ((FromType->isRealFloatingType() &&
1588               ToType->isIntegralType(S.Context)) ||
1589              (FromType->isIntegralOrUnscopedEnumerationType() &&
1590               ToType->isRealFloatingType())) {
1591     // Floating-integral conversions (C++ 4.9).
1592     SCS.Second = ICK_Floating_Integral;
1593     FromType = ToType.getUnqualifiedType();
1594   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1595     SCS.Second = ICK_Block_Pointer_Conversion;
1596   } else if (AllowObjCWritebackConversion &&
1597              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1598     SCS.Second = ICK_Writeback_Conversion;
1599   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1600                                    FromType, IncompatibleObjC)) {
1601     // Pointer conversions (C++ 4.10).
1602     SCS.Second = ICK_Pointer_Conversion;
1603     SCS.IncompatibleObjC = IncompatibleObjC;
1604     FromType = FromType.getUnqualifiedType();
1605   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1606                                          InOverloadResolution, FromType)) {
1607     // Pointer to member conversions (4.11).
1608     SCS.Second = ICK_Pointer_Member;
1609   } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1610     SCS.Second = SecondICK;
1611     FromType = ToType.getUnqualifiedType();
1612   } else if (!S.getLangOpts().CPlusPlus &&
1613              S.Context.typesAreCompatible(ToType, FromType)) {
1614     // Compatible conversions (Clang extension for C function overloading)
1615     SCS.Second = ICK_Compatible_Conversion;
1616     FromType = ToType.getUnqualifiedType();
1617   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1618     // Treat a conversion that strips "noreturn" as an identity conversion.
1619     SCS.Second = ICK_NoReturn_Adjustment;
1620   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1621                                              InOverloadResolution,
1622                                              SCS, CStyle)) {
1623     SCS.Second = ICK_TransparentUnionConversion;
1624     FromType = ToType;
1625   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1626                                  CStyle)) {
1627     // tryAtomicConversion has updated the standard conversion sequence
1628     // appropriately.
1629     return true;
1630   } else if (ToType->isEventT() &&
1631              From->isIntegerConstantExpr(S.getASTContext()) &&
1632              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1633     SCS.Second = ICK_Zero_Event_Conversion;
1634     FromType = ToType;
1635   } else {
1636     // No second conversion required.
1637     SCS.Second = ICK_Identity;
1638   }
1639   SCS.setToType(1, FromType);
1640 
1641   QualType CanonFrom;
1642   QualType CanonTo;
1643   // The third conversion can be a qualification conversion (C++ 4p1).
1644   bool ObjCLifetimeConversion;
1645   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1646                                   ObjCLifetimeConversion)) {
1647     SCS.Third = ICK_Qualification;
1648     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1649     FromType = ToType;
1650     CanonFrom = S.Context.getCanonicalType(FromType);
1651     CanonTo = S.Context.getCanonicalType(ToType);
1652   } else {
1653     // No conversion required
1654     SCS.Third = ICK_Identity;
1655 
1656     // C++ [over.best.ics]p6:
1657     //   [...] Any difference in top-level cv-qualification is
1658     //   subsumed by the initialization itself and does not constitute
1659     //   a conversion. [...]
1660     CanonFrom = S.Context.getCanonicalType(FromType);
1661     CanonTo = S.Context.getCanonicalType(ToType);
1662     if (CanonFrom.getLocalUnqualifiedType()
1663                                        == CanonTo.getLocalUnqualifiedType() &&
1664         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1665       FromType = ToType;
1666       CanonFrom = CanonTo;
1667     }
1668   }
1669   SCS.setToType(2, FromType);
1670 
1671   // If we have not converted the argument type to the parameter type,
1672   // this is a bad conversion sequence.
1673   if (CanonFrom != CanonTo)
1674     return false;
1675 
1676   return true;
1677 }
1678 
1679 static bool
1680 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1681                                      QualType &ToType,
1682                                      bool InOverloadResolution,
1683                                      StandardConversionSequence &SCS,
1684                                      bool CStyle) {
1685 
1686   const RecordType *UT = ToType->getAsUnionType();
1687   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1688     return false;
1689   // The field to initialize within the transparent union.
1690   RecordDecl *UD = UT->getDecl();
1691   // It's compatible if the expression matches any of the fields.
1692   for (RecordDecl::field_iterator it = UD->field_begin(),
1693        itend = UD->field_end();
1694        it != itend; ++it) {
1695     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1696                              CStyle, /*ObjCWritebackConversion=*/false)) {
1697       ToType = it->getType();
1698       return true;
1699     }
1700   }
1701   return false;
1702 }
1703 
1704 /// IsIntegralPromotion - Determines whether the conversion from the
1705 /// expression From (whose potentially-adjusted type is FromType) to
1706 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1707 /// sets PromotedType to the promoted type.
1708 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1709   const BuiltinType *To = ToType->getAs<BuiltinType>();
1710   // All integers are built-in.
1711   if (!To) {
1712     return false;
1713   }
1714 
1715   // An rvalue of type char, signed char, unsigned char, short int, or
1716   // unsigned short int can be converted to an rvalue of type int if
1717   // int can represent all the values of the source type; otherwise,
1718   // the source rvalue can be converted to an rvalue of type unsigned
1719   // int (C++ 4.5p1).
1720   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1721       !FromType->isEnumeralType()) {
1722     if (// We can promote any signed, promotable integer type to an int
1723         (FromType->isSignedIntegerType() ||
1724          // We can promote any unsigned integer type whose size is
1725          // less than int to an int.
1726          (!FromType->isSignedIntegerType() &&
1727           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1728       return To->getKind() == BuiltinType::Int;
1729     }
1730 
1731     return To->getKind() == BuiltinType::UInt;
1732   }
1733 
1734   // C++11 [conv.prom]p3:
1735   //   A prvalue of an unscoped enumeration type whose underlying type is not
1736   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1737   //   following types that can represent all the values of the enumeration
1738   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1739   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1740   //   long long int. If none of the types in that list can represent all the
1741   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1742   //   type can be converted to an rvalue a prvalue of the extended integer type
1743   //   with lowest integer conversion rank (4.13) greater than the rank of long
1744   //   long in which all the values of the enumeration can be represented. If
1745   //   there are two such extended types, the signed one is chosen.
1746   // C++11 [conv.prom]p4:
1747   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1748   //   can be converted to a prvalue of its underlying type. Moreover, if
1749   //   integral promotion can be applied to its underlying type, a prvalue of an
1750   //   unscoped enumeration type whose underlying type is fixed can also be
1751   //   converted to a prvalue of the promoted underlying type.
1752   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1753     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1754     // provided for a scoped enumeration.
1755     if (FromEnumType->getDecl()->isScoped())
1756       return false;
1757 
1758     // We can perform an integral promotion to the underlying type of the enum,
1759     // even if that's not the promoted type.
1760     if (FromEnumType->getDecl()->isFixed()) {
1761       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1762       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1763              IsIntegralPromotion(From, Underlying, ToType);
1764     }
1765 
1766     // We have already pre-calculated the promotion type, so this is trivial.
1767     if (ToType->isIntegerType() &&
1768         !RequireCompleteType(From->getLocStart(), FromType, 0))
1769       return Context.hasSameUnqualifiedType(ToType,
1770                                 FromEnumType->getDecl()->getPromotionType());
1771   }
1772 
1773   // C++0x [conv.prom]p2:
1774   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1775   //   to an rvalue a prvalue of the first of the following types that can
1776   //   represent all the values of its underlying type: int, unsigned int,
1777   //   long int, unsigned long int, long long int, or unsigned long long int.
1778   //   If none of the types in that list can represent all the values of its
1779   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1780   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1781   //   type.
1782   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1783       ToType->isIntegerType()) {
1784     // Determine whether the type we're converting from is signed or
1785     // unsigned.
1786     bool FromIsSigned = FromType->isSignedIntegerType();
1787     uint64_t FromSize = Context.getTypeSize(FromType);
1788 
1789     // The types we'll try to promote to, in the appropriate
1790     // order. Try each of these types.
1791     QualType PromoteTypes[6] = {
1792       Context.IntTy, Context.UnsignedIntTy,
1793       Context.LongTy, Context.UnsignedLongTy ,
1794       Context.LongLongTy, Context.UnsignedLongLongTy
1795     };
1796     for (int Idx = 0; Idx < 6; ++Idx) {
1797       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1798       if (FromSize < ToSize ||
1799           (FromSize == ToSize &&
1800            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1801         // We found the type that we can promote to. If this is the
1802         // type we wanted, we have a promotion. Otherwise, no
1803         // promotion.
1804         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1805       }
1806     }
1807   }
1808 
1809   // An rvalue for an integral bit-field (9.6) can be converted to an
1810   // rvalue of type int if int can represent all the values of the
1811   // bit-field; otherwise, it can be converted to unsigned int if
1812   // unsigned int can represent all the values of the bit-field. If
1813   // the bit-field is larger yet, no integral promotion applies to
1814   // it. If the bit-field has an enumerated type, it is treated as any
1815   // other value of that type for promotion purposes (C++ 4.5p3).
1816   // FIXME: We should delay checking of bit-fields until we actually perform the
1817   // conversion.
1818   using llvm::APSInt;
1819   if (From)
1820     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1821       APSInt BitWidth;
1822       if (FromType->isIntegralType(Context) &&
1823           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1824         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1825         ToSize = Context.getTypeSize(ToType);
1826 
1827         // Are we promoting to an int from a bitfield that fits in an int?
1828         if (BitWidth < ToSize ||
1829             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1830           return To->getKind() == BuiltinType::Int;
1831         }
1832 
1833         // Are we promoting to an unsigned int from an unsigned bitfield
1834         // that fits into an unsigned int?
1835         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1836           return To->getKind() == BuiltinType::UInt;
1837         }
1838 
1839         return false;
1840       }
1841     }
1842 
1843   // An rvalue of type bool can be converted to an rvalue of type int,
1844   // with false becoming zero and true becoming one (C++ 4.5p4).
1845   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1846     return true;
1847   }
1848 
1849   return false;
1850 }
1851 
1852 /// IsFloatingPointPromotion - Determines whether the conversion from
1853 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1854 /// returns true and sets PromotedType to the promoted type.
1855 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1856   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1857     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1858       /// An rvalue of type float can be converted to an rvalue of type
1859       /// double. (C++ 4.6p1).
1860       if (FromBuiltin->getKind() == BuiltinType::Float &&
1861           ToBuiltin->getKind() == BuiltinType::Double)
1862         return true;
1863 
1864       // C99 6.3.1.5p1:
1865       //   When a float is promoted to double or long double, or a
1866       //   double is promoted to long double [...].
1867       if (!getLangOpts().CPlusPlus &&
1868           (FromBuiltin->getKind() == BuiltinType::Float ||
1869            FromBuiltin->getKind() == BuiltinType::Double) &&
1870           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1871         return true;
1872 
1873       // Half can be promoted to float.
1874       if (!getLangOpts().NativeHalfType &&
1875            FromBuiltin->getKind() == BuiltinType::Half &&
1876           ToBuiltin->getKind() == BuiltinType::Float)
1877         return true;
1878     }
1879 
1880   return false;
1881 }
1882 
1883 /// \brief Determine if a conversion is a complex promotion.
1884 ///
1885 /// A complex promotion is defined as a complex -> complex conversion
1886 /// where the conversion between the underlying real types is a
1887 /// floating-point or integral promotion.
1888 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1889   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1890   if (!FromComplex)
1891     return false;
1892 
1893   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1894   if (!ToComplex)
1895     return false;
1896 
1897   return IsFloatingPointPromotion(FromComplex->getElementType(),
1898                                   ToComplex->getElementType()) ||
1899     IsIntegralPromotion(0, FromComplex->getElementType(),
1900                         ToComplex->getElementType());
1901 }
1902 
1903 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1904 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1905 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1906 /// if non-empty, will be a pointer to ToType that may or may not have
1907 /// the right set of qualifiers on its pointee.
1908 ///
1909 static QualType
1910 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1911                                    QualType ToPointee, QualType ToType,
1912                                    ASTContext &Context,
1913                                    bool StripObjCLifetime = false) {
1914   assert((FromPtr->getTypeClass() == Type::Pointer ||
1915           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1916          "Invalid similarly-qualified pointer type");
1917 
1918   /// Conversions to 'id' subsume cv-qualifier conversions.
1919   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1920     return ToType.getUnqualifiedType();
1921 
1922   QualType CanonFromPointee
1923     = Context.getCanonicalType(FromPtr->getPointeeType());
1924   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1925   Qualifiers Quals = CanonFromPointee.getQualifiers();
1926 
1927   if (StripObjCLifetime)
1928     Quals.removeObjCLifetime();
1929 
1930   // Exact qualifier match -> return the pointer type we're converting to.
1931   if (CanonToPointee.getLocalQualifiers() == Quals) {
1932     // ToType is exactly what we need. Return it.
1933     if (!ToType.isNull())
1934       return ToType.getUnqualifiedType();
1935 
1936     // Build a pointer to ToPointee. It has the right qualifiers
1937     // already.
1938     if (isa<ObjCObjectPointerType>(ToType))
1939       return Context.getObjCObjectPointerType(ToPointee);
1940     return Context.getPointerType(ToPointee);
1941   }
1942 
1943   // Just build a canonical type that has the right qualifiers.
1944   QualType QualifiedCanonToPointee
1945     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1946 
1947   if (isa<ObjCObjectPointerType>(ToType))
1948     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1949   return Context.getPointerType(QualifiedCanonToPointee);
1950 }
1951 
1952 static bool isNullPointerConstantForConversion(Expr *Expr,
1953                                                bool InOverloadResolution,
1954                                                ASTContext &Context) {
1955   // Handle value-dependent integral null pointer constants correctly.
1956   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1957   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1958       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1959     return !InOverloadResolution;
1960 
1961   return Expr->isNullPointerConstant(Context,
1962                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1963                                         : Expr::NPC_ValueDependentIsNull);
1964 }
1965 
1966 /// IsPointerConversion - Determines whether the conversion of the
1967 /// expression From, which has the (possibly adjusted) type FromType,
1968 /// can be converted to the type ToType via a pointer conversion (C++
1969 /// 4.10). If so, returns true and places the converted type (that
1970 /// might differ from ToType in its cv-qualifiers at some level) into
1971 /// ConvertedType.
1972 ///
1973 /// This routine also supports conversions to and from block pointers
1974 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1975 /// pointers to interfaces. FIXME: Once we've determined the
1976 /// appropriate overloading rules for Objective-C, we may want to
1977 /// split the Objective-C checks into a different routine; however,
1978 /// GCC seems to consider all of these conversions to be pointer
1979 /// conversions, so for now they live here. IncompatibleObjC will be
1980 /// set if the conversion is an allowed Objective-C conversion that
1981 /// should result in a warning.
1982 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1983                                bool InOverloadResolution,
1984                                QualType& ConvertedType,
1985                                bool &IncompatibleObjC) {
1986   IncompatibleObjC = false;
1987   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1988                               IncompatibleObjC))
1989     return true;
1990 
1991   // Conversion from a null pointer constant to any Objective-C pointer type.
1992   if (ToType->isObjCObjectPointerType() &&
1993       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1994     ConvertedType = ToType;
1995     return true;
1996   }
1997 
1998   // Blocks: Block pointers can be converted to void*.
1999   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2000       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2001     ConvertedType = ToType;
2002     return true;
2003   }
2004   // Blocks: A null pointer constant can be converted to a block
2005   // pointer type.
2006   if (ToType->isBlockPointerType() &&
2007       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2008     ConvertedType = ToType;
2009     return true;
2010   }
2011 
2012   // If the left-hand-side is nullptr_t, the right side can be a null
2013   // pointer constant.
2014   if (ToType->isNullPtrType() &&
2015       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2016     ConvertedType = ToType;
2017     return true;
2018   }
2019 
2020   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2021   if (!ToTypePtr)
2022     return false;
2023 
2024   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2025   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2026     ConvertedType = ToType;
2027     return true;
2028   }
2029 
2030   // Beyond this point, both types need to be pointers
2031   // , including objective-c pointers.
2032   QualType ToPointeeType = ToTypePtr->getPointeeType();
2033   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2034       !getLangOpts().ObjCAutoRefCount) {
2035     ConvertedType = BuildSimilarlyQualifiedPointerType(
2036                                       FromType->getAs<ObjCObjectPointerType>(),
2037                                                        ToPointeeType,
2038                                                        ToType, Context);
2039     return true;
2040   }
2041   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2042   if (!FromTypePtr)
2043     return false;
2044 
2045   QualType FromPointeeType = FromTypePtr->getPointeeType();
2046 
2047   // If the unqualified pointee types are the same, this can't be a
2048   // pointer conversion, so don't do all of the work below.
2049   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2050     return false;
2051 
2052   // An rvalue of type "pointer to cv T," where T is an object type,
2053   // can be converted to an rvalue of type "pointer to cv void" (C++
2054   // 4.10p2).
2055   if (FromPointeeType->isIncompleteOrObjectType() &&
2056       ToPointeeType->isVoidType()) {
2057     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2058                                                        ToPointeeType,
2059                                                        ToType, Context,
2060                                                    /*StripObjCLifetime=*/true);
2061     return true;
2062   }
2063 
2064   // MSVC allows implicit function to void* type conversion.
2065   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2066       ToPointeeType->isVoidType()) {
2067     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2068                                                        ToPointeeType,
2069                                                        ToType, Context);
2070     return true;
2071   }
2072 
2073   // When we're overloading in C, we allow a special kind of pointer
2074   // conversion for compatible-but-not-identical pointee types.
2075   if (!getLangOpts().CPlusPlus &&
2076       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2077     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2078                                                        ToPointeeType,
2079                                                        ToType, Context);
2080     return true;
2081   }
2082 
2083   // C++ [conv.ptr]p3:
2084   //
2085   //   An rvalue of type "pointer to cv D," where D is a class type,
2086   //   can be converted to an rvalue of type "pointer to cv B," where
2087   //   B is a base class (clause 10) of D. If B is an inaccessible
2088   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2089   //   necessitates this conversion is ill-formed. The result of the
2090   //   conversion is a pointer to the base class sub-object of the
2091   //   derived class object. The null pointer value is converted to
2092   //   the null pointer value of the destination type.
2093   //
2094   // Note that we do not check for ambiguity or inaccessibility
2095   // here. That is handled by CheckPointerConversion.
2096   if (getLangOpts().CPlusPlus &&
2097       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2098       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2099       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2100       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2101     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2102                                                        ToPointeeType,
2103                                                        ToType, Context);
2104     return true;
2105   }
2106 
2107   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2108       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2109     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2110                                                        ToPointeeType,
2111                                                        ToType, Context);
2112     return true;
2113   }
2114 
2115   return false;
2116 }
2117 
2118 /// \brief Adopt the given qualifiers for the given type.
2119 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2120   Qualifiers TQs = T.getQualifiers();
2121 
2122   // Check whether qualifiers already match.
2123   if (TQs == Qs)
2124     return T;
2125 
2126   if (Qs.compatiblyIncludes(TQs))
2127     return Context.getQualifiedType(T, Qs);
2128 
2129   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2130 }
2131 
2132 /// isObjCPointerConversion - Determines whether this is an
2133 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2134 /// with the same arguments and return values.
2135 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2136                                    QualType& ConvertedType,
2137                                    bool &IncompatibleObjC) {
2138   if (!getLangOpts().ObjC1)
2139     return false;
2140 
2141   // The set of qualifiers on the type we're converting from.
2142   Qualifiers FromQualifiers = FromType.getQualifiers();
2143 
2144   // First, we handle all conversions on ObjC object pointer types.
2145   const ObjCObjectPointerType* ToObjCPtr =
2146     ToType->getAs<ObjCObjectPointerType>();
2147   const ObjCObjectPointerType *FromObjCPtr =
2148     FromType->getAs<ObjCObjectPointerType>();
2149 
2150   if (ToObjCPtr && FromObjCPtr) {
2151     // If the pointee types are the same (ignoring qualifications),
2152     // then this is not a pointer conversion.
2153     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2154                                        FromObjCPtr->getPointeeType()))
2155       return false;
2156 
2157     // Check for compatible
2158     // Objective C++: We're able to convert between "id" or "Class" and a
2159     // pointer to any interface (in both directions).
2160     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2161       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2162       return true;
2163     }
2164     // Conversions with Objective-C's id<...>.
2165     if ((FromObjCPtr->isObjCQualifiedIdType() ||
2166          ToObjCPtr->isObjCQualifiedIdType()) &&
2167         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2168                                                   /*compare=*/false)) {
2169       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2170       return true;
2171     }
2172     // Objective C++: We're able to convert from a pointer to an
2173     // interface to a pointer to a different interface.
2174     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2175       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2176       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2177       if (getLangOpts().CPlusPlus && LHS && RHS &&
2178           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2179                                                 FromObjCPtr->getPointeeType()))
2180         return false;
2181       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2182                                                    ToObjCPtr->getPointeeType(),
2183                                                          ToType, Context);
2184       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2185       return true;
2186     }
2187 
2188     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2189       // Okay: this is some kind of implicit downcast of Objective-C
2190       // interfaces, which is permitted. However, we're going to
2191       // complain about it.
2192       IncompatibleObjC = true;
2193       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2194                                                    ToObjCPtr->getPointeeType(),
2195                                                          ToType, Context);
2196       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2197       return true;
2198     }
2199   }
2200   // Beyond this point, both types need to be C pointers or block pointers.
2201   QualType ToPointeeType;
2202   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2203     ToPointeeType = ToCPtr->getPointeeType();
2204   else if (const BlockPointerType *ToBlockPtr =
2205             ToType->getAs<BlockPointerType>()) {
2206     // Objective C++: We're able to convert from a pointer to any object
2207     // to a block pointer type.
2208     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2209       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2210       return true;
2211     }
2212     ToPointeeType = ToBlockPtr->getPointeeType();
2213   }
2214   else if (FromType->getAs<BlockPointerType>() &&
2215            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2216     // Objective C++: We're able to convert from a block pointer type to a
2217     // pointer to any object.
2218     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2219     return true;
2220   }
2221   else
2222     return false;
2223 
2224   QualType FromPointeeType;
2225   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2226     FromPointeeType = FromCPtr->getPointeeType();
2227   else if (const BlockPointerType *FromBlockPtr =
2228            FromType->getAs<BlockPointerType>())
2229     FromPointeeType = FromBlockPtr->getPointeeType();
2230   else
2231     return false;
2232 
2233   // If we have pointers to pointers, recursively check whether this
2234   // is an Objective-C conversion.
2235   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2236       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2237                               IncompatibleObjC)) {
2238     // We always complain about this conversion.
2239     IncompatibleObjC = true;
2240     ConvertedType = Context.getPointerType(ConvertedType);
2241     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2242     return true;
2243   }
2244   // Allow conversion of pointee being objective-c pointer to another one;
2245   // as in I* to id.
2246   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2247       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2248       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2249                               IncompatibleObjC)) {
2250 
2251     ConvertedType = Context.getPointerType(ConvertedType);
2252     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2253     return true;
2254   }
2255 
2256   // If we have pointers to functions or blocks, check whether the only
2257   // differences in the argument and result types are in Objective-C
2258   // pointer conversions. If so, we permit the conversion (but
2259   // complain about it).
2260   const FunctionProtoType *FromFunctionType
2261     = FromPointeeType->getAs<FunctionProtoType>();
2262   const FunctionProtoType *ToFunctionType
2263     = ToPointeeType->getAs<FunctionProtoType>();
2264   if (FromFunctionType && ToFunctionType) {
2265     // If the function types are exactly the same, this isn't an
2266     // Objective-C pointer conversion.
2267     if (Context.getCanonicalType(FromPointeeType)
2268           == Context.getCanonicalType(ToPointeeType))
2269       return false;
2270 
2271     // Perform the quick checks that will tell us whether these
2272     // function types are obviously different.
2273     if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2274         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2275         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2276       return false;
2277 
2278     bool HasObjCConversion = false;
2279     if (Context.getCanonicalType(FromFunctionType->getResultType())
2280           == Context.getCanonicalType(ToFunctionType->getResultType())) {
2281       // Okay, the types match exactly. Nothing to do.
2282     } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2283                                        ToFunctionType->getResultType(),
2284                                        ConvertedType, IncompatibleObjC)) {
2285       // Okay, we have an Objective-C pointer conversion.
2286       HasObjCConversion = true;
2287     } else {
2288       // Function types are too different. Abort.
2289       return false;
2290     }
2291 
2292     // Check argument types.
2293     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2294          ArgIdx != NumArgs; ++ArgIdx) {
2295       QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2296       QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2297       if (Context.getCanonicalType(FromArgType)
2298             == Context.getCanonicalType(ToArgType)) {
2299         // Okay, the types match exactly. Nothing to do.
2300       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2301                                          ConvertedType, IncompatibleObjC)) {
2302         // Okay, we have an Objective-C pointer conversion.
2303         HasObjCConversion = true;
2304       } else {
2305         // Argument types are too different. Abort.
2306         return false;
2307       }
2308     }
2309 
2310     if (HasObjCConversion) {
2311       // We had an Objective-C conversion. Allow this pointer
2312       // conversion, but complain about it.
2313       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2314       IncompatibleObjC = true;
2315       return true;
2316     }
2317   }
2318 
2319   return false;
2320 }
2321 
2322 /// \brief Determine whether this is an Objective-C writeback conversion,
2323 /// used for parameter passing when performing automatic reference counting.
2324 ///
2325 /// \param FromType The type we're converting form.
2326 ///
2327 /// \param ToType The type we're converting to.
2328 ///
2329 /// \param ConvertedType The type that will be produced after applying
2330 /// this conversion.
2331 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2332                                      QualType &ConvertedType) {
2333   if (!getLangOpts().ObjCAutoRefCount ||
2334       Context.hasSameUnqualifiedType(FromType, ToType))
2335     return false;
2336 
2337   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2338   QualType ToPointee;
2339   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2340     ToPointee = ToPointer->getPointeeType();
2341   else
2342     return false;
2343 
2344   Qualifiers ToQuals = ToPointee.getQualifiers();
2345   if (!ToPointee->isObjCLifetimeType() ||
2346       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2347       !ToQuals.withoutObjCLifetime().empty())
2348     return false;
2349 
2350   // Argument must be a pointer to __strong to __weak.
2351   QualType FromPointee;
2352   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2353     FromPointee = FromPointer->getPointeeType();
2354   else
2355     return false;
2356 
2357   Qualifiers FromQuals = FromPointee.getQualifiers();
2358   if (!FromPointee->isObjCLifetimeType() ||
2359       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2360        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2361     return false;
2362 
2363   // Make sure that we have compatible qualifiers.
2364   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2365   if (!ToQuals.compatiblyIncludes(FromQuals))
2366     return false;
2367 
2368   // Remove qualifiers from the pointee type we're converting from; they
2369   // aren't used in the compatibility check belong, and we'll be adding back
2370   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2371   FromPointee = FromPointee.getUnqualifiedType();
2372 
2373   // The unqualified form of the pointee types must be compatible.
2374   ToPointee = ToPointee.getUnqualifiedType();
2375   bool IncompatibleObjC;
2376   if (Context.typesAreCompatible(FromPointee, ToPointee))
2377     FromPointee = ToPointee;
2378   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2379                                     IncompatibleObjC))
2380     return false;
2381 
2382   /// \brief Construct the type we're converting to, which is a pointer to
2383   /// __autoreleasing pointee.
2384   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2385   ConvertedType = Context.getPointerType(FromPointee);
2386   return true;
2387 }
2388 
2389 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2390                                     QualType& ConvertedType) {
2391   QualType ToPointeeType;
2392   if (const BlockPointerType *ToBlockPtr =
2393         ToType->getAs<BlockPointerType>())
2394     ToPointeeType = ToBlockPtr->getPointeeType();
2395   else
2396     return false;
2397 
2398   QualType FromPointeeType;
2399   if (const BlockPointerType *FromBlockPtr =
2400       FromType->getAs<BlockPointerType>())
2401     FromPointeeType = FromBlockPtr->getPointeeType();
2402   else
2403     return false;
2404   // We have pointer to blocks, check whether the only
2405   // differences in the argument and result types are in Objective-C
2406   // pointer conversions. If so, we permit the conversion.
2407 
2408   const FunctionProtoType *FromFunctionType
2409     = FromPointeeType->getAs<FunctionProtoType>();
2410   const FunctionProtoType *ToFunctionType
2411     = ToPointeeType->getAs<FunctionProtoType>();
2412 
2413   if (!FromFunctionType || !ToFunctionType)
2414     return false;
2415 
2416   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2417     return true;
2418 
2419   // Perform the quick checks that will tell us whether these
2420   // function types are obviously different.
2421   if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2422       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2423     return false;
2424 
2425   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2426   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2427   if (FromEInfo != ToEInfo)
2428     return false;
2429 
2430   bool IncompatibleObjC = false;
2431   if (Context.hasSameType(FromFunctionType->getResultType(),
2432                           ToFunctionType->getResultType())) {
2433     // Okay, the types match exactly. Nothing to do.
2434   } else {
2435     QualType RHS = FromFunctionType->getResultType();
2436     QualType LHS = ToFunctionType->getResultType();
2437     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2438         !RHS.hasQualifiers() && LHS.hasQualifiers())
2439        LHS = LHS.getUnqualifiedType();
2440 
2441      if (Context.hasSameType(RHS,LHS)) {
2442        // OK exact match.
2443      } else if (isObjCPointerConversion(RHS, LHS,
2444                                         ConvertedType, IncompatibleObjC)) {
2445      if (IncompatibleObjC)
2446        return false;
2447      // Okay, we have an Objective-C pointer conversion.
2448      }
2449      else
2450        return false;
2451    }
2452 
2453    // Check argument types.
2454    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2455         ArgIdx != NumArgs; ++ArgIdx) {
2456      IncompatibleObjC = false;
2457      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2458      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2459      if (Context.hasSameType(FromArgType, ToArgType)) {
2460        // Okay, the types match exactly. Nothing to do.
2461      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2462                                         ConvertedType, IncompatibleObjC)) {
2463        if (IncompatibleObjC)
2464          return false;
2465        // Okay, we have an Objective-C pointer conversion.
2466      } else
2467        // Argument types are too different. Abort.
2468        return false;
2469    }
2470    if (LangOpts.ObjCAutoRefCount &&
2471        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2472                                                     ToFunctionType))
2473      return false;
2474 
2475    ConvertedType = ToType;
2476    return true;
2477 }
2478 
2479 enum {
2480   ft_default,
2481   ft_different_class,
2482   ft_parameter_arity,
2483   ft_parameter_mismatch,
2484   ft_return_type,
2485   ft_qualifer_mismatch
2486 };
2487 
2488 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2489 /// function types.  Catches different number of parameter, mismatch in
2490 /// parameter types, and different return types.
2491 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2492                                       QualType FromType, QualType ToType) {
2493   // If either type is not valid, include no extra info.
2494   if (FromType.isNull() || ToType.isNull()) {
2495     PDiag << ft_default;
2496     return;
2497   }
2498 
2499   // Get the function type from the pointers.
2500   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2501     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2502                             *ToMember = ToType->getAs<MemberPointerType>();
2503     if (FromMember->getClass() != ToMember->getClass()) {
2504       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2505             << QualType(FromMember->getClass(), 0);
2506       return;
2507     }
2508     FromType = FromMember->getPointeeType();
2509     ToType = ToMember->getPointeeType();
2510   }
2511 
2512   if (FromType->isPointerType())
2513     FromType = FromType->getPointeeType();
2514   if (ToType->isPointerType())
2515     ToType = ToType->getPointeeType();
2516 
2517   // Remove references.
2518   FromType = FromType.getNonReferenceType();
2519   ToType = ToType.getNonReferenceType();
2520 
2521   // Don't print extra info for non-specialized template functions.
2522   if (FromType->isInstantiationDependentType() &&
2523       !FromType->getAs<TemplateSpecializationType>()) {
2524     PDiag << ft_default;
2525     return;
2526   }
2527 
2528   // No extra info for same types.
2529   if (Context.hasSameType(FromType, ToType)) {
2530     PDiag << ft_default;
2531     return;
2532   }
2533 
2534   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2535                           *ToFunction = ToType->getAs<FunctionProtoType>();
2536 
2537   // Both types need to be function types.
2538   if (!FromFunction || !ToFunction) {
2539     PDiag << ft_default;
2540     return;
2541   }
2542 
2543   if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2544     PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2545           << FromFunction->getNumArgs();
2546     return;
2547   }
2548 
2549   // Handle different parameter types.
2550   unsigned ArgPos;
2551   if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2552     PDiag << ft_parameter_mismatch << ArgPos + 1
2553           << ToFunction->getArgType(ArgPos)
2554           << FromFunction->getArgType(ArgPos);
2555     return;
2556   }
2557 
2558   // Handle different return type.
2559   if (!Context.hasSameType(FromFunction->getResultType(),
2560                            ToFunction->getResultType())) {
2561     PDiag << ft_return_type << ToFunction->getResultType()
2562           << FromFunction->getResultType();
2563     return;
2564   }
2565 
2566   unsigned FromQuals = FromFunction->getTypeQuals(),
2567            ToQuals = ToFunction->getTypeQuals();
2568   if (FromQuals != ToQuals) {
2569     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2570     return;
2571   }
2572 
2573   // Unable to find a difference, so add no extra info.
2574   PDiag << ft_default;
2575 }
2576 
2577 /// FunctionArgTypesAreEqual - This routine checks two function proto types
2578 /// for equality of their argument types. Caller has already checked that
2579 /// they have same number of arguments.  If the parameters are different,
2580 /// ArgPos will have the parameter index of the first different parameter.
2581 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2582                                     const FunctionProtoType *NewType,
2583                                     unsigned *ArgPos) {
2584   for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2585        N = NewType->arg_type_begin(),
2586        E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2587     if (!Context.hasSameType(*O, *N)) {
2588       if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2589       return false;
2590     }
2591   }
2592   return true;
2593 }
2594 
2595 /// CheckPointerConversion - Check the pointer conversion from the
2596 /// expression From to the type ToType. This routine checks for
2597 /// ambiguous or inaccessible derived-to-base pointer
2598 /// conversions for which IsPointerConversion has already returned
2599 /// true. It returns true and produces a diagnostic if there was an
2600 /// error, or returns false otherwise.
2601 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2602                                   CastKind &Kind,
2603                                   CXXCastPath& BasePath,
2604                                   bool IgnoreBaseAccess) {
2605   QualType FromType = From->getType();
2606   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2607 
2608   Kind = CK_BitCast;
2609 
2610   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2611       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2612       Expr::NPCK_ZeroExpression) {
2613     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2614       DiagRuntimeBehavior(From->getExprLoc(), From,
2615                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2616                             << ToType << From->getSourceRange());
2617     else if (!isUnevaluatedContext())
2618       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2619         << ToType << From->getSourceRange();
2620   }
2621   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2622     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2623       QualType FromPointeeType = FromPtrType->getPointeeType(),
2624                ToPointeeType   = ToPtrType->getPointeeType();
2625 
2626       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2627           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2628         // We must have a derived-to-base conversion. Check an
2629         // ambiguous or inaccessible conversion.
2630         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2631                                          From->getExprLoc(),
2632                                          From->getSourceRange(), &BasePath,
2633                                          IgnoreBaseAccess))
2634           return true;
2635 
2636         // The conversion was successful.
2637         Kind = CK_DerivedToBase;
2638       }
2639     }
2640   } else if (const ObjCObjectPointerType *ToPtrType =
2641                ToType->getAs<ObjCObjectPointerType>()) {
2642     if (const ObjCObjectPointerType *FromPtrType =
2643           FromType->getAs<ObjCObjectPointerType>()) {
2644       // Objective-C++ conversions are always okay.
2645       // FIXME: We should have a different class of conversions for the
2646       // Objective-C++ implicit conversions.
2647       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2648         return false;
2649     } else if (FromType->isBlockPointerType()) {
2650       Kind = CK_BlockPointerToObjCPointerCast;
2651     } else {
2652       Kind = CK_CPointerToObjCPointerCast;
2653     }
2654   } else if (ToType->isBlockPointerType()) {
2655     if (!FromType->isBlockPointerType())
2656       Kind = CK_AnyPointerToBlockPointerCast;
2657   }
2658 
2659   // We shouldn't fall into this case unless it's valid for other
2660   // reasons.
2661   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2662     Kind = CK_NullToPointer;
2663 
2664   return false;
2665 }
2666 
2667 /// IsMemberPointerConversion - Determines whether the conversion of the
2668 /// expression From, which has the (possibly adjusted) type FromType, can be
2669 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2670 /// If so, returns true and places the converted type (that might differ from
2671 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2672 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2673                                      QualType ToType,
2674                                      bool InOverloadResolution,
2675                                      QualType &ConvertedType) {
2676   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2677   if (!ToTypePtr)
2678     return false;
2679 
2680   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2681   if (From->isNullPointerConstant(Context,
2682                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2683                                         : Expr::NPC_ValueDependentIsNull)) {
2684     ConvertedType = ToType;
2685     return true;
2686   }
2687 
2688   // Otherwise, both types have to be member pointers.
2689   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2690   if (!FromTypePtr)
2691     return false;
2692 
2693   // A pointer to member of B can be converted to a pointer to member of D,
2694   // where D is derived from B (C++ 4.11p2).
2695   QualType FromClass(FromTypePtr->getClass(), 0);
2696   QualType ToClass(ToTypePtr->getClass(), 0);
2697 
2698   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2699       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2700       IsDerivedFrom(ToClass, FromClass)) {
2701     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2702                                                  ToClass.getTypePtr());
2703     return true;
2704   }
2705 
2706   return false;
2707 }
2708 
2709 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2710 /// expression From to the type ToType. This routine checks for ambiguous or
2711 /// virtual or inaccessible base-to-derived member pointer conversions
2712 /// for which IsMemberPointerConversion has already returned true. It returns
2713 /// true and produces a diagnostic if there was an error, or returns false
2714 /// otherwise.
2715 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2716                                         CastKind &Kind,
2717                                         CXXCastPath &BasePath,
2718                                         bool IgnoreBaseAccess) {
2719   QualType FromType = From->getType();
2720   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2721   if (!FromPtrType) {
2722     // This must be a null pointer to member pointer conversion
2723     assert(From->isNullPointerConstant(Context,
2724                                        Expr::NPC_ValueDependentIsNull) &&
2725            "Expr must be null pointer constant!");
2726     Kind = CK_NullToMemberPointer;
2727     return false;
2728   }
2729 
2730   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2731   assert(ToPtrType && "No member pointer cast has a target type "
2732                       "that is not a member pointer.");
2733 
2734   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2735   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2736 
2737   // FIXME: What about dependent types?
2738   assert(FromClass->isRecordType() && "Pointer into non-class.");
2739   assert(ToClass->isRecordType() && "Pointer into non-class.");
2740 
2741   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2742                      /*DetectVirtual=*/true);
2743   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2744   assert(DerivationOkay &&
2745          "Should not have been called if derivation isn't OK.");
2746   (void)DerivationOkay;
2747 
2748   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2749                                   getUnqualifiedType())) {
2750     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2751     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2752       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2753     return true;
2754   }
2755 
2756   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2757     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2758       << FromClass << ToClass << QualType(VBase, 0)
2759       << From->getSourceRange();
2760     return true;
2761   }
2762 
2763   if (!IgnoreBaseAccess)
2764     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2765                          Paths.front(),
2766                          diag::err_downcast_from_inaccessible_base);
2767 
2768   // Must be a base to derived member conversion.
2769   BuildBasePathArray(Paths, BasePath);
2770   Kind = CK_BaseToDerivedMemberPointer;
2771   return false;
2772 }
2773 
2774 /// IsQualificationConversion - Determines whether the conversion from
2775 /// an rvalue of type FromType to ToType is a qualification conversion
2776 /// (C++ 4.4).
2777 ///
2778 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2779 /// when the qualification conversion involves a change in the Objective-C
2780 /// object lifetime.
2781 bool
2782 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2783                                 bool CStyle, bool &ObjCLifetimeConversion) {
2784   FromType = Context.getCanonicalType(FromType);
2785   ToType = Context.getCanonicalType(ToType);
2786   ObjCLifetimeConversion = false;
2787 
2788   // If FromType and ToType are the same type, this is not a
2789   // qualification conversion.
2790   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2791     return false;
2792 
2793   // (C++ 4.4p4):
2794   //   A conversion can add cv-qualifiers at levels other than the first
2795   //   in multi-level pointers, subject to the following rules: [...]
2796   bool PreviousToQualsIncludeConst = true;
2797   bool UnwrappedAnyPointer = false;
2798   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2799     // Within each iteration of the loop, we check the qualifiers to
2800     // determine if this still looks like a qualification
2801     // conversion. Then, if all is well, we unwrap one more level of
2802     // pointers or pointers-to-members and do it all again
2803     // until there are no more pointers or pointers-to-members left to
2804     // unwrap.
2805     UnwrappedAnyPointer = true;
2806 
2807     Qualifiers FromQuals = FromType.getQualifiers();
2808     Qualifiers ToQuals = ToType.getQualifiers();
2809 
2810     // Objective-C ARC:
2811     //   Check Objective-C lifetime conversions.
2812     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2813         UnwrappedAnyPointer) {
2814       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2815         ObjCLifetimeConversion = true;
2816         FromQuals.removeObjCLifetime();
2817         ToQuals.removeObjCLifetime();
2818       } else {
2819         // Qualification conversions cannot cast between different
2820         // Objective-C lifetime qualifiers.
2821         return false;
2822       }
2823     }
2824 
2825     // Allow addition/removal of GC attributes but not changing GC attributes.
2826     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2827         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2828       FromQuals.removeObjCGCAttr();
2829       ToQuals.removeObjCGCAttr();
2830     }
2831 
2832     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2833     //      2,j, and similarly for volatile.
2834     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2835       return false;
2836 
2837     //   -- if the cv 1,j and cv 2,j are different, then const is in
2838     //      every cv for 0 < k < j.
2839     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2840         && !PreviousToQualsIncludeConst)
2841       return false;
2842 
2843     // Keep track of whether all prior cv-qualifiers in the "to" type
2844     // include const.
2845     PreviousToQualsIncludeConst
2846       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2847   }
2848 
2849   // We are left with FromType and ToType being the pointee types
2850   // after unwrapping the original FromType and ToType the same number
2851   // of types. If we unwrapped any pointers, and if FromType and
2852   // ToType have the same unqualified type (since we checked
2853   // qualifiers above), then this is a qualification conversion.
2854   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2855 }
2856 
2857 /// \brief - Determine whether this is a conversion from a scalar type to an
2858 /// atomic type.
2859 ///
2860 /// If successful, updates \c SCS's second and third steps in the conversion
2861 /// sequence to finish the conversion.
2862 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2863                                 bool InOverloadResolution,
2864                                 StandardConversionSequence &SCS,
2865                                 bool CStyle) {
2866   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2867   if (!ToAtomic)
2868     return false;
2869 
2870   StandardConversionSequence InnerSCS;
2871   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2872                             InOverloadResolution, InnerSCS,
2873                             CStyle, /*AllowObjCWritebackConversion=*/false))
2874     return false;
2875 
2876   SCS.Second = InnerSCS.Second;
2877   SCS.setToType(1, InnerSCS.getToType(1));
2878   SCS.Third = InnerSCS.Third;
2879   SCS.QualificationIncludesObjCLifetime
2880     = InnerSCS.QualificationIncludesObjCLifetime;
2881   SCS.setToType(2, InnerSCS.getToType(2));
2882   return true;
2883 }
2884 
2885 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2886                                               CXXConstructorDecl *Constructor,
2887                                               QualType Type) {
2888   const FunctionProtoType *CtorType =
2889       Constructor->getType()->getAs<FunctionProtoType>();
2890   if (CtorType->getNumArgs() > 0) {
2891     QualType FirstArg = CtorType->getArgType(0);
2892     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2893       return true;
2894   }
2895   return false;
2896 }
2897 
2898 static OverloadingResult
2899 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2900                                        CXXRecordDecl *To,
2901                                        UserDefinedConversionSequence &User,
2902                                        OverloadCandidateSet &CandidateSet,
2903                                        bool AllowExplicit) {
2904   DeclContext::lookup_result R = S.LookupConstructors(To);
2905   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2906        Con != ConEnd; ++Con) {
2907     NamedDecl *D = *Con;
2908     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2909 
2910     // Find the constructor (which may be a template).
2911     CXXConstructorDecl *Constructor = 0;
2912     FunctionTemplateDecl *ConstructorTmpl
2913       = dyn_cast<FunctionTemplateDecl>(D);
2914     if (ConstructorTmpl)
2915       Constructor
2916         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2917     else
2918       Constructor = cast<CXXConstructorDecl>(D);
2919 
2920     bool Usable = !Constructor->isInvalidDecl() &&
2921                   S.isInitListConstructor(Constructor) &&
2922                   (AllowExplicit || !Constructor->isExplicit());
2923     if (Usable) {
2924       // If the first argument is (a reference to) the target type,
2925       // suppress conversions.
2926       bool SuppressUserConversions =
2927           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2928       if (ConstructorTmpl)
2929         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2930                                        /*ExplicitArgs*/ 0,
2931                                        From, CandidateSet,
2932                                        SuppressUserConversions);
2933       else
2934         S.AddOverloadCandidate(Constructor, FoundDecl,
2935                                From, CandidateSet,
2936                                SuppressUserConversions);
2937     }
2938   }
2939 
2940   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2941 
2942   OverloadCandidateSet::iterator Best;
2943   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2944   case OR_Success: {
2945     // Record the standard conversion we used and the conversion function.
2946     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2947     QualType ThisType = Constructor->getThisType(S.Context);
2948     // Initializer lists don't have conversions as such.
2949     User.Before.setAsIdentityConversion();
2950     User.HadMultipleCandidates = HadMultipleCandidates;
2951     User.ConversionFunction = Constructor;
2952     User.FoundConversionFunction = Best->FoundDecl;
2953     User.After.setAsIdentityConversion();
2954     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2955     User.After.setAllToTypes(ToType);
2956     return OR_Success;
2957   }
2958 
2959   case OR_No_Viable_Function:
2960     return OR_No_Viable_Function;
2961   case OR_Deleted:
2962     return OR_Deleted;
2963   case OR_Ambiguous:
2964     return OR_Ambiguous;
2965   }
2966 
2967   llvm_unreachable("Invalid OverloadResult!");
2968 }
2969 
2970 /// Determines whether there is a user-defined conversion sequence
2971 /// (C++ [over.ics.user]) that converts expression From to the type
2972 /// ToType. If such a conversion exists, User will contain the
2973 /// user-defined conversion sequence that performs such a conversion
2974 /// and this routine will return true. Otherwise, this routine returns
2975 /// false and User is unspecified.
2976 ///
2977 /// \param AllowExplicit  true if the conversion should consider C++0x
2978 /// "explicit" conversion functions as well as non-explicit conversion
2979 /// functions (C++0x [class.conv.fct]p2).
2980 static OverloadingResult
2981 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2982                         UserDefinedConversionSequence &User,
2983                         OverloadCandidateSet &CandidateSet,
2984                         bool AllowExplicit) {
2985   // Whether we will only visit constructors.
2986   bool ConstructorsOnly = false;
2987 
2988   // If the type we are conversion to is a class type, enumerate its
2989   // constructors.
2990   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2991     // C++ [over.match.ctor]p1:
2992     //   When objects of class type are direct-initialized (8.5), or
2993     //   copy-initialized from an expression of the same or a
2994     //   derived class type (8.5), overload resolution selects the
2995     //   constructor. [...] For copy-initialization, the candidate
2996     //   functions are all the converting constructors (12.3.1) of
2997     //   that class. The argument list is the expression-list within
2998     //   the parentheses of the initializer.
2999     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3000         (From->getType()->getAs<RecordType>() &&
3001          S.IsDerivedFrom(From->getType(), ToType)))
3002       ConstructorsOnly = true;
3003 
3004     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3005     // RequireCompleteType may have returned true due to some invalid decl
3006     // during template instantiation, but ToType may be complete enough now
3007     // to try to recover.
3008     if (ToType->isIncompleteType()) {
3009       // We're not going to find any constructors.
3010     } else if (CXXRecordDecl *ToRecordDecl
3011                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3012 
3013       Expr **Args = &From;
3014       unsigned NumArgs = 1;
3015       bool ListInitializing = false;
3016       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3017         // But first, see if there is an init-list-contructor that will work.
3018         OverloadingResult Result = IsInitializerListConstructorConversion(
3019             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3020         if (Result != OR_No_Viable_Function)
3021           return Result;
3022         // Never mind.
3023         CandidateSet.clear();
3024 
3025         // If we're list-initializing, we pass the individual elements as
3026         // arguments, not the entire list.
3027         Args = InitList->getInits();
3028         NumArgs = InitList->getNumInits();
3029         ListInitializing = true;
3030       }
3031 
3032       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3033       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3034            Con != ConEnd; ++Con) {
3035         NamedDecl *D = *Con;
3036         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3037 
3038         // Find the constructor (which may be a template).
3039         CXXConstructorDecl *Constructor = 0;
3040         FunctionTemplateDecl *ConstructorTmpl
3041           = dyn_cast<FunctionTemplateDecl>(D);
3042         if (ConstructorTmpl)
3043           Constructor
3044             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3045         else
3046           Constructor = cast<CXXConstructorDecl>(D);
3047 
3048         bool Usable = !Constructor->isInvalidDecl();
3049         if (ListInitializing)
3050           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3051         else
3052           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3053         if (Usable) {
3054           bool SuppressUserConversions = !ConstructorsOnly;
3055           if (SuppressUserConversions && ListInitializing) {
3056             SuppressUserConversions = false;
3057             if (NumArgs == 1) {
3058               // If the first argument is (a reference to) the target type,
3059               // suppress conversions.
3060               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3061                                                 S.Context, Constructor, ToType);
3062             }
3063           }
3064           if (ConstructorTmpl)
3065             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3066                                            /*ExplicitArgs*/ 0,
3067                                            llvm::makeArrayRef(Args, NumArgs),
3068                                            CandidateSet, SuppressUserConversions);
3069           else
3070             // Allow one user-defined conversion when user specifies a
3071             // From->ToType conversion via an static cast (c-style, etc).
3072             S.AddOverloadCandidate(Constructor, FoundDecl,
3073                                    llvm::makeArrayRef(Args, NumArgs),
3074                                    CandidateSet, SuppressUserConversions);
3075         }
3076       }
3077     }
3078   }
3079 
3080   // Enumerate conversion functions, if we're allowed to.
3081   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3082   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3083     // No conversion functions from incomplete types.
3084   } else if (const RecordType *FromRecordType
3085                                    = From->getType()->getAs<RecordType>()) {
3086     if (CXXRecordDecl *FromRecordDecl
3087          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3088       // Add all of the conversion functions as candidates.
3089       std::pair<CXXRecordDecl::conversion_iterator,
3090                 CXXRecordDecl::conversion_iterator>
3091         Conversions = FromRecordDecl->getVisibleConversionFunctions();
3092       for (CXXRecordDecl::conversion_iterator
3093              I = Conversions.first, E = Conversions.second; I != E; ++I) {
3094         DeclAccessPair FoundDecl = I.getPair();
3095         NamedDecl *D = FoundDecl.getDecl();
3096         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3097         if (isa<UsingShadowDecl>(D))
3098           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3099 
3100         CXXConversionDecl *Conv;
3101         FunctionTemplateDecl *ConvTemplate;
3102         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3103           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3104         else
3105           Conv = cast<CXXConversionDecl>(D);
3106 
3107         if (AllowExplicit || !Conv->isExplicit()) {
3108           if (ConvTemplate)
3109             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3110                                              ActingContext, From, ToType,
3111                                              CandidateSet);
3112           else
3113             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3114                                      From, ToType, CandidateSet);
3115         }
3116       }
3117     }
3118   }
3119 
3120   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3121 
3122   OverloadCandidateSet::iterator Best;
3123   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3124   case OR_Success:
3125     // Record the standard conversion we used and the conversion function.
3126     if (CXXConstructorDecl *Constructor
3127           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3128       // C++ [over.ics.user]p1:
3129       //   If the user-defined conversion is specified by a
3130       //   constructor (12.3.1), the initial standard conversion
3131       //   sequence converts the source type to the type required by
3132       //   the argument of the constructor.
3133       //
3134       QualType ThisType = Constructor->getThisType(S.Context);
3135       if (isa<InitListExpr>(From)) {
3136         // Initializer lists don't have conversions as such.
3137         User.Before.setAsIdentityConversion();
3138       } else {
3139         if (Best->Conversions[0].isEllipsis())
3140           User.EllipsisConversion = true;
3141         else {
3142           User.Before = Best->Conversions[0].Standard;
3143           User.EllipsisConversion = false;
3144         }
3145       }
3146       User.HadMultipleCandidates = HadMultipleCandidates;
3147       User.ConversionFunction = Constructor;
3148       User.FoundConversionFunction = Best->FoundDecl;
3149       User.After.setAsIdentityConversion();
3150       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3151       User.After.setAllToTypes(ToType);
3152       return OR_Success;
3153     }
3154     if (CXXConversionDecl *Conversion
3155                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3156       // C++ [over.ics.user]p1:
3157       //
3158       //   [...] If the user-defined conversion is specified by a
3159       //   conversion function (12.3.2), the initial standard
3160       //   conversion sequence converts the source type to the
3161       //   implicit object parameter of the conversion function.
3162       User.Before = Best->Conversions[0].Standard;
3163       User.HadMultipleCandidates = HadMultipleCandidates;
3164       User.ConversionFunction = Conversion;
3165       User.FoundConversionFunction = Best->FoundDecl;
3166       User.EllipsisConversion = false;
3167 
3168       // C++ [over.ics.user]p2:
3169       //   The second standard conversion sequence converts the
3170       //   result of the user-defined conversion to the target type
3171       //   for the sequence. Since an implicit conversion sequence
3172       //   is an initialization, the special rules for
3173       //   initialization by user-defined conversion apply when
3174       //   selecting the best user-defined conversion for a
3175       //   user-defined conversion sequence (see 13.3.3 and
3176       //   13.3.3.1).
3177       User.After = Best->FinalConversion;
3178       return OR_Success;
3179     }
3180     llvm_unreachable("Not a constructor or conversion function?");
3181 
3182   case OR_No_Viable_Function:
3183     return OR_No_Viable_Function;
3184   case OR_Deleted:
3185     // No conversion here! We're done.
3186     return OR_Deleted;
3187 
3188   case OR_Ambiguous:
3189     return OR_Ambiguous;
3190   }
3191 
3192   llvm_unreachable("Invalid OverloadResult!");
3193 }
3194 
3195 bool
3196 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3197   ImplicitConversionSequence ICS;
3198   OverloadCandidateSet CandidateSet(From->getExprLoc());
3199   OverloadingResult OvResult =
3200     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3201                             CandidateSet, false);
3202   if (OvResult == OR_Ambiguous)
3203     Diag(From->getLocStart(),
3204          diag::err_typecheck_ambiguous_condition)
3205           << From->getType() << ToType << From->getSourceRange();
3206   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3207     if (!RequireCompleteType(From->getLocStart(), ToType,
3208                           diag::err_typecheck_nonviable_condition_incomplete,
3209                              From->getType(), From->getSourceRange()))
3210       Diag(From->getLocStart(),
3211            diag::err_typecheck_nonviable_condition)
3212            << From->getType() << From->getSourceRange() << ToType;
3213   }
3214   else
3215     return false;
3216   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3217   return true;
3218 }
3219 
3220 /// \brief Compare the user-defined conversion functions or constructors
3221 /// of two user-defined conversion sequences to determine whether any ordering
3222 /// is possible.
3223 static ImplicitConversionSequence::CompareKind
3224 compareConversionFunctions(Sema &S,
3225                            FunctionDecl *Function1,
3226                            FunctionDecl *Function2) {
3227   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3228     return ImplicitConversionSequence::Indistinguishable;
3229 
3230   // Objective-C++:
3231   //   If both conversion functions are implicitly-declared conversions from
3232   //   a lambda closure type to a function pointer and a block pointer,
3233   //   respectively, always prefer the conversion to a function pointer,
3234   //   because the function pointer is more lightweight and is more likely
3235   //   to keep code working.
3236   CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3237   if (!Conv1)
3238     return ImplicitConversionSequence::Indistinguishable;
3239 
3240   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3241   if (!Conv2)
3242     return ImplicitConversionSequence::Indistinguishable;
3243 
3244   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3245     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3246     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3247     if (Block1 != Block2)
3248       return Block1? ImplicitConversionSequence::Worse
3249                    : ImplicitConversionSequence::Better;
3250   }
3251 
3252   return ImplicitConversionSequence::Indistinguishable;
3253 }
3254 
3255 /// CompareImplicitConversionSequences - Compare two implicit
3256 /// conversion sequences to determine whether one is better than the
3257 /// other or if they are indistinguishable (C++ 13.3.3.2).
3258 static ImplicitConversionSequence::CompareKind
3259 CompareImplicitConversionSequences(Sema &S,
3260                                    const ImplicitConversionSequence& ICS1,
3261                                    const ImplicitConversionSequence& ICS2)
3262 {
3263   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3264   // conversion sequences (as defined in 13.3.3.1)
3265   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3266   //      conversion sequence than a user-defined conversion sequence or
3267   //      an ellipsis conversion sequence, and
3268   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3269   //      conversion sequence than an ellipsis conversion sequence
3270   //      (13.3.3.1.3).
3271   //
3272   // C++0x [over.best.ics]p10:
3273   //   For the purpose of ranking implicit conversion sequences as
3274   //   described in 13.3.3.2, the ambiguous conversion sequence is
3275   //   treated as a user-defined sequence that is indistinguishable
3276   //   from any other user-defined conversion sequence.
3277   if (ICS1.getKindRank() < ICS2.getKindRank())
3278     return ImplicitConversionSequence::Better;
3279   if (ICS2.getKindRank() < ICS1.getKindRank())
3280     return ImplicitConversionSequence::Worse;
3281 
3282   // The following checks require both conversion sequences to be of
3283   // the same kind.
3284   if (ICS1.getKind() != ICS2.getKind())
3285     return ImplicitConversionSequence::Indistinguishable;
3286 
3287   ImplicitConversionSequence::CompareKind Result =
3288       ImplicitConversionSequence::Indistinguishable;
3289 
3290   // Two implicit conversion sequences of the same form are
3291   // indistinguishable conversion sequences unless one of the
3292   // following rules apply: (C++ 13.3.3.2p3):
3293   if (ICS1.isStandard())
3294     Result = CompareStandardConversionSequences(S,
3295                                                 ICS1.Standard, ICS2.Standard);
3296   else if (ICS1.isUserDefined()) {
3297     // User-defined conversion sequence U1 is a better conversion
3298     // sequence than another user-defined conversion sequence U2 if
3299     // they contain the same user-defined conversion function or
3300     // constructor and if the second standard conversion sequence of
3301     // U1 is better than the second standard conversion sequence of
3302     // U2 (C++ 13.3.3.2p3).
3303     if (ICS1.UserDefined.ConversionFunction ==
3304           ICS2.UserDefined.ConversionFunction)
3305       Result = CompareStandardConversionSequences(S,
3306                                                   ICS1.UserDefined.After,
3307                                                   ICS2.UserDefined.After);
3308     else
3309       Result = compareConversionFunctions(S,
3310                                           ICS1.UserDefined.ConversionFunction,
3311                                           ICS2.UserDefined.ConversionFunction);
3312   }
3313 
3314   // List-initialization sequence L1 is a better conversion sequence than
3315   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3316   // for some X and L2 does not.
3317   if (Result == ImplicitConversionSequence::Indistinguishable &&
3318       !ICS1.isBad() &&
3319       ICS1.isListInitializationSequence() &&
3320       ICS2.isListInitializationSequence()) {
3321     if (ICS1.isStdInitializerListElement() &&
3322         !ICS2.isStdInitializerListElement())
3323       return ImplicitConversionSequence::Better;
3324     if (!ICS1.isStdInitializerListElement() &&
3325         ICS2.isStdInitializerListElement())
3326       return ImplicitConversionSequence::Worse;
3327   }
3328 
3329   return Result;
3330 }
3331 
3332 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3333   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3334     Qualifiers Quals;
3335     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3336     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3337   }
3338 
3339   return Context.hasSameUnqualifiedType(T1, T2);
3340 }
3341 
3342 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3343 // determine if one is a proper subset of the other.
3344 static ImplicitConversionSequence::CompareKind
3345 compareStandardConversionSubsets(ASTContext &Context,
3346                                  const StandardConversionSequence& SCS1,
3347                                  const StandardConversionSequence& SCS2) {
3348   ImplicitConversionSequence::CompareKind Result
3349     = ImplicitConversionSequence::Indistinguishable;
3350 
3351   // the identity conversion sequence is considered to be a subsequence of
3352   // any non-identity conversion sequence
3353   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3354     return ImplicitConversionSequence::Better;
3355   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3356     return ImplicitConversionSequence::Worse;
3357 
3358   if (SCS1.Second != SCS2.Second) {
3359     if (SCS1.Second == ICK_Identity)
3360       Result = ImplicitConversionSequence::Better;
3361     else if (SCS2.Second == ICK_Identity)
3362       Result = ImplicitConversionSequence::Worse;
3363     else
3364       return ImplicitConversionSequence::Indistinguishable;
3365   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3366     return ImplicitConversionSequence::Indistinguishable;
3367 
3368   if (SCS1.Third == SCS2.Third) {
3369     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3370                              : ImplicitConversionSequence::Indistinguishable;
3371   }
3372 
3373   if (SCS1.Third == ICK_Identity)
3374     return Result == ImplicitConversionSequence::Worse
3375              ? ImplicitConversionSequence::Indistinguishable
3376              : ImplicitConversionSequence::Better;
3377 
3378   if (SCS2.Third == ICK_Identity)
3379     return Result == ImplicitConversionSequence::Better
3380              ? ImplicitConversionSequence::Indistinguishable
3381              : ImplicitConversionSequence::Worse;
3382 
3383   return ImplicitConversionSequence::Indistinguishable;
3384 }
3385 
3386 /// \brief Determine whether one of the given reference bindings is better
3387 /// than the other based on what kind of bindings they are.
3388 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3389                                        const StandardConversionSequence &SCS2) {
3390   // C++0x [over.ics.rank]p3b4:
3391   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3392   //      implicit object parameter of a non-static member function declared
3393   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3394   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3395   //      lvalue reference to a function lvalue and S2 binds an rvalue
3396   //      reference*.
3397   //
3398   // FIXME: Rvalue references. We're going rogue with the above edits,
3399   // because the semantics in the current C++0x working paper (N3225 at the
3400   // time of this writing) break the standard definition of std::forward
3401   // and std::reference_wrapper when dealing with references to functions.
3402   // Proposed wording changes submitted to CWG for consideration.
3403   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3404       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3405     return false;
3406 
3407   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3408           SCS2.IsLvalueReference) ||
3409          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3410           !SCS2.IsLvalueReference);
3411 }
3412 
3413 /// CompareStandardConversionSequences - Compare two standard
3414 /// conversion sequences to determine whether one is better than the
3415 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3416 static ImplicitConversionSequence::CompareKind
3417 CompareStandardConversionSequences(Sema &S,
3418                                    const StandardConversionSequence& SCS1,
3419                                    const StandardConversionSequence& SCS2)
3420 {
3421   // Standard conversion sequence S1 is a better conversion sequence
3422   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3423 
3424   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3425   //     sequences in the canonical form defined by 13.3.3.1.1,
3426   //     excluding any Lvalue Transformation; the identity conversion
3427   //     sequence is considered to be a subsequence of any
3428   //     non-identity conversion sequence) or, if not that,
3429   if (ImplicitConversionSequence::CompareKind CK
3430         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3431     return CK;
3432 
3433   //  -- the rank of S1 is better than the rank of S2 (by the rules
3434   //     defined below), or, if not that,
3435   ImplicitConversionRank Rank1 = SCS1.getRank();
3436   ImplicitConversionRank Rank2 = SCS2.getRank();
3437   if (Rank1 < Rank2)
3438     return ImplicitConversionSequence::Better;
3439   else if (Rank2 < Rank1)
3440     return ImplicitConversionSequence::Worse;
3441 
3442   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3443   // are indistinguishable unless one of the following rules
3444   // applies:
3445 
3446   //   A conversion that is not a conversion of a pointer, or
3447   //   pointer to member, to bool is better than another conversion
3448   //   that is such a conversion.
3449   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3450     return SCS2.isPointerConversionToBool()
3451              ? ImplicitConversionSequence::Better
3452              : ImplicitConversionSequence::Worse;
3453 
3454   // C++ [over.ics.rank]p4b2:
3455   //
3456   //   If class B is derived directly or indirectly from class A,
3457   //   conversion of B* to A* is better than conversion of B* to
3458   //   void*, and conversion of A* to void* is better than conversion
3459   //   of B* to void*.
3460   bool SCS1ConvertsToVoid
3461     = SCS1.isPointerConversionToVoidPointer(S.Context);
3462   bool SCS2ConvertsToVoid
3463     = SCS2.isPointerConversionToVoidPointer(S.Context);
3464   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3465     // Exactly one of the conversion sequences is a conversion to
3466     // a void pointer; it's the worse conversion.
3467     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3468                               : ImplicitConversionSequence::Worse;
3469   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3470     // Neither conversion sequence converts to a void pointer; compare
3471     // their derived-to-base conversions.
3472     if (ImplicitConversionSequence::CompareKind DerivedCK
3473           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3474       return DerivedCK;
3475   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3476              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3477     // Both conversion sequences are conversions to void
3478     // pointers. Compare the source types to determine if there's an
3479     // inheritance relationship in their sources.
3480     QualType FromType1 = SCS1.getFromType();
3481     QualType FromType2 = SCS2.getFromType();
3482 
3483     // Adjust the types we're converting from via the array-to-pointer
3484     // conversion, if we need to.
3485     if (SCS1.First == ICK_Array_To_Pointer)
3486       FromType1 = S.Context.getArrayDecayedType(FromType1);
3487     if (SCS2.First == ICK_Array_To_Pointer)
3488       FromType2 = S.Context.getArrayDecayedType(FromType2);
3489 
3490     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3491     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3492 
3493     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3494       return ImplicitConversionSequence::Better;
3495     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3496       return ImplicitConversionSequence::Worse;
3497 
3498     // Objective-C++: If one interface is more specific than the
3499     // other, it is the better one.
3500     const ObjCObjectPointerType* FromObjCPtr1
3501       = FromType1->getAs<ObjCObjectPointerType>();
3502     const ObjCObjectPointerType* FromObjCPtr2
3503       = FromType2->getAs<ObjCObjectPointerType>();
3504     if (FromObjCPtr1 && FromObjCPtr2) {
3505       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3506                                                           FromObjCPtr2);
3507       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3508                                                            FromObjCPtr1);
3509       if (AssignLeft != AssignRight) {
3510         return AssignLeft? ImplicitConversionSequence::Better
3511                          : ImplicitConversionSequence::Worse;
3512       }
3513     }
3514   }
3515 
3516   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3517   // bullet 3).
3518   if (ImplicitConversionSequence::CompareKind QualCK
3519         = CompareQualificationConversions(S, SCS1, SCS2))
3520     return QualCK;
3521 
3522   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3523     // Check for a better reference binding based on the kind of bindings.
3524     if (isBetterReferenceBindingKind(SCS1, SCS2))
3525       return ImplicitConversionSequence::Better;
3526     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3527       return ImplicitConversionSequence::Worse;
3528 
3529     // C++ [over.ics.rank]p3b4:
3530     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3531     //      which the references refer are the same type except for
3532     //      top-level cv-qualifiers, and the type to which the reference
3533     //      initialized by S2 refers is more cv-qualified than the type
3534     //      to which the reference initialized by S1 refers.
3535     QualType T1 = SCS1.getToType(2);
3536     QualType T2 = SCS2.getToType(2);
3537     T1 = S.Context.getCanonicalType(T1);
3538     T2 = S.Context.getCanonicalType(T2);
3539     Qualifiers T1Quals, T2Quals;
3540     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3541     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3542     if (UnqualT1 == UnqualT2) {
3543       // Objective-C++ ARC: If the references refer to objects with different
3544       // lifetimes, prefer bindings that don't change lifetime.
3545       if (SCS1.ObjCLifetimeConversionBinding !=
3546                                           SCS2.ObjCLifetimeConversionBinding) {
3547         return SCS1.ObjCLifetimeConversionBinding
3548                                            ? ImplicitConversionSequence::Worse
3549                                            : ImplicitConversionSequence::Better;
3550       }
3551 
3552       // If the type is an array type, promote the element qualifiers to the
3553       // type for comparison.
3554       if (isa<ArrayType>(T1) && T1Quals)
3555         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3556       if (isa<ArrayType>(T2) && T2Quals)
3557         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3558       if (T2.isMoreQualifiedThan(T1))
3559         return ImplicitConversionSequence::Better;
3560       else if (T1.isMoreQualifiedThan(T2))
3561         return ImplicitConversionSequence::Worse;
3562     }
3563   }
3564 
3565   // In Microsoft mode, prefer an integral conversion to a
3566   // floating-to-integral conversion if the integral conversion
3567   // is between types of the same size.
3568   // For example:
3569   // void f(float);
3570   // void f(int);
3571   // int main {
3572   //    long a;
3573   //    f(a);
3574   // }
3575   // Here, MSVC will call f(int) instead of generating a compile error
3576   // as clang will do in standard mode.
3577   if (S.getLangOpts().MicrosoftMode &&
3578       SCS1.Second == ICK_Integral_Conversion &&
3579       SCS2.Second == ICK_Floating_Integral &&
3580       S.Context.getTypeSize(SCS1.getFromType()) ==
3581       S.Context.getTypeSize(SCS1.getToType(2)))
3582     return ImplicitConversionSequence::Better;
3583 
3584   return ImplicitConversionSequence::Indistinguishable;
3585 }
3586 
3587 /// CompareQualificationConversions - Compares two standard conversion
3588 /// sequences to determine whether they can be ranked based on their
3589 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3590 ImplicitConversionSequence::CompareKind
3591 CompareQualificationConversions(Sema &S,
3592                                 const StandardConversionSequence& SCS1,
3593                                 const StandardConversionSequence& SCS2) {
3594   // C++ 13.3.3.2p3:
3595   //  -- S1 and S2 differ only in their qualification conversion and
3596   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3597   //     cv-qualification signature of type T1 is a proper subset of
3598   //     the cv-qualification signature of type T2, and S1 is not the
3599   //     deprecated string literal array-to-pointer conversion (4.2).
3600   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3601       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3602     return ImplicitConversionSequence::Indistinguishable;
3603 
3604   // FIXME: the example in the standard doesn't use a qualification
3605   // conversion (!)
3606   QualType T1 = SCS1.getToType(2);
3607   QualType T2 = SCS2.getToType(2);
3608   T1 = S.Context.getCanonicalType(T1);
3609   T2 = S.Context.getCanonicalType(T2);
3610   Qualifiers T1Quals, T2Quals;
3611   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3612   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3613 
3614   // If the types are the same, we won't learn anything by unwrapped
3615   // them.
3616   if (UnqualT1 == UnqualT2)
3617     return ImplicitConversionSequence::Indistinguishable;
3618 
3619   // If the type is an array type, promote the element qualifiers to the type
3620   // for comparison.
3621   if (isa<ArrayType>(T1) && T1Quals)
3622     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3623   if (isa<ArrayType>(T2) && T2Quals)
3624     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3625 
3626   ImplicitConversionSequence::CompareKind Result
3627     = ImplicitConversionSequence::Indistinguishable;
3628 
3629   // Objective-C++ ARC:
3630   //   Prefer qualification conversions not involving a change in lifetime
3631   //   to qualification conversions that do not change lifetime.
3632   if (SCS1.QualificationIncludesObjCLifetime !=
3633                                       SCS2.QualificationIncludesObjCLifetime) {
3634     Result = SCS1.QualificationIncludesObjCLifetime
3635                ? ImplicitConversionSequence::Worse
3636                : ImplicitConversionSequence::Better;
3637   }
3638 
3639   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3640     // Within each iteration of the loop, we check the qualifiers to
3641     // determine if this still looks like a qualification
3642     // conversion. Then, if all is well, we unwrap one more level of
3643     // pointers or pointers-to-members and do it all again
3644     // until there are no more pointers or pointers-to-members left
3645     // to unwrap. This essentially mimics what
3646     // IsQualificationConversion does, but here we're checking for a
3647     // strict subset of qualifiers.
3648     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3649       // The qualifiers are the same, so this doesn't tell us anything
3650       // about how the sequences rank.
3651       ;
3652     else if (T2.isMoreQualifiedThan(T1)) {
3653       // T1 has fewer qualifiers, so it could be the better sequence.
3654       if (Result == ImplicitConversionSequence::Worse)
3655         // Neither has qualifiers that are a subset of the other's
3656         // qualifiers.
3657         return ImplicitConversionSequence::Indistinguishable;
3658 
3659       Result = ImplicitConversionSequence::Better;
3660     } else if (T1.isMoreQualifiedThan(T2)) {
3661       // T2 has fewer qualifiers, so it could be the better sequence.
3662       if (Result == ImplicitConversionSequence::Better)
3663         // Neither has qualifiers that are a subset of the other's
3664         // qualifiers.
3665         return ImplicitConversionSequence::Indistinguishable;
3666 
3667       Result = ImplicitConversionSequence::Worse;
3668     } else {
3669       // Qualifiers are disjoint.
3670       return ImplicitConversionSequence::Indistinguishable;
3671     }
3672 
3673     // If the types after this point are equivalent, we're done.
3674     if (S.Context.hasSameUnqualifiedType(T1, T2))
3675       break;
3676   }
3677 
3678   // Check that the winning standard conversion sequence isn't using
3679   // the deprecated string literal array to pointer conversion.
3680   switch (Result) {
3681   case ImplicitConversionSequence::Better:
3682     if (SCS1.DeprecatedStringLiteralToCharPtr)
3683       Result = ImplicitConversionSequence::Indistinguishable;
3684     break;
3685 
3686   case ImplicitConversionSequence::Indistinguishable:
3687     break;
3688 
3689   case ImplicitConversionSequence::Worse:
3690     if (SCS2.DeprecatedStringLiteralToCharPtr)
3691       Result = ImplicitConversionSequence::Indistinguishable;
3692     break;
3693   }
3694 
3695   return Result;
3696 }
3697 
3698 /// CompareDerivedToBaseConversions - Compares two standard conversion
3699 /// sequences to determine whether they can be ranked based on their
3700 /// various kinds of derived-to-base conversions (C++
3701 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3702 /// conversions between Objective-C interface types.
3703 ImplicitConversionSequence::CompareKind
3704 CompareDerivedToBaseConversions(Sema &S,
3705                                 const StandardConversionSequence& SCS1,
3706                                 const StandardConversionSequence& SCS2) {
3707   QualType FromType1 = SCS1.getFromType();
3708   QualType ToType1 = SCS1.getToType(1);
3709   QualType FromType2 = SCS2.getFromType();
3710   QualType ToType2 = SCS2.getToType(1);
3711 
3712   // Adjust the types we're converting from via the array-to-pointer
3713   // conversion, if we need to.
3714   if (SCS1.First == ICK_Array_To_Pointer)
3715     FromType1 = S.Context.getArrayDecayedType(FromType1);
3716   if (SCS2.First == ICK_Array_To_Pointer)
3717     FromType2 = S.Context.getArrayDecayedType(FromType2);
3718 
3719   // Canonicalize all of the types.
3720   FromType1 = S.Context.getCanonicalType(FromType1);
3721   ToType1 = S.Context.getCanonicalType(ToType1);
3722   FromType2 = S.Context.getCanonicalType(FromType2);
3723   ToType2 = S.Context.getCanonicalType(ToType2);
3724 
3725   // C++ [over.ics.rank]p4b3:
3726   //
3727   //   If class B is derived directly or indirectly from class A and
3728   //   class C is derived directly or indirectly from B,
3729   //
3730   // Compare based on pointer conversions.
3731   if (SCS1.Second == ICK_Pointer_Conversion &&
3732       SCS2.Second == ICK_Pointer_Conversion &&
3733       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3734       FromType1->isPointerType() && FromType2->isPointerType() &&
3735       ToType1->isPointerType() && ToType2->isPointerType()) {
3736     QualType FromPointee1
3737       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3738     QualType ToPointee1
3739       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3740     QualType FromPointee2
3741       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3742     QualType ToPointee2
3743       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3744 
3745     //   -- conversion of C* to B* is better than conversion of C* to A*,
3746     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3747       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3748         return ImplicitConversionSequence::Better;
3749       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3750         return ImplicitConversionSequence::Worse;
3751     }
3752 
3753     //   -- conversion of B* to A* is better than conversion of C* to A*,
3754     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3755       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3756         return ImplicitConversionSequence::Better;
3757       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3758         return ImplicitConversionSequence::Worse;
3759     }
3760   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3761              SCS2.Second == ICK_Pointer_Conversion) {
3762     const ObjCObjectPointerType *FromPtr1
3763       = FromType1->getAs<ObjCObjectPointerType>();
3764     const ObjCObjectPointerType *FromPtr2
3765       = FromType2->getAs<ObjCObjectPointerType>();
3766     const ObjCObjectPointerType *ToPtr1
3767       = ToType1->getAs<ObjCObjectPointerType>();
3768     const ObjCObjectPointerType *ToPtr2
3769       = ToType2->getAs<ObjCObjectPointerType>();
3770 
3771     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3772       // Apply the same conversion ranking rules for Objective-C pointer types
3773       // that we do for C++ pointers to class types. However, we employ the
3774       // Objective-C pseudo-subtyping relationship used for assignment of
3775       // Objective-C pointer types.
3776       bool FromAssignLeft
3777         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3778       bool FromAssignRight
3779         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3780       bool ToAssignLeft
3781         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3782       bool ToAssignRight
3783         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3784 
3785       // A conversion to an a non-id object pointer type or qualified 'id'
3786       // type is better than a conversion to 'id'.
3787       if (ToPtr1->isObjCIdType() &&
3788           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3789         return ImplicitConversionSequence::Worse;
3790       if (ToPtr2->isObjCIdType() &&
3791           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3792         return ImplicitConversionSequence::Better;
3793 
3794       // A conversion to a non-id object pointer type is better than a
3795       // conversion to a qualified 'id' type
3796       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3797         return ImplicitConversionSequence::Worse;
3798       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3799         return ImplicitConversionSequence::Better;
3800 
3801       // A conversion to an a non-Class object pointer type or qualified 'Class'
3802       // type is better than a conversion to 'Class'.
3803       if (ToPtr1->isObjCClassType() &&
3804           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3805         return ImplicitConversionSequence::Worse;
3806       if (ToPtr2->isObjCClassType() &&
3807           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3808         return ImplicitConversionSequence::Better;
3809 
3810       // A conversion to a non-Class object pointer type is better than a
3811       // conversion to a qualified 'Class' type.
3812       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3813         return ImplicitConversionSequence::Worse;
3814       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3815         return ImplicitConversionSequence::Better;
3816 
3817       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3818       if (S.Context.hasSameType(FromType1, FromType2) &&
3819           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3820           (ToAssignLeft != ToAssignRight))
3821         return ToAssignLeft? ImplicitConversionSequence::Worse
3822                            : ImplicitConversionSequence::Better;
3823 
3824       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3825       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3826           (FromAssignLeft != FromAssignRight))
3827         return FromAssignLeft? ImplicitConversionSequence::Better
3828         : ImplicitConversionSequence::Worse;
3829     }
3830   }
3831 
3832   // Ranking of member-pointer types.
3833   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3834       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3835       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3836     const MemberPointerType * FromMemPointer1 =
3837                                         FromType1->getAs<MemberPointerType>();
3838     const MemberPointerType * ToMemPointer1 =
3839                                           ToType1->getAs<MemberPointerType>();
3840     const MemberPointerType * FromMemPointer2 =
3841                                           FromType2->getAs<MemberPointerType>();
3842     const MemberPointerType * ToMemPointer2 =
3843                                           ToType2->getAs<MemberPointerType>();
3844     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3845     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3846     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3847     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3848     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3849     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3850     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3851     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3852     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3853     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3854       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3855         return ImplicitConversionSequence::Worse;
3856       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3857         return ImplicitConversionSequence::Better;
3858     }
3859     // conversion of B::* to C::* is better than conversion of A::* to C::*
3860     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3861       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3862         return ImplicitConversionSequence::Better;
3863       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3864         return ImplicitConversionSequence::Worse;
3865     }
3866   }
3867 
3868   if (SCS1.Second == ICK_Derived_To_Base) {
3869     //   -- conversion of C to B is better than conversion of C to A,
3870     //   -- binding of an expression of type C to a reference of type
3871     //      B& is better than binding an expression of type C to a
3872     //      reference of type A&,
3873     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3874         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3875       if (S.IsDerivedFrom(ToType1, ToType2))
3876         return ImplicitConversionSequence::Better;
3877       else if (S.IsDerivedFrom(ToType2, ToType1))
3878         return ImplicitConversionSequence::Worse;
3879     }
3880 
3881     //   -- conversion of B to A is better than conversion of C to A.
3882     //   -- binding of an expression of type B to a reference of type
3883     //      A& is better than binding an expression of type C to a
3884     //      reference of type A&,
3885     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3886         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3887       if (S.IsDerivedFrom(FromType2, FromType1))
3888         return ImplicitConversionSequence::Better;
3889       else if (S.IsDerivedFrom(FromType1, FromType2))
3890         return ImplicitConversionSequence::Worse;
3891     }
3892   }
3893 
3894   return ImplicitConversionSequence::Indistinguishable;
3895 }
3896 
3897 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3898 /// C++ class.
3899 static bool isTypeValid(QualType T) {
3900   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3901     return !Record->isInvalidDecl();
3902 
3903   return true;
3904 }
3905 
3906 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3907 /// determine whether they are reference-related,
3908 /// reference-compatible, reference-compatible with added
3909 /// qualification, or incompatible, for use in C++ initialization by
3910 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3911 /// type, and the first type (T1) is the pointee type of the reference
3912 /// type being initialized.
3913 Sema::ReferenceCompareResult
3914 Sema::CompareReferenceRelationship(SourceLocation Loc,
3915                                    QualType OrigT1, QualType OrigT2,
3916                                    bool &DerivedToBase,
3917                                    bool &ObjCConversion,
3918                                    bool &ObjCLifetimeConversion) {
3919   assert(!OrigT1->isReferenceType() &&
3920     "T1 must be the pointee type of the reference type");
3921   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3922 
3923   QualType T1 = Context.getCanonicalType(OrigT1);
3924   QualType T2 = Context.getCanonicalType(OrigT2);
3925   Qualifiers T1Quals, T2Quals;
3926   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3927   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3928 
3929   // C++ [dcl.init.ref]p4:
3930   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3931   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3932   //   T1 is a base class of T2.
3933   DerivedToBase = false;
3934   ObjCConversion = false;
3935   ObjCLifetimeConversion = false;
3936   if (UnqualT1 == UnqualT2) {
3937     // Nothing to do.
3938   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3939              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3940              IsDerivedFrom(UnqualT2, UnqualT1))
3941     DerivedToBase = true;
3942   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3943            UnqualT2->isObjCObjectOrInterfaceType() &&
3944            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3945     ObjCConversion = true;
3946   else
3947     return Ref_Incompatible;
3948 
3949   // At this point, we know that T1 and T2 are reference-related (at
3950   // least).
3951 
3952   // If the type is an array type, promote the element qualifiers to the type
3953   // for comparison.
3954   if (isa<ArrayType>(T1) && T1Quals)
3955     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3956   if (isa<ArrayType>(T2) && T2Quals)
3957     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3958 
3959   // C++ [dcl.init.ref]p4:
3960   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3961   //   reference-related to T2 and cv1 is the same cv-qualification
3962   //   as, or greater cv-qualification than, cv2. For purposes of
3963   //   overload resolution, cases for which cv1 is greater
3964   //   cv-qualification than cv2 are identified as
3965   //   reference-compatible with added qualification (see 13.3.3.2).
3966   //
3967   // Note that we also require equivalence of Objective-C GC and address-space
3968   // qualifiers when performing these computations, so that e.g., an int in
3969   // address space 1 is not reference-compatible with an int in address
3970   // space 2.
3971   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3972       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3973     T1Quals.removeObjCLifetime();
3974     T2Quals.removeObjCLifetime();
3975     ObjCLifetimeConversion = true;
3976   }
3977 
3978   if (T1Quals == T2Quals)
3979     return Ref_Compatible;
3980   else if (T1Quals.compatiblyIncludes(T2Quals))
3981     return Ref_Compatible_With_Added_Qualification;
3982   else
3983     return Ref_Related;
3984 }
3985 
3986 /// \brief Look for a user-defined conversion to an value reference-compatible
3987 ///        with DeclType. Return true if something definite is found.
3988 static bool
3989 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3990                          QualType DeclType, SourceLocation DeclLoc,
3991                          Expr *Init, QualType T2, bool AllowRvalues,
3992                          bool AllowExplicit) {
3993   assert(T2->isRecordType() && "Can only find conversions of record types.");
3994   CXXRecordDecl *T2RecordDecl
3995     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3996 
3997   OverloadCandidateSet CandidateSet(DeclLoc);
3998   std::pair<CXXRecordDecl::conversion_iterator,
3999             CXXRecordDecl::conversion_iterator>
4000     Conversions = T2RecordDecl->getVisibleConversionFunctions();
4001   for (CXXRecordDecl::conversion_iterator
4002          I = Conversions.first, E = Conversions.second; I != E; ++I) {
4003     NamedDecl *D = *I;
4004     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4005     if (isa<UsingShadowDecl>(D))
4006       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4007 
4008     FunctionTemplateDecl *ConvTemplate
4009       = dyn_cast<FunctionTemplateDecl>(D);
4010     CXXConversionDecl *Conv;
4011     if (ConvTemplate)
4012       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4013     else
4014       Conv = cast<CXXConversionDecl>(D);
4015 
4016     // If this is an explicit conversion, and we're not allowed to consider
4017     // explicit conversions, skip it.
4018     if (!AllowExplicit && Conv->isExplicit())
4019       continue;
4020 
4021     if (AllowRvalues) {
4022       bool DerivedToBase = false;
4023       bool ObjCConversion = false;
4024       bool ObjCLifetimeConversion = false;
4025 
4026       // If we are initializing an rvalue reference, don't permit conversion
4027       // functions that return lvalues.
4028       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4029         const ReferenceType *RefType
4030           = Conv->getConversionType()->getAs<LValueReferenceType>();
4031         if (RefType && !RefType->getPointeeType()->isFunctionType())
4032           continue;
4033       }
4034 
4035       if (!ConvTemplate &&
4036           S.CompareReferenceRelationship(
4037             DeclLoc,
4038             Conv->getConversionType().getNonReferenceType()
4039               .getUnqualifiedType(),
4040             DeclType.getNonReferenceType().getUnqualifiedType(),
4041             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4042           Sema::Ref_Incompatible)
4043         continue;
4044     } else {
4045       // If the conversion function doesn't return a reference type,
4046       // it can't be considered for this conversion. An rvalue reference
4047       // is only acceptable if its referencee is a function type.
4048 
4049       const ReferenceType *RefType =
4050         Conv->getConversionType()->getAs<ReferenceType>();
4051       if (!RefType ||
4052           (!RefType->isLValueReferenceType() &&
4053            !RefType->getPointeeType()->isFunctionType()))
4054         continue;
4055     }
4056 
4057     if (ConvTemplate)
4058       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4059                                        Init, DeclType, CandidateSet);
4060     else
4061       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4062                                DeclType, CandidateSet);
4063   }
4064 
4065   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4066 
4067   OverloadCandidateSet::iterator Best;
4068   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4069   case OR_Success:
4070     // C++ [over.ics.ref]p1:
4071     //
4072     //   [...] If the parameter binds directly to the result of
4073     //   applying a conversion function to the argument
4074     //   expression, the implicit conversion sequence is a
4075     //   user-defined conversion sequence (13.3.3.1.2), with the
4076     //   second standard conversion sequence either an identity
4077     //   conversion or, if the conversion function returns an
4078     //   entity of a type that is a derived class of the parameter
4079     //   type, a derived-to-base Conversion.
4080     if (!Best->FinalConversion.DirectBinding)
4081       return false;
4082 
4083     ICS.setUserDefined();
4084     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4085     ICS.UserDefined.After = Best->FinalConversion;
4086     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4087     ICS.UserDefined.ConversionFunction = Best->Function;
4088     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4089     ICS.UserDefined.EllipsisConversion = false;
4090     assert(ICS.UserDefined.After.ReferenceBinding &&
4091            ICS.UserDefined.After.DirectBinding &&
4092            "Expected a direct reference binding!");
4093     return true;
4094 
4095   case OR_Ambiguous:
4096     ICS.setAmbiguous();
4097     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4098          Cand != CandidateSet.end(); ++Cand)
4099       if (Cand->Viable)
4100         ICS.Ambiguous.addConversion(Cand->Function);
4101     return true;
4102 
4103   case OR_No_Viable_Function:
4104   case OR_Deleted:
4105     // There was no suitable conversion, or we found a deleted
4106     // conversion; continue with other checks.
4107     return false;
4108   }
4109 
4110   llvm_unreachable("Invalid OverloadResult!");
4111 }
4112 
4113 /// \brief Compute an implicit conversion sequence for reference
4114 /// initialization.
4115 static ImplicitConversionSequence
4116 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4117                  SourceLocation DeclLoc,
4118                  bool SuppressUserConversions,
4119                  bool AllowExplicit) {
4120   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4121 
4122   // Most paths end in a failed conversion.
4123   ImplicitConversionSequence ICS;
4124   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4125 
4126   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4127   QualType T2 = Init->getType();
4128 
4129   // If the initializer is the address of an overloaded function, try
4130   // to resolve the overloaded function. If all goes well, T2 is the
4131   // type of the resulting function.
4132   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4133     DeclAccessPair Found;
4134     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4135                                                                 false, Found))
4136       T2 = Fn->getType();
4137   }
4138 
4139   // Compute some basic properties of the types and the initializer.
4140   bool isRValRef = DeclType->isRValueReferenceType();
4141   bool DerivedToBase = false;
4142   bool ObjCConversion = false;
4143   bool ObjCLifetimeConversion = false;
4144   Expr::Classification InitCategory = Init->Classify(S.Context);
4145   Sema::ReferenceCompareResult RefRelationship
4146     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4147                                      ObjCConversion, ObjCLifetimeConversion);
4148 
4149 
4150   // C++0x [dcl.init.ref]p5:
4151   //   A reference to type "cv1 T1" is initialized by an expression
4152   //   of type "cv2 T2" as follows:
4153 
4154   //     -- If reference is an lvalue reference and the initializer expression
4155   if (!isRValRef) {
4156     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4157     //        reference-compatible with "cv2 T2," or
4158     //
4159     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4160     if (InitCategory.isLValue() &&
4161         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4162       // C++ [over.ics.ref]p1:
4163       //   When a parameter of reference type binds directly (8.5.3)
4164       //   to an argument expression, the implicit conversion sequence
4165       //   is the identity conversion, unless the argument expression
4166       //   has a type that is a derived class of the parameter type,
4167       //   in which case the implicit conversion sequence is a
4168       //   derived-to-base Conversion (13.3.3.1).
4169       ICS.setStandard();
4170       ICS.Standard.First = ICK_Identity;
4171       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4172                          : ObjCConversion? ICK_Compatible_Conversion
4173                          : ICK_Identity;
4174       ICS.Standard.Third = ICK_Identity;
4175       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4176       ICS.Standard.setToType(0, T2);
4177       ICS.Standard.setToType(1, T1);
4178       ICS.Standard.setToType(2, T1);
4179       ICS.Standard.ReferenceBinding = true;
4180       ICS.Standard.DirectBinding = true;
4181       ICS.Standard.IsLvalueReference = !isRValRef;
4182       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4183       ICS.Standard.BindsToRvalue = false;
4184       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4185       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4186       ICS.Standard.CopyConstructor = 0;
4187 
4188       // Nothing more to do: the inaccessibility/ambiguity check for
4189       // derived-to-base conversions is suppressed when we're
4190       // computing the implicit conversion sequence (C++
4191       // [over.best.ics]p2).
4192       return ICS;
4193     }
4194 
4195     //       -- has a class type (i.e., T2 is a class type), where T1 is
4196     //          not reference-related to T2, and can be implicitly
4197     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4198     //          is reference-compatible with "cv3 T3" 92) (this
4199     //          conversion is selected by enumerating the applicable
4200     //          conversion functions (13.3.1.6) and choosing the best
4201     //          one through overload resolution (13.3)),
4202     if (!SuppressUserConversions && T2->isRecordType() &&
4203         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4204         RefRelationship == Sema::Ref_Incompatible) {
4205       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4206                                    Init, T2, /*AllowRvalues=*/false,
4207                                    AllowExplicit))
4208         return ICS;
4209     }
4210   }
4211 
4212   //     -- Otherwise, the reference shall be an lvalue reference to a
4213   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4214   //        shall be an rvalue reference.
4215   //
4216   // We actually handle one oddity of C++ [over.ics.ref] at this
4217   // point, which is that, due to p2 (which short-circuits reference
4218   // binding by only attempting a simple conversion for non-direct
4219   // bindings) and p3's strange wording, we allow a const volatile
4220   // reference to bind to an rvalue. Hence the check for the presence
4221   // of "const" rather than checking for "const" being the only
4222   // qualifier.
4223   // This is also the point where rvalue references and lvalue inits no longer
4224   // go together.
4225   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4226     return ICS;
4227 
4228   //       -- If the initializer expression
4229   //
4230   //            -- is an xvalue, class prvalue, array prvalue or function
4231   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4232   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4233       (InitCategory.isXValue() ||
4234       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4235       (InitCategory.isLValue() && T2->isFunctionType()))) {
4236     ICS.setStandard();
4237     ICS.Standard.First = ICK_Identity;
4238     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4239                       : ObjCConversion? ICK_Compatible_Conversion
4240                       : ICK_Identity;
4241     ICS.Standard.Third = ICK_Identity;
4242     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4243     ICS.Standard.setToType(0, T2);
4244     ICS.Standard.setToType(1, T1);
4245     ICS.Standard.setToType(2, T1);
4246     ICS.Standard.ReferenceBinding = true;
4247     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4248     // binding unless we're binding to a class prvalue.
4249     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4250     // allow the use of rvalue references in C++98/03 for the benefit of
4251     // standard library implementors; therefore, we need the xvalue check here.
4252     ICS.Standard.DirectBinding =
4253       S.getLangOpts().CPlusPlus11 ||
4254       (InitCategory.isPRValue() && !T2->isRecordType());
4255     ICS.Standard.IsLvalueReference = !isRValRef;
4256     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4257     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4258     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4259     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4260     ICS.Standard.CopyConstructor = 0;
4261     return ICS;
4262   }
4263 
4264   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4265   //               reference-related to T2, and can be implicitly converted to
4266   //               an xvalue, class prvalue, or function lvalue of type
4267   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4268   //               "cv3 T3",
4269   //
4270   //          then the reference is bound to the value of the initializer
4271   //          expression in the first case and to the result of the conversion
4272   //          in the second case (or, in either case, to an appropriate base
4273   //          class subobject).
4274   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4275       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4276       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4277                                Init, T2, /*AllowRvalues=*/true,
4278                                AllowExplicit)) {
4279     // In the second case, if the reference is an rvalue reference
4280     // and the second standard conversion sequence of the
4281     // user-defined conversion sequence includes an lvalue-to-rvalue
4282     // conversion, the program is ill-formed.
4283     if (ICS.isUserDefined() && isRValRef &&
4284         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4285       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4286 
4287     return ICS;
4288   }
4289 
4290   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4291   //          initialized from the initializer expression using the
4292   //          rules for a non-reference copy initialization (8.5). The
4293   //          reference is then bound to the temporary. If T1 is
4294   //          reference-related to T2, cv1 must be the same
4295   //          cv-qualification as, or greater cv-qualification than,
4296   //          cv2; otherwise, the program is ill-formed.
4297   if (RefRelationship == Sema::Ref_Related) {
4298     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4299     // we would be reference-compatible or reference-compatible with
4300     // added qualification. But that wasn't the case, so the reference
4301     // initialization fails.
4302     //
4303     // Note that we only want to check address spaces and cvr-qualifiers here.
4304     // ObjC GC and lifetime qualifiers aren't important.
4305     Qualifiers T1Quals = T1.getQualifiers();
4306     Qualifiers T2Quals = T2.getQualifiers();
4307     T1Quals.removeObjCGCAttr();
4308     T1Quals.removeObjCLifetime();
4309     T2Quals.removeObjCGCAttr();
4310     T2Quals.removeObjCLifetime();
4311     if (!T1Quals.compatiblyIncludes(T2Quals))
4312       return ICS;
4313   }
4314 
4315   // If at least one of the types is a class type, the types are not
4316   // related, and we aren't allowed any user conversions, the
4317   // reference binding fails. This case is important for breaking
4318   // recursion, since TryImplicitConversion below will attempt to
4319   // create a temporary through the use of a copy constructor.
4320   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4321       (T1->isRecordType() || T2->isRecordType()))
4322     return ICS;
4323 
4324   // If T1 is reference-related to T2 and the reference is an rvalue
4325   // reference, the initializer expression shall not be an lvalue.
4326   if (RefRelationship >= Sema::Ref_Related &&
4327       isRValRef && Init->Classify(S.Context).isLValue())
4328     return ICS;
4329 
4330   // C++ [over.ics.ref]p2:
4331   //   When a parameter of reference type is not bound directly to
4332   //   an argument expression, the conversion sequence is the one
4333   //   required to convert the argument expression to the
4334   //   underlying type of the reference according to
4335   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4336   //   to copy-initializing a temporary of the underlying type with
4337   //   the argument expression. Any difference in top-level
4338   //   cv-qualification is subsumed by the initialization itself
4339   //   and does not constitute a conversion.
4340   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4341                               /*AllowExplicit=*/false,
4342                               /*InOverloadResolution=*/false,
4343                               /*CStyle=*/false,
4344                               /*AllowObjCWritebackConversion=*/false);
4345 
4346   // Of course, that's still a reference binding.
4347   if (ICS.isStandard()) {
4348     ICS.Standard.ReferenceBinding = true;
4349     ICS.Standard.IsLvalueReference = !isRValRef;
4350     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4351     ICS.Standard.BindsToRvalue = true;
4352     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4353     ICS.Standard.ObjCLifetimeConversionBinding = false;
4354   } else if (ICS.isUserDefined()) {
4355     // Don't allow rvalue references to bind to lvalues.
4356     if (DeclType->isRValueReferenceType()) {
4357       if (const ReferenceType *RefType
4358             = ICS.UserDefined.ConversionFunction->getResultType()
4359                 ->getAs<LValueReferenceType>()) {
4360         if (!RefType->getPointeeType()->isFunctionType()) {
4361           ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4362                      DeclType);
4363           return ICS;
4364         }
4365       }
4366     }
4367 
4368     ICS.UserDefined.After.ReferenceBinding = true;
4369     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4370     ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4371     ICS.UserDefined.After.BindsToRvalue = true;
4372     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4373     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4374   }
4375 
4376   return ICS;
4377 }
4378 
4379 static ImplicitConversionSequence
4380 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4381                       bool SuppressUserConversions,
4382                       bool InOverloadResolution,
4383                       bool AllowObjCWritebackConversion,
4384                       bool AllowExplicit = false);
4385 
4386 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4387 /// initializer list From.
4388 static ImplicitConversionSequence
4389 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4390                   bool SuppressUserConversions,
4391                   bool InOverloadResolution,
4392                   bool AllowObjCWritebackConversion) {
4393   // C++11 [over.ics.list]p1:
4394   //   When an argument is an initializer list, it is not an expression and
4395   //   special rules apply for converting it to a parameter type.
4396 
4397   ImplicitConversionSequence Result;
4398   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4399   Result.setListInitializationSequence();
4400 
4401   // We need a complete type for what follows. Incomplete types can never be
4402   // initialized from init lists.
4403   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4404     return Result;
4405 
4406   // C++11 [over.ics.list]p2:
4407   //   If the parameter type is std::initializer_list<X> or "array of X" and
4408   //   all the elements can be implicitly converted to X, the implicit
4409   //   conversion sequence is the worst conversion necessary to convert an
4410   //   element of the list to X.
4411   bool toStdInitializerList = false;
4412   QualType X;
4413   if (ToType->isArrayType())
4414     X = S.Context.getAsArrayType(ToType)->getElementType();
4415   else
4416     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4417   if (!X.isNull()) {
4418     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4419       Expr *Init = From->getInit(i);
4420       ImplicitConversionSequence ICS =
4421           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4422                                 InOverloadResolution,
4423                                 AllowObjCWritebackConversion);
4424       // If a single element isn't convertible, fail.
4425       if (ICS.isBad()) {
4426         Result = ICS;
4427         break;
4428       }
4429       // Otherwise, look for the worst conversion.
4430       if (Result.isBad() ||
4431           CompareImplicitConversionSequences(S, ICS, Result) ==
4432               ImplicitConversionSequence::Worse)
4433         Result = ICS;
4434     }
4435 
4436     // For an empty list, we won't have computed any conversion sequence.
4437     // Introduce the identity conversion sequence.
4438     if (From->getNumInits() == 0) {
4439       Result.setStandard();
4440       Result.Standard.setAsIdentityConversion();
4441       Result.Standard.setFromType(ToType);
4442       Result.Standard.setAllToTypes(ToType);
4443     }
4444 
4445     Result.setListInitializationSequence();
4446     Result.setStdInitializerListElement(toStdInitializerList);
4447     return Result;
4448   }
4449 
4450   // C++11 [over.ics.list]p3:
4451   //   Otherwise, if the parameter is a non-aggregate class X and overload
4452   //   resolution chooses a single best constructor [...] the implicit
4453   //   conversion sequence is a user-defined conversion sequence. If multiple
4454   //   constructors are viable but none is better than the others, the
4455   //   implicit conversion sequence is a user-defined conversion sequence.
4456   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4457     // This function can deal with initializer lists.
4458     Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4459                                       /*AllowExplicit=*/false,
4460                                       InOverloadResolution, /*CStyle=*/false,
4461                                       AllowObjCWritebackConversion);
4462     Result.setListInitializationSequence();
4463     return Result;
4464   }
4465 
4466   // C++11 [over.ics.list]p4:
4467   //   Otherwise, if the parameter has an aggregate type which can be
4468   //   initialized from the initializer list [...] the implicit conversion
4469   //   sequence is a user-defined conversion sequence.
4470   if (ToType->isAggregateType()) {
4471     // Type is an aggregate, argument is an init list. At this point it comes
4472     // down to checking whether the initialization works.
4473     // FIXME: Find out whether this parameter is consumed or not.
4474     InitializedEntity Entity =
4475         InitializedEntity::InitializeParameter(S.Context, ToType,
4476                                                /*Consumed=*/false);
4477     if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4478       Result.setUserDefined();
4479       Result.UserDefined.Before.setAsIdentityConversion();
4480       // Initializer lists don't have a type.
4481       Result.UserDefined.Before.setFromType(QualType());
4482       Result.UserDefined.Before.setAllToTypes(QualType());
4483 
4484       Result.UserDefined.After.setAsIdentityConversion();
4485       Result.UserDefined.After.setFromType(ToType);
4486       Result.UserDefined.After.setAllToTypes(ToType);
4487       Result.UserDefined.ConversionFunction = 0;
4488     }
4489     return Result;
4490   }
4491 
4492   // C++11 [over.ics.list]p5:
4493   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4494   if (ToType->isReferenceType()) {
4495     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4496     // mention initializer lists in any way. So we go by what list-
4497     // initialization would do and try to extrapolate from that.
4498 
4499     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4500 
4501     // If the initializer list has a single element that is reference-related
4502     // to the parameter type, we initialize the reference from that.
4503     if (From->getNumInits() == 1) {
4504       Expr *Init = From->getInit(0);
4505 
4506       QualType T2 = Init->getType();
4507 
4508       // If the initializer is the address of an overloaded function, try
4509       // to resolve the overloaded function. If all goes well, T2 is the
4510       // type of the resulting function.
4511       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4512         DeclAccessPair Found;
4513         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4514                                    Init, ToType, false, Found))
4515           T2 = Fn->getType();
4516       }
4517 
4518       // Compute some basic properties of the types and the initializer.
4519       bool dummy1 = false;
4520       bool dummy2 = false;
4521       bool dummy3 = false;
4522       Sema::ReferenceCompareResult RefRelationship
4523         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4524                                          dummy2, dummy3);
4525 
4526       if (RefRelationship >= Sema::Ref_Related)
4527         return TryReferenceInit(S, Init, ToType,
4528                                 /*FIXME:*/From->getLocStart(),
4529                                 SuppressUserConversions,
4530                                 /*AllowExplicit=*/false);
4531     }
4532 
4533     // Otherwise, we bind the reference to a temporary created from the
4534     // initializer list.
4535     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4536                                InOverloadResolution,
4537                                AllowObjCWritebackConversion);
4538     if (Result.isFailure())
4539       return Result;
4540     assert(!Result.isEllipsis() &&
4541            "Sub-initialization cannot result in ellipsis conversion.");
4542 
4543     // Can we even bind to a temporary?
4544     if (ToType->isRValueReferenceType() ||
4545         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4546       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4547                                             Result.UserDefined.After;
4548       SCS.ReferenceBinding = true;
4549       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4550       SCS.BindsToRvalue = true;
4551       SCS.BindsToFunctionLvalue = false;
4552       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4553       SCS.ObjCLifetimeConversionBinding = false;
4554     } else
4555       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4556                     From, ToType);
4557     return Result;
4558   }
4559 
4560   // C++11 [over.ics.list]p6:
4561   //   Otherwise, if the parameter type is not a class:
4562   if (!ToType->isRecordType()) {
4563     //    - if the initializer list has one element, the implicit conversion
4564     //      sequence is the one required to convert the element to the
4565     //      parameter type.
4566     unsigned NumInits = From->getNumInits();
4567     if (NumInits == 1)
4568       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4569                                      SuppressUserConversions,
4570                                      InOverloadResolution,
4571                                      AllowObjCWritebackConversion);
4572     //    - if the initializer list has no elements, the implicit conversion
4573     //      sequence is the identity conversion.
4574     else if (NumInits == 0) {
4575       Result.setStandard();
4576       Result.Standard.setAsIdentityConversion();
4577       Result.Standard.setFromType(ToType);
4578       Result.Standard.setAllToTypes(ToType);
4579     }
4580     Result.setListInitializationSequence();
4581     return Result;
4582   }
4583 
4584   // C++11 [over.ics.list]p7:
4585   //   In all cases other than those enumerated above, no conversion is possible
4586   return Result;
4587 }
4588 
4589 /// TryCopyInitialization - Try to copy-initialize a value of type
4590 /// ToType from the expression From. Return the implicit conversion
4591 /// sequence required to pass this argument, which may be a bad
4592 /// conversion sequence (meaning that the argument cannot be passed to
4593 /// a parameter of this type). If @p SuppressUserConversions, then we
4594 /// do not permit any user-defined conversion sequences.
4595 static ImplicitConversionSequence
4596 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4597                       bool SuppressUserConversions,
4598                       bool InOverloadResolution,
4599                       bool AllowObjCWritebackConversion,
4600                       bool AllowExplicit) {
4601   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4602     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4603                              InOverloadResolution,AllowObjCWritebackConversion);
4604 
4605   if (ToType->isReferenceType())
4606     return TryReferenceInit(S, From, ToType,
4607                             /*FIXME:*/From->getLocStart(),
4608                             SuppressUserConversions,
4609                             AllowExplicit);
4610 
4611   return TryImplicitConversion(S, From, ToType,
4612                                SuppressUserConversions,
4613                                /*AllowExplicit=*/false,
4614                                InOverloadResolution,
4615                                /*CStyle=*/false,
4616                                AllowObjCWritebackConversion);
4617 }
4618 
4619 static bool TryCopyInitialization(const CanQualType FromQTy,
4620                                   const CanQualType ToQTy,
4621                                   Sema &S,
4622                                   SourceLocation Loc,
4623                                   ExprValueKind FromVK) {
4624   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4625   ImplicitConversionSequence ICS =
4626     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4627 
4628   return !ICS.isBad();
4629 }
4630 
4631 /// TryObjectArgumentInitialization - Try to initialize the object
4632 /// parameter of the given member function (@c Method) from the
4633 /// expression @p From.
4634 static ImplicitConversionSequence
4635 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4636                                 Expr::Classification FromClassification,
4637                                 CXXMethodDecl *Method,
4638                                 CXXRecordDecl *ActingContext) {
4639   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4640   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4641   //                 const volatile object.
4642   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4643     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4644   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4645 
4646   // Set up the conversion sequence as a "bad" conversion, to allow us
4647   // to exit early.
4648   ImplicitConversionSequence ICS;
4649 
4650   // We need to have an object of class type.
4651   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4652     FromType = PT->getPointeeType();
4653 
4654     // When we had a pointer, it's implicitly dereferenced, so we
4655     // better have an lvalue.
4656     assert(FromClassification.isLValue());
4657   }
4658 
4659   assert(FromType->isRecordType());
4660 
4661   // C++0x [over.match.funcs]p4:
4662   //   For non-static member functions, the type of the implicit object
4663   //   parameter is
4664   //
4665   //     - "lvalue reference to cv X" for functions declared without a
4666   //        ref-qualifier or with the & ref-qualifier
4667   //     - "rvalue reference to cv X" for functions declared with the &&
4668   //        ref-qualifier
4669   //
4670   // where X is the class of which the function is a member and cv is the
4671   // cv-qualification on the member function declaration.
4672   //
4673   // However, when finding an implicit conversion sequence for the argument, we
4674   // are not allowed to create temporaries or perform user-defined conversions
4675   // (C++ [over.match.funcs]p5). We perform a simplified version of
4676   // reference binding here, that allows class rvalues to bind to
4677   // non-constant references.
4678 
4679   // First check the qualifiers.
4680   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4681   if (ImplicitParamType.getCVRQualifiers()
4682                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4683       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4684     ICS.setBad(BadConversionSequence::bad_qualifiers,
4685                FromType, ImplicitParamType);
4686     return ICS;
4687   }
4688 
4689   // Check that we have either the same type or a derived type. It
4690   // affects the conversion rank.
4691   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4692   ImplicitConversionKind SecondKind;
4693   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4694     SecondKind = ICK_Identity;
4695   } else if (S.IsDerivedFrom(FromType, ClassType))
4696     SecondKind = ICK_Derived_To_Base;
4697   else {
4698     ICS.setBad(BadConversionSequence::unrelated_class,
4699                FromType, ImplicitParamType);
4700     return ICS;
4701   }
4702 
4703   // Check the ref-qualifier.
4704   switch (Method->getRefQualifier()) {
4705   case RQ_None:
4706     // Do nothing; we don't care about lvalueness or rvalueness.
4707     break;
4708 
4709   case RQ_LValue:
4710     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4711       // non-const lvalue reference cannot bind to an rvalue
4712       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4713                  ImplicitParamType);
4714       return ICS;
4715     }
4716     break;
4717 
4718   case RQ_RValue:
4719     if (!FromClassification.isRValue()) {
4720       // rvalue reference cannot bind to an lvalue
4721       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4722                  ImplicitParamType);
4723       return ICS;
4724     }
4725     break;
4726   }
4727 
4728   // Success. Mark this as a reference binding.
4729   ICS.setStandard();
4730   ICS.Standard.setAsIdentityConversion();
4731   ICS.Standard.Second = SecondKind;
4732   ICS.Standard.setFromType(FromType);
4733   ICS.Standard.setAllToTypes(ImplicitParamType);
4734   ICS.Standard.ReferenceBinding = true;
4735   ICS.Standard.DirectBinding = true;
4736   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4737   ICS.Standard.BindsToFunctionLvalue = false;
4738   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4739   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4740     = (Method->getRefQualifier() == RQ_None);
4741   return ICS;
4742 }
4743 
4744 /// PerformObjectArgumentInitialization - Perform initialization of
4745 /// the implicit object parameter for the given Method with the given
4746 /// expression.
4747 ExprResult
4748 Sema::PerformObjectArgumentInitialization(Expr *From,
4749                                           NestedNameSpecifier *Qualifier,
4750                                           NamedDecl *FoundDecl,
4751                                           CXXMethodDecl *Method) {
4752   QualType FromRecordType, DestType;
4753   QualType ImplicitParamRecordType  =
4754     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4755 
4756   Expr::Classification FromClassification;
4757   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4758     FromRecordType = PT->getPointeeType();
4759     DestType = Method->getThisType(Context);
4760     FromClassification = Expr::Classification::makeSimpleLValue();
4761   } else {
4762     FromRecordType = From->getType();
4763     DestType = ImplicitParamRecordType;
4764     FromClassification = From->Classify(Context);
4765   }
4766 
4767   // Note that we always use the true parent context when performing
4768   // the actual argument initialization.
4769   ImplicitConversionSequence ICS
4770     = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4771                                       Method, Method->getParent());
4772   if (ICS.isBad()) {
4773     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4774       Qualifiers FromQs = FromRecordType.getQualifiers();
4775       Qualifiers ToQs = DestType.getQualifiers();
4776       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4777       if (CVR) {
4778         Diag(From->getLocStart(),
4779              diag::err_member_function_call_bad_cvr)
4780           << Method->getDeclName() << FromRecordType << (CVR - 1)
4781           << From->getSourceRange();
4782         Diag(Method->getLocation(), diag::note_previous_decl)
4783           << Method->getDeclName();
4784         return ExprError();
4785       }
4786     }
4787 
4788     return Diag(From->getLocStart(),
4789                 diag::err_implicit_object_parameter_init)
4790        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4791   }
4792 
4793   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4794     ExprResult FromRes =
4795       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4796     if (FromRes.isInvalid())
4797       return ExprError();
4798     From = FromRes.take();
4799   }
4800 
4801   if (!Context.hasSameType(From->getType(), DestType))
4802     From = ImpCastExprToType(From, DestType, CK_NoOp,
4803                              From->getValueKind()).take();
4804   return Owned(From);
4805 }
4806 
4807 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4808 /// expression From to bool (C++0x [conv]p3).
4809 static ImplicitConversionSequence
4810 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4811   // FIXME: This is pretty broken.
4812   return TryImplicitConversion(S, From, S.Context.BoolTy,
4813                                // FIXME: Are these flags correct?
4814                                /*SuppressUserConversions=*/false,
4815                                /*AllowExplicit=*/true,
4816                                /*InOverloadResolution=*/false,
4817                                /*CStyle=*/false,
4818                                /*AllowObjCWritebackConversion=*/false);
4819 }
4820 
4821 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4822 /// of the expression From to bool (C++0x [conv]p3).
4823 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4824   if (checkPlaceholderForOverload(*this, From))
4825     return ExprError();
4826 
4827   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4828   if (!ICS.isBad())
4829     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4830 
4831   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4832     return Diag(From->getLocStart(),
4833                 diag::err_typecheck_bool_condition)
4834                   << From->getType() << From->getSourceRange();
4835   return ExprError();
4836 }
4837 
4838 /// Check that the specified conversion is permitted in a converted constant
4839 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4840 /// is acceptable.
4841 static bool CheckConvertedConstantConversions(Sema &S,
4842                                               StandardConversionSequence &SCS) {
4843   // Since we know that the target type is an integral or unscoped enumeration
4844   // type, most conversion kinds are impossible. All possible First and Third
4845   // conversions are fine.
4846   switch (SCS.Second) {
4847   case ICK_Identity:
4848   case ICK_Integral_Promotion:
4849   case ICK_Integral_Conversion:
4850   case ICK_Zero_Event_Conversion:
4851     return true;
4852 
4853   case ICK_Boolean_Conversion:
4854     // Conversion from an integral or unscoped enumeration type to bool is
4855     // classified as ICK_Boolean_Conversion, but it's also an integral
4856     // conversion, so it's permitted in a converted constant expression.
4857     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4858            SCS.getToType(2)->isBooleanType();
4859 
4860   case ICK_Floating_Integral:
4861   case ICK_Complex_Real:
4862     return false;
4863 
4864   case ICK_Lvalue_To_Rvalue:
4865   case ICK_Array_To_Pointer:
4866   case ICK_Function_To_Pointer:
4867   case ICK_NoReturn_Adjustment:
4868   case ICK_Qualification:
4869   case ICK_Compatible_Conversion:
4870   case ICK_Vector_Conversion:
4871   case ICK_Vector_Splat:
4872   case ICK_Derived_To_Base:
4873   case ICK_Pointer_Conversion:
4874   case ICK_Pointer_Member:
4875   case ICK_Block_Pointer_Conversion:
4876   case ICK_Writeback_Conversion:
4877   case ICK_Floating_Promotion:
4878   case ICK_Complex_Promotion:
4879   case ICK_Complex_Conversion:
4880   case ICK_Floating_Conversion:
4881   case ICK_TransparentUnionConversion:
4882     llvm_unreachable("unexpected second conversion kind");
4883 
4884   case ICK_Num_Conversion_Kinds:
4885     break;
4886   }
4887 
4888   llvm_unreachable("unknown conversion kind");
4889 }
4890 
4891 /// CheckConvertedConstantExpression - Check that the expression From is a
4892 /// converted constant expression of type T, perform the conversion and produce
4893 /// the converted expression, per C++11 [expr.const]p3.
4894 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4895                                                   llvm::APSInt &Value,
4896                                                   CCEKind CCE) {
4897   assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4898   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4899 
4900   if (checkPlaceholderForOverload(*this, From))
4901     return ExprError();
4902 
4903   // C++11 [expr.const]p3 with proposed wording fixes:
4904   //  A converted constant expression of type T is a core constant expression,
4905   //  implicitly converted to a prvalue of type T, where the converted
4906   //  expression is a literal constant expression and the implicit conversion
4907   //  sequence contains only user-defined conversions, lvalue-to-rvalue
4908   //  conversions, integral promotions, and integral conversions other than
4909   //  narrowing conversions.
4910   ImplicitConversionSequence ICS =
4911     TryImplicitConversion(From, T,
4912                           /*SuppressUserConversions=*/false,
4913                           /*AllowExplicit=*/false,
4914                           /*InOverloadResolution=*/false,
4915                           /*CStyle=*/false,
4916                           /*AllowObjcWritebackConversion=*/false);
4917   StandardConversionSequence *SCS = 0;
4918   switch (ICS.getKind()) {
4919   case ImplicitConversionSequence::StandardConversion:
4920     if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4921       return Diag(From->getLocStart(),
4922                   diag::err_typecheck_converted_constant_expression_disallowed)
4923                << From->getType() << From->getSourceRange() << T;
4924     SCS = &ICS.Standard;
4925     break;
4926   case ImplicitConversionSequence::UserDefinedConversion:
4927     // We are converting from class type to an integral or enumeration type, so
4928     // the Before sequence must be trivial.
4929     if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4930       return Diag(From->getLocStart(),
4931                   diag::err_typecheck_converted_constant_expression_disallowed)
4932                << From->getType() << From->getSourceRange() << T;
4933     SCS = &ICS.UserDefined.After;
4934     break;
4935   case ImplicitConversionSequence::AmbiguousConversion:
4936   case ImplicitConversionSequence::BadConversion:
4937     if (!DiagnoseMultipleUserDefinedConversion(From, T))
4938       return Diag(From->getLocStart(),
4939                   diag::err_typecheck_converted_constant_expression)
4940                     << From->getType() << From->getSourceRange() << T;
4941     return ExprError();
4942 
4943   case ImplicitConversionSequence::EllipsisConversion:
4944     llvm_unreachable("ellipsis conversion in converted constant expression");
4945   }
4946 
4947   ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4948   if (Result.isInvalid())
4949     return Result;
4950 
4951   // Check for a narrowing implicit conversion.
4952   APValue PreNarrowingValue;
4953   QualType PreNarrowingType;
4954   switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4955                                 PreNarrowingType)) {
4956   case NK_Variable_Narrowing:
4957     // Implicit conversion to a narrower type, and the value is not a constant
4958     // expression. We'll diagnose this in a moment.
4959   case NK_Not_Narrowing:
4960     break;
4961 
4962   case NK_Constant_Narrowing:
4963     Diag(From->getLocStart(),
4964          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4965                              diag::err_cce_narrowing)
4966       << CCE << /*Constant*/1
4967       << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
4968     break;
4969 
4970   case NK_Type_Narrowing:
4971     Diag(From->getLocStart(),
4972          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4973                              diag::err_cce_narrowing)
4974       << CCE << /*Constant*/0 << From->getType() << T;
4975     break;
4976   }
4977 
4978   // Check the expression is a constant expression.
4979   SmallVector<PartialDiagnosticAt, 8> Notes;
4980   Expr::EvalResult Eval;
4981   Eval.Diag = &Notes;
4982 
4983   if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
4984     // The expression can't be folded, so we can't keep it at this position in
4985     // the AST.
4986     Result = ExprError();
4987   } else {
4988     Value = Eval.Val.getInt();
4989 
4990     if (Notes.empty()) {
4991       // It's a constant expression.
4992       return Result;
4993     }
4994   }
4995 
4996   // It's not a constant expression. Produce an appropriate diagnostic.
4997   if (Notes.size() == 1 &&
4998       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4999     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5000   else {
5001     Diag(From->getLocStart(), diag::err_expr_not_cce)
5002       << CCE << From->getSourceRange();
5003     for (unsigned I = 0; I < Notes.size(); ++I)
5004       Diag(Notes[I].first, Notes[I].second);
5005   }
5006   return Result;
5007 }
5008 
5009 /// dropPointerConversions - If the given standard conversion sequence
5010 /// involves any pointer conversions, remove them.  This may change
5011 /// the result type of the conversion sequence.
5012 static void dropPointerConversion(StandardConversionSequence &SCS) {
5013   if (SCS.Second == ICK_Pointer_Conversion) {
5014     SCS.Second = ICK_Identity;
5015     SCS.Third = ICK_Identity;
5016     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5017   }
5018 }
5019 
5020 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5021 /// convert the expression From to an Objective-C pointer type.
5022 static ImplicitConversionSequence
5023 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5024   // Do an implicit conversion to 'id'.
5025   QualType Ty = S.Context.getObjCIdType();
5026   ImplicitConversionSequence ICS
5027     = TryImplicitConversion(S, From, Ty,
5028                             // FIXME: Are these flags correct?
5029                             /*SuppressUserConversions=*/false,
5030                             /*AllowExplicit=*/true,
5031                             /*InOverloadResolution=*/false,
5032                             /*CStyle=*/false,
5033                             /*AllowObjCWritebackConversion=*/false);
5034 
5035   // Strip off any final conversions to 'id'.
5036   switch (ICS.getKind()) {
5037   case ImplicitConversionSequence::BadConversion:
5038   case ImplicitConversionSequence::AmbiguousConversion:
5039   case ImplicitConversionSequence::EllipsisConversion:
5040     break;
5041 
5042   case ImplicitConversionSequence::UserDefinedConversion:
5043     dropPointerConversion(ICS.UserDefined.After);
5044     break;
5045 
5046   case ImplicitConversionSequence::StandardConversion:
5047     dropPointerConversion(ICS.Standard);
5048     break;
5049   }
5050 
5051   return ICS;
5052 }
5053 
5054 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5055 /// conversion of the expression From to an Objective-C pointer type.
5056 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5057   if (checkPlaceholderForOverload(*this, From))
5058     return ExprError();
5059 
5060   QualType Ty = Context.getObjCIdType();
5061   ImplicitConversionSequence ICS =
5062     TryContextuallyConvertToObjCPointer(*this, From);
5063   if (!ICS.isBad())
5064     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5065   return ExprError();
5066 }
5067 
5068 /// Determine whether the provided type is an integral type, or an enumeration
5069 /// type of a permitted flavor.
5070 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5071   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5072                                  : T->isIntegralOrUnscopedEnumerationType();
5073 }
5074 
5075 static ExprResult
5076 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5077                             Sema::ContextualImplicitConverter &Converter,
5078                             QualType T, UnresolvedSetImpl &ViableConversions) {
5079 
5080   if (Converter.Suppress)
5081     return ExprError();
5082 
5083   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5084   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5085     CXXConversionDecl *Conv =
5086         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5087     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5088     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5089   }
5090   return SemaRef.Owned(From);
5091 }
5092 
5093 static bool
5094 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5095                            Sema::ContextualImplicitConverter &Converter,
5096                            QualType T, bool HadMultipleCandidates,
5097                            UnresolvedSetImpl &ExplicitConversions) {
5098   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5099     DeclAccessPair Found = ExplicitConversions[0];
5100     CXXConversionDecl *Conversion =
5101         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5102 
5103     // The user probably meant to invoke the given explicit
5104     // conversion; use it.
5105     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5106     std::string TypeStr;
5107     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5108 
5109     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5110         << FixItHint::CreateInsertion(From->getLocStart(),
5111                                       "static_cast<" + TypeStr + ">(")
5112         << FixItHint::CreateInsertion(
5113                SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5114     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5115 
5116     // If we aren't in a SFINAE context, build a call to the
5117     // explicit conversion function.
5118     if (SemaRef.isSFINAEContext())
5119       return true;
5120 
5121     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5122     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5123                                                        HadMultipleCandidates);
5124     if (Result.isInvalid())
5125       return true;
5126     // Record usage of conversion in an implicit cast.
5127     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5128                                     CK_UserDefinedConversion, Result.get(), 0,
5129                                     Result.get()->getValueKind());
5130   }
5131   return false;
5132 }
5133 
5134 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5135                              Sema::ContextualImplicitConverter &Converter,
5136                              QualType T, bool HadMultipleCandidates,
5137                              DeclAccessPair &Found) {
5138   CXXConversionDecl *Conversion =
5139       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5140   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5141 
5142   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5143   if (!Converter.SuppressConversion) {
5144     if (SemaRef.isSFINAEContext())
5145       return true;
5146 
5147     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5148         << From->getSourceRange();
5149   }
5150 
5151   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5152                                                      HadMultipleCandidates);
5153   if (Result.isInvalid())
5154     return true;
5155   // Record usage of conversion in an implicit cast.
5156   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5157                                   CK_UserDefinedConversion, Result.get(), 0,
5158                                   Result.get()->getValueKind());
5159   return false;
5160 }
5161 
5162 static ExprResult finishContextualImplicitConversion(
5163     Sema &SemaRef, SourceLocation Loc, Expr *From,
5164     Sema::ContextualImplicitConverter &Converter) {
5165   if (!Converter.match(From->getType()) && !Converter.Suppress)
5166     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5167         << From->getSourceRange();
5168 
5169   return SemaRef.DefaultLvalueConversion(From);
5170 }
5171 
5172 static void
5173 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5174                                   UnresolvedSetImpl &ViableConversions,
5175                                   OverloadCandidateSet &CandidateSet) {
5176   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5177     DeclAccessPair FoundDecl = ViableConversions[I];
5178     NamedDecl *D = FoundDecl.getDecl();
5179     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5180     if (isa<UsingShadowDecl>(D))
5181       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5182 
5183     CXXConversionDecl *Conv;
5184     FunctionTemplateDecl *ConvTemplate;
5185     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5186       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5187     else
5188       Conv = cast<CXXConversionDecl>(D);
5189 
5190     if (ConvTemplate)
5191       SemaRef.AddTemplateConversionCandidate(
5192           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet);
5193     else
5194       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5195                                      ToType, CandidateSet);
5196   }
5197 }
5198 
5199 /// \brief Attempt to convert the given expression to a type which is accepted
5200 /// by the given converter.
5201 ///
5202 /// This routine will attempt to convert an expression of class type to a
5203 /// type accepted by the specified converter. In C++11 and before, the class
5204 /// must have a single non-explicit conversion function converting to a matching
5205 /// type. In C++1y, there can be multiple such conversion functions, but only
5206 /// one target type.
5207 ///
5208 /// \param Loc The source location of the construct that requires the
5209 /// conversion.
5210 ///
5211 /// \param From The expression we're converting from.
5212 ///
5213 /// \param Converter Used to control and diagnose the conversion process.
5214 ///
5215 /// \returns The expression, converted to an integral or enumeration type if
5216 /// successful.
5217 ExprResult Sema::PerformContextualImplicitConversion(
5218     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5219   // We can't perform any more checking for type-dependent expressions.
5220   if (From->isTypeDependent())
5221     return Owned(From);
5222 
5223   // Process placeholders immediately.
5224   if (From->hasPlaceholderType()) {
5225     ExprResult result = CheckPlaceholderExpr(From);
5226     if (result.isInvalid())
5227       return result;
5228     From = result.take();
5229   }
5230 
5231   // If the expression already has a matching type, we're golden.
5232   QualType T = From->getType();
5233   if (Converter.match(T))
5234     return DefaultLvalueConversion(From);
5235 
5236   // FIXME: Check for missing '()' if T is a function type?
5237 
5238   // We can only perform contextual implicit conversions on objects of class
5239   // type.
5240   const RecordType *RecordTy = T->getAs<RecordType>();
5241   if (!RecordTy || !getLangOpts().CPlusPlus) {
5242     if (!Converter.Suppress)
5243       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5244     return Owned(From);
5245   }
5246 
5247   // We must have a complete class type.
5248   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5249     ContextualImplicitConverter &Converter;
5250     Expr *From;
5251 
5252     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5253         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5254 
5255     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5256       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5257     }
5258   } IncompleteDiagnoser(Converter, From);
5259 
5260   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5261     return Owned(From);
5262 
5263   // Look for a conversion to an integral or enumeration type.
5264   UnresolvedSet<4>
5265       ViableConversions; // These are *potentially* viable in C++1y.
5266   UnresolvedSet<4> ExplicitConversions;
5267   std::pair<CXXRecordDecl::conversion_iterator,
5268             CXXRecordDecl::conversion_iterator> Conversions =
5269       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5270 
5271   bool HadMultipleCandidates =
5272       (std::distance(Conversions.first, Conversions.second) > 1);
5273 
5274   // To check that there is only one target type, in C++1y:
5275   QualType ToType;
5276   bool HasUniqueTargetType = true;
5277 
5278   // Collect explicit or viable (potentially in C++1y) conversions.
5279   for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5280                                           E = Conversions.second;
5281        I != E; ++I) {
5282     NamedDecl *D = (*I)->getUnderlyingDecl();
5283     CXXConversionDecl *Conversion;
5284     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5285     if (ConvTemplate) {
5286       if (getLangOpts().CPlusPlus1y)
5287         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5288       else
5289         continue; // C++11 does not consider conversion operator templates(?).
5290     } else
5291       Conversion = cast<CXXConversionDecl>(D);
5292 
5293     assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5294            "Conversion operator templates are considered potentially "
5295            "viable in C++1y");
5296 
5297     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5298     if (Converter.match(CurToType) || ConvTemplate) {
5299 
5300       if (Conversion->isExplicit()) {
5301         // FIXME: For C++1y, do we need this restriction?
5302         // cf. diagnoseNoViableConversion()
5303         if (!ConvTemplate)
5304           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5305       } else {
5306         if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5307           if (ToType.isNull())
5308             ToType = CurToType.getUnqualifiedType();
5309           else if (HasUniqueTargetType &&
5310                    (CurToType.getUnqualifiedType() != ToType))
5311             HasUniqueTargetType = false;
5312         }
5313         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5314       }
5315     }
5316   }
5317 
5318   if (getLangOpts().CPlusPlus1y) {
5319     // C++1y [conv]p6:
5320     // ... An expression e of class type E appearing in such a context
5321     // is said to be contextually implicitly converted to a specified
5322     // type T and is well-formed if and only if e can be implicitly
5323     // converted to a type T that is determined as follows: E is searched
5324     // for conversion functions whose return type is cv T or reference to
5325     // cv T such that T is allowed by the context. There shall be
5326     // exactly one such T.
5327 
5328     // If no unique T is found:
5329     if (ToType.isNull()) {
5330       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5331                                      HadMultipleCandidates,
5332                                      ExplicitConversions))
5333         return ExprError();
5334       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5335     }
5336 
5337     // If more than one unique Ts are found:
5338     if (!HasUniqueTargetType)
5339       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5340                                          ViableConversions);
5341 
5342     // If one unique T is found:
5343     // First, build a candidate set from the previously recorded
5344     // potentially viable conversions.
5345     OverloadCandidateSet CandidateSet(Loc);
5346     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5347                                       CandidateSet);
5348 
5349     // Then, perform overload resolution over the candidate set.
5350     OverloadCandidateSet::iterator Best;
5351     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5352     case OR_Success: {
5353       // Apply this conversion.
5354       DeclAccessPair Found =
5355           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5356       if (recordConversion(*this, Loc, From, Converter, T,
5357                            HadMultipleCandidates, Found))
5358         return ExprError();
5359       break;
5360     }
5361     case OR_Ambiguous:
5362       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5363                                          ViableConversions);
5364     case OR_No_Viable_Function:
5365       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5366                                      HadMultipleCandidates,
5367                                      ExplicitConversions))
5368         return ExprError();
5369     // fall through 'OR_Deleted' case.
5370     case OR_Deleted:
5371       // We'll complain below about a non-integral condition type.
5372       break;
5373     }
5374   } else {
5375     switch (ViableConversions.size()) {
5376     case 0: {
5377       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5378                                      HadMultipleCandidates,
5379                                      ExplicitConversions))
5380         return ExprError();
5381 
5382       // We'll complain below about a non-integral condition type.
5383       break;
5384     }
5385     case 1: {
5386       // Apply this conversion.
5387       DeclAccessPair Found = ViableConversions[0];
5388       if (recordConversion(*this, Loc, From, Converter, T,
5389                            HadMultipleCandidates, Found))
5390         return ExprError();
5391       break;
5392     }
5393     default:
5394       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5395                                          ViableConversions);
5396     }
5397   }
5398 
5399   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5400 }
5401 
5402 /// AddOverloadCandidate - Adds the given function to the set of
5403 /// candidate functions, using the given function call arguments.  If
5404 /// @p SuppressUserConversions, then don't allow user-defined
5405 /// conversions via constructors or conversion operators.
5406 ///
5407 /// \param PartialOverloading true if we are performing "partial" overloading
5408 /// based on an incomplete set of function arguments. This feature is used by
5409 /// code completion.
5410 void
5411 Sema::AddOverloadCandidate(FunctionDecl *Function,
5412                            DeclAccessPair FoundDecl,
5413                            ArrayRef<Expr *> Args,
5414                            OverloadCandidateSet& CandidateSet,
5415                            bool SuppressUserConversions,
5416                            bool PartialOverloading,
5417                            bool AllowExplicit) {
5418   const FunctionProtoType* Proto
5419     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5420   assert(Proto && "Functions without a prototype cannot be overloaded");
5421   assert(!Function->getDescribedFunctionTemplate() &&
5422          "Use AddTemplateOverloadCandidate for function templates");
5423 
5424   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5425     if (!isa<CXXConstructorDecl>(Method)) {
5426       // If we get here, it's because we're calling a member function
5427       // that is named without a member access expression (e.g.,
5428       // "this->f") that was either written explicitly or created
5429       // implicitly. This can happen with a qualified call to a member
5430       // function, e.g., X::f(). We use an empty type for the implied
5431       // object argument (C++ [over.call.func]p3), and the acting context
5432       // is irrelevant.
5433       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5434                          QualType(), Expr::Classification::makeSimpleLValue(),
5435                          Args, CandidateSet, SuppressUserConversions);
5436       return;
5437     }
5438     // We treat a constructor like a non-member function, since its object
5439     // argument doesn't participate in overload resolution.
5440   }
5441 
5442   if (!CandidateSet.isNewCandidate(Function))
5443     return;
5444 
5445   // Overload resolution is always an unevaluated context.
5446   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5447 
5448   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5449     // C++ [class.copy]p3:
5450     //   A member function template is never instantiated to perform the copy
5451     //   of a class object to an object of its class type.
5452     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5453     if (Args.size() == 1 &&
5454         Constructor->isSpecializationCopyingObject() &&
5455         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5456          IsDerivedFrom(Args[0]->getType(), ClassType)))
5457       return;
5458   }
5459 
5460   // Add this candidate
5461   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5462   Candidate.FoundDecl = FoundDecl;
5463   Candidate.Function = Function;
5464   Candidate.Viable = true;
5465   Candidate.IsSurrogate = false;
5466   Candidate.IgnoreObjectArgument = false;
5467   Candidate.ExplicitCallArguments = Args.size();
5468 
5469   unsigned NumArgsInProto = Proto->getNumArgs();
5470 
5471   // (C++ 13.3.2p2): A candidate function having fewer than m
5472   // parameters is viable only if it has an ellipsis in its parameter
5473   // list (8.3.5).
5474   if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5475       !Proto->isVariadic()) {
5476     Candidate.Viable = false;
5477     Candidate.FailureKind = ovl_fail_too_many_arguments;
5478     return;
5479   }
5480 
5481   // (C++ 13.3.2p2): A candidate function having more than m parameters
5482   // is viable only if the (m+1)st parameter has a default argument
5483   // (8.3.6). For the purposes of overload resolution, the
5484   // parameter list is truncated on the right, so that there are
5485   // exactly m parameters.
5486   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5487   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5488     // Not enough arguments.
5489     Candidate.Viable = false;
5490     Candidate.FailureKind = ovl_fail_too_few_arguments;
5491     return;
5492   }
5493 
5494   // (CUDA B.1): Check for invalid calls between targets.
5495   if (getLangOpts().CUDA)
5496     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5497       if (CheckCUDATarget(Caller, Function)) {
5498         Candidate.Viable = false;
5499         Candidate.FailureKind = ovl_fail_bad_target;
5500         return;
5501       }
5502 
5503   // Determine the implicit conversion sequences for each of the
5504   // arguments.
5505   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5506     if (ArgIdx < NumArgsInProto) {
5507       // (C++ 13.3.2p3): for F to be a viable function, there shall
5508       // exist for each argument an implicit conversion sequence
5509       // (13.3.3.1) that converts that argument to the corresponding
5510       // parameter of F.
5511       QualType ParamType = Proto->getArgType(ArgIdx);
5512       Candidate.Conversions[ArgIdx]
5513         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5514                                 SuppressUserConversions,
5515                                 /*InOverloadResolution=*/true,
5516                                 /*AllowObjCWritebackConversion=*/
5517                                   getLangOpts().ObjCAutoRefCount,
5518                                 AllowExplicit);
5519       if (Candidate.Conversions[ArgIdx].isBad()) {
5520         Candidate.Viable = false;
5521         Candidate.FailureKind = ovl_fail_bad_conversion;
5522         break;
5523       }
5524     } else {
5525       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5526       // argument for which there is no corresponding parameter is
5527       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5528       Candidate.Conversions[ArgIdx].setEllipsis();
5529     }
5530   }
5531 }
5532 
5533 /// \brief Add all of the function declarations in the given function set to
5534 /// the overload canddiate set.
5535 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5536                                  ArrayRef<Expr *> Args,
5537                                  OverloadCandidateSet& CandidateSet,
5538                                  bool SuppressUserConversions,
5539                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
5540   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5541     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5542     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5543       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5544         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5545                            cast<CXXMethodDecl>(FD)->getParent(),
5546                            Args[0]->getType(), Args[0]->Classify(Context),
5547                            Args.slice(1), CandidateSet,
5548                            SuppressUserConversions);
5549       else
5550         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5551                              SuppressUserConversions);
5552     } else {
5553       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5554       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5555           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5556         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5557                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5558                                    ExplicitTemplateArgs,
5559                                    Args[0]->getType(),
5560                                    Args[0]->Classify(Context), Args.slice(1),
5561                                    CandidateSet, SuppressUserConversions);
5562       else
5563         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5564                                      ExplicitTemplateArgs, Args,
5565                                      CandidateSet, SuppressUserConversions);
5566     }
5567   }
5568 }
5569 
5570 /// AddMethodCandidate - Adds a named decl (which is some kind of
5571 /// method) as a method candidate to the given overload set.
5572 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5573                               QualType ObjectType,
5574                               Expr::Classification ObjectClassification,
5575                               ArrayRef<Expr *> Args,
5576                               OverloadCandidateSet& CandidateSet,
5577                               bool SuppressUserConversions) {
5578   NamedDecl *Decl = FoundDecl.getDecl();
5579   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5580 
5581   if (isa<UsingShadowDecl>(Decl))
5582     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5583 
5584   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5585     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5586            "Expected a member function template");
5587     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5588                                /*ExplicitArgs*/ 0,
5589                                ObjectType, ObjectClassification,
5590                                Args, CandidateSet,
5591                                SuppressUserConversions);
5592   } else {
5593     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5594                        ObjectType, ObjectClassification,
5595                        Args,
5596                        CandidateSet, SuppressUserConversions);
5597   }
5598 }
5599 
5600 /// AddMethodCandidate - Adds the given C++ member function to the set
5601 /// of candidate functions, using the given function call arguments
5602 /// and the object argument (@c Object). For example, in a call
5603 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5604 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5605 /// allow user-defined conversions via constructors or conversion
5606 /// operators.
5607 void
5608 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5609                          CXXRecordDecl *ActingContext, QualType ObjectType,
5610                          Expr::Classification ObjectClassification,
5611                          ArrayRef<Expr *> Args,
5612                          OverloadCandidateSet& CandidateSet,
5613                          bool SuppressUserConversions) {
5614   const FunctionProtoType* Proto
5615     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5616   assert(Proto && "Methods without a prototype cannot be overloaded");
5617   assert(!isa<CXXConstructorDecl>(Method) &&
5618          "Use AddOverloadCandidate for constructors");
5619 
5620   if (!CandidateSet.isNewCandidate(Method))
5621     return;
5622 
5623   // Overload resolution is always an unevaluated context.
5624   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5625 
5626   // Add this candidate
5627   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5628   Candidate.FoundDecl = FoundDecl;
5629   Candidate.Function = Method;
5630   Candidate.IsSurrogate = false;
5631   Candidate.IgnoreObjectArgument = false;
5632   Candidate.ExplicitCallArguments = Args.size();
5633 
5634   unsigned NumArgsInProto = Proto->getNumArgs();
5635 
5636   // (C++ 13.3.2p2): A candidate function having fewer than m
5637   // parameters is viable only if it has an ellipsis in its parameter
5638   // list (8.3.5).
5639   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5640     Candidate.Viable = false;
5641     Candidate.FailureKind = ovl_fail_too_many_arguments;
5642     return;
5643   }
5644 
5645   // (C++ 13.3.2p2): A candidate function having more than m parameters
5646   // is viable only if the (m+1)st parameter has a default argument
5647   // (8.3.6). For the purposes of overload resolution, the
5648   // parameter list is truncated on the right, so that there are
5649   // exactly m parameters.
5650   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5651   if (Args.size() < MinRequiredArgs) {
5652     // Not enough arguments.
5653     Candidate.Viable = false;
5654     Candidate.FailureKind = ovl_fail_too_few_arguments;
5655     return;
5656   }
5657 
5658   Candidate.Viable = true;
5659 
5660   if (Method->isStatic() || ObjectType.isNull())
5661     // The implicit object argument is ignored.
5662     Candidate.IgnoreObjectArgument = true;
5663   else {
5664     // Determine the implicit conversion sequence for the object
5665     // parameter.
5666     Candidate.Conversions[0]
5667       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5668                                         Method, ActingContext);
5669     if (Candidate.Conversions[0].isBad()) {
5670       Candidate.Viable = false;
5671       Candidate.FailureKind = ovl_fail_bad_conversion;
5672       return;
5673     }
5674   }
5675 
5676   // Determine the implicit conversion sequences for each of the
5677   // arguments.
5678   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5679     if (ArgIdx < NumArgsInProto) {
5680       // (C++ 13.3.2p3): for F to be a viable function, there shall
5681       // exist for each argument an implicit conversion sequence
5682       // (13.3.3.1) that converts that argument to the corresponding
5683       // parameter of F.
5684       QualType ParamType = Proto->getArgType(ArgIdx);
5685       Candidate.Conversions[ArgIdx + 1]
5686         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5687                                 SuppressUserConversions,
5688                                 /*InOverloadResolution=*/true,
5689                                 /*AllowObjCWritebackConversion=*/
5690                                   getLangOpts().ObjCAutoRefCount);
5691       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5692         Candidate.Viable = false;
5693         Candidate.FailureKind = ovl_fail_bad_conversion;
5694         break;
5695       }
5696     } else {
5697       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5698       // argument for which there is no corresponding parameter is
5699       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5700       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5701     }
5702   }
5703 }
5704 
5705 /// \brief Add a C++ member function template as a candidate to the candidate
5706 /// set, using template argument deduction to produce an appropriate member
5707 /// function template specialization.
5708 void
5709 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5710                                  DeclAccessPair FoundDecl,
5711                                  CXXRecordDecl *ActingContext,
5712                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5713                                  QualType ObjectType,
5714                                  Expr::Classification ObjectClassification,
5715                                  ArrayRef<Expr *> Args,
5716                                  OverloadCandidateSet& CandidateSet,
5717                                  bool SuppressUserConversions) {
5718   if (!CandidateSet.isNewCandidate(MethodTmpl))
5719     return;
5720 
5721   // C++ [over.match.funcs]p7:
5722   //   In each case where a candidate is a function template, candidate
5723   //   function template specializations are generated using template argument
5724   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5725   //   candidate functions in the usual way.113) A given name can refer to one
5726   //   or more function templates and also to a set of overloaded non-template
5727   //   functions. In such a case, the candidate functions generated from each
5728   //   function template are combined with the set of non-template candidate
5729   //   functions.
5730   TemplateDeductionInfo Info(CandidateSet.getLocation());
5731   FunctionDecl *Specialization = 0;
5732   if (TemplateDeductionResult Result
5733       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5734                                 Specialization, Info)) {
5735     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5736     Candidate.FoundDecl = FoundDecl;
5737     Candidate.Function = MethodTmpl->getTemplatedDecl();
5738     Candidate.Viable = false;
5739     Candidate.FailureKind = ovl_fail_bad_deduction;
5740     Candidate.IsSurrogate = false;
5741     Candidate.IgnoreObjectArgument = false;
5742     Candidate.ExplicitCallArguments = Args.size();
5743     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5744                                                           Info);
5745     return;
5746   }
5747 
5748   // Add the function template specialization produced by template argument
5749   // deduction as a candidate.
5750   assert(Specialization && "Missing member function template specialization?");
5751   assert(isa<CXXMethodDecl>(Specialization) &&
5752          "Specialization is not a member function?");
5753   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5754                      ActingContext, ObjectType, ObjectClassification, Args,
5755                      CandidateSet, SuppressUserConversions);
5756 }
5757 
5758 /// \brief Add a C++ function template specialization as a candidate
5759 /// in the candidate set, using template argument deduction to produce
5760 /// an appropriate function template specialization.
5761 void
5762 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5763                                    DeclAccessPair FoundDecl,
5764                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5765                                    ArrayRef<Expr *> Args,
5766                                    OverloadCandidateSet& CandidateSet,
5767                                    bool SuppressUserConversions) {
5768   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5769     return;
5770 
5771   // C++ [over.match.funcs]p7:
5772   //   In each case where a candidate is a function template, candidate
5773   //   function template specializations are generated using template argument
5774   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5775   //   candidate functions in the usual way.113) A given name can refer to one
5776   //   or more function templates and also to a set of overloaded non-template
5777   //   functions. In such a case, the candidate functions generated from each
5778   //   function template are combined with the set of non-template candidate
5779   //   functions.
5780   TemplateDeductionInfo Info(CandidateSet.getLocation());
5781   FunctionDecl *Specialization = 0;
5782   if (TemplateDeductionResult Result
5783         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5784                                   Specialization, Info)) {
5785     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5786     Candidate.FoundDecl = FoundDecl;
5787     Candidate.Function = FunctionTemplate->getTemplatedDecl();
5788     Candidate.Viable = false;
5789     Candidate.FailureKind = ovl_fail_bad_deduction;
5790     Candidate.IsSurrogate = false;
5791     Candidate.IgnoreObjectArgument = false;
5792     Candidate.ExplicitCallArguments = Args.size();
5793     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5794                                                           Info);
5795     return;
5796   }
5797 
5798   // Add the function template specialization produced by template argument
5799   // deduction as a candidate.
5800   assert(Specialization && "Missing function template specialization?");
5801   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5802                        SuppressUserConversions);
5803 }
5804 
5805 /// AddConversionCandidate - Add a C++ conversion function as a
5806 /// candidate in the candidate set (C++ [over.match.conv],
5807 /// C++ [over.match.copy]). From is the expression we're converting from,
5808 /// and ToType is the type that we're eventually trying to convert to
5809 /// (which may or may not be the same type as the type that the
5810 /// conversion function produces).
5811 void
5812 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5813                              DeclAccessPair FoundDecl,
5814                              CXXRecordDecl *ActingContext,
5815                              Expr *From, QualType ToType,
5816                              OverloadCandidateSet& CandidateSet) {
5817   assert(!Conversion->getDescribedFunctionTemplate() &&
5818          "Conversion function templates use AddTemplateConversionCandidate");
5819   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5820   if (!CandidateSet.isNewCandidate(Conversion))
5821     return;
5822 
5823   // If the conversion function has an undeduced return type, trigger its
5824   // deduction now.
5825   if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5826     if (DeduceReturnType(Conversion, From->getExprLoc()))
5827       return;
5828     ConvType = Conversion->getConversionType().getNonReferenceType();
5829   }
5830 
5831   // Overload resolution is always an unevaluated context.
5832   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5833 
5834   // Add this candidate
5835   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5836   Candidate.FoundDecl = FoundDecl;
5837   Candidate.Function = Conversion;
5838   Candidate.IsSurrogate = false;
5839   Candidate.IgnoreObjectArgument = false;
5840   Candidate.FinalConversion.setAsIdentityConversion();
5841   Candidate.FinalConversion.setFromType(ConvType);
5842   Candidate.FinalConversion.setAllToTypes(ToType);
5843   Candidate.Viable = true;
5844   Candidate.ExplicitCallArguments = 1;
5845 
5846   // C++ [over.match.funcs]p4:
5847   //   For conversion functions, the function is considered to be a member of
5848   //   the class of the implicit implied object argument for the purpose of
5849   //   defining the type of the implicit object parameter.
5850   //
5851   // Determine the implicit conversion sequence for the implicit
5852   // object parameter.
5853   QualType ImplicitParamType = From->getType();
5854   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5855     ImplicitParamType = FromPtrType->getPointeeType();
5856   CXXRecordDecl *ConversionContext
5857     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5858 
5859   Candidate.Conversions[0]
5860     = TryObjectArgumentInitialization(*this, From->getType(),
5861                                       From->Classify(Context),
5862                                       Conversion, ConversionContext);
5863 
5864   if (Candidate.Conversions[0].isBad()) {
5865     Candidate.Viable = false;
5866     Candidate.FailureKind = ovl_fail_bad_conversion;
5867     return;
5868   }
5869 
5870   // We won't go through a user-define type conversion function to convert a
5871   // derived to base as such conversions are given Conversion Rank. They only
5872   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5873   QualType FromCanon
5874     = Context.getCanonicalType(From->getType().getUnqualifiedType());
5875   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5876   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5877     Candidate.Viable = false;
5878     Candidate.FailureKind = ovl_fail_trivial_conversion;
5879     return;
5880   }
5881 
5882   // To determine what the conversion from the result of calling the
5883   // conversion function to the type we're eventually trying to
5884   // convert to (ToType), we need to synthesize a call to the
5885   // conversion function and attempt copy initialization from it. This
5886   // makes sure that we get the right semantics with respect to
5887   // lvalues/rvalues and the type. Fortunately, we can allocate this
5888   // call on the stack and we don't need its arguments to be
5889   // well-formed.
5890   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5891                             VK_LValue, From->getLocStart());
5892   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5893                                 Context.getPointerType(Conversion->getType()),
5894                                 CK_FunctionToPointerDecay,
5895                                 &ConversionRef, VK_RValue);
5896 
5897   QualType ConversionType = Conversion->getConversionType();
5898   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5899     Candidate.Viable = false;
5900     Candidate.FailureKind = ovl_fail_bad_final_conversion;
5901     return;
5902   }
5903 
5904   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5905 
5906   // Note that it is safe to allocate CallExpr on the stack here because
5907   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5908   // allocator).
5909   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5910   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
5911                 From->getLocStart());
5912   ImplicitConversionSequence ICS =
5913     TryCopyInitialization(*this, &Call, ToType,
5914                           /*SuppressUserConversions=*/true,
5915                           /*InOverloadResolution=*/false,
5916                           /*AllowObjCWritebackConversion=*/false);
5917 
5918   switch (ICS.getKind()) {
5919   case ImplicitConversionSequence::StandardConversion:
5920     Candidate.FinalConversion = ICS.Standard;
5921 
5922     // C++ [over.ics.user]p3:
5923     //   If the user-defined conversion is specified by a specialization of a
5924     //   conversion function template, the second standard conversion sequence
5925     //   shall have exact match rank.
5926     if (Conversion->getPrimaryTemplate() &&
5927         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5928       Candidate.Viable = false;
5929       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5930     }
5931 
5932     // C++0x [dcl.init.ref]p5:
5933     //    In the second case, if the reference is an rvalue reference and
5934     //    the second standard conversion sequence of the user-defined
5935     //    conversion sequence includes an lvalue-to-rvalue conversion, the
5936     //    program is ill-formed.
5937     if (ToType->isRValueReferenceType() &&
5938         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5939       Candidate.Viable = false;
5940       Candidate.FailureKind = ovl_fail_bad_final_conversion;
5941     }
5942     break;
5943 
5944   case ImplicitConversionSequence::BadConversion:
5945     Candidate.Viable = false;
5946     Candidate.FailureKind = ovl_fail_bad_final_conversion;
5947     break;
5948 
5949   default:
5950     llvm_unreachable(
5951            "Can only end up with a standard conversion sequence or failure");
5952   }
5953 }
5954 
5955 /// \brief Adds a conversion function template specialization
5956 /// candidate to the overload set, using template argument deduction
5957 /// to deduce the template arguments of the conversion function
5958 /// template from the type that we are converting to (C++
5959 /// [temp.deduct.conv]).
5960 void
5961 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5962                                      DeclAccessPair FoundDecl,
5963                                      CXXRecordDecl *ActingDC,
5964                                      Expr *From, QualType ToType,
5965                                      OverloadCandidateSet &CandidateSet) {
5966   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5967          "Only conversion function templates permitted here");
5968 
5969   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5970     return;
5971 
5972   TemplateDeductionInfo Info(CandidateSet.getLocation());
5973   CXXConversionDecl *Specialization = 0;
5974   if (TemplateDeductionResult Result
5975         = DeduceTemplateArguments(FunctionTemplate, ToType,
5976                                   Specialization, Info)) {
5977     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5978     Candidate.FoundDecl = FoundDecl;
5979     Candidate.Function = FunctionTemplate->getTemplatedDecl();
5980     Candidate.Viable = false;
5981     Candidate.FailureKind = ovl_fail_bad_deduction;
5982     Candidate.IsSurrogate = false;
5983     Candidate.IgnoreObjectArgument = false;
5984     Candidate.ExplicitCallArguments = 1;
5985     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5986                                                           Info);
5987     return;
5988   }
5989 
5990   // Add the conversion function template specialization produced by
5991   // template argument deduction as a candidate.
5992   assert(Specialization && "Missing function template specialization?");
5993   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5994                          CandidateSet);
5995 }
5996 
5997 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5998 /// converts the given @c Object to a function pointer via the
5999 /// conversion function @c Conversion, and then attempts to call it
6000 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6001 /// the type of function that we'll eventually be calling.
6002 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6003                                  DeclAccessPair FoundDecl,
6004                                  CXXRecordDecl *ActingContext,
6005                                  const FunctionProtoType *Proto,
6006                                  Expr *Object,
6007                                  ArrayRef<Expr *> Args,
6008                                  OverloadCandidateSet& CandidateSet) {
6009   if (!CandidateSet.isNewCandidate(Conversion))
6010     return;
6011 
6012   // Overload resolution is always an unevaluated context.
6013   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6014 
6015   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6016   Candidate.FoundDecl = FoundDecl;
6017   Candidate.Function = 0;
6018   Candidate.Surrogate = Conversion;
6019   Candidate.Viable = true;
6020   Candidate.IsSurrogate = true;
6021   Candidate.IgnoreObjectArgument = false;
6022   Candidate.ExplicitCallArguments = Args.size();
6023 
6024   // Determine the implicit conversion sequence for the implicit
6025   // object parameter.
6026   ImplicitConversionSequence ObjectInit
6027     = TryObjectArgumentInitialization(*this, Object->getType(),
6028                                       Object->Classify(Context),
6029                                       Conversion, ActingContext);
6030   if (ObjectInit.isBad()) {
6031     Candidate.Viable = false;
6032     Candidate.FailureKind = ovl_fail_bad_conversion;
6033     Candidate.Conversions[0] = ObjectInit;
6034     return;
6035   }
6036 
6037   // The first conversion is actually a user-defined conversion whose
6038   // first conversion is ObjectInit's standard conversion (which is
6039   // effectively a reference binding). Record it as such.
6040   Candidate.Conversions[0].setUserDefined();
6041   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6042   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6043   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6044   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6045   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6046   Candidate.Conversions[0].UserDefined.After
6047     = Candidate.Conversions[0].UserDefined.Before;
6048   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6049 
6050   // Find the
6051   unsigned NumArgsInProto = Proto->getNumArgs();
6052 
6053   // (C++ 13.3.2p2): A candidate function having fewer than m
6054   // parameters is viable only if it has an ellipsis in its parameter
6055   // list (8.3.5).
6056   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
6057     Candidate.Viable = false;
6058     Candidate.FailureKind = ovl_fail_too_many_arguments;
6059     return;
6060   }
6061 
6062   // Function types don't have any default arguments, so just check if
6063   // we have enough arguments.
6064   if (Args.size() < NumArgsInProto) {
6065     // Not enough arguments.
6066     Candidate.Viable = false;
6067     Candidate.FailureKind = ovl_fail_too_few_arguments;
6068     return;
6069   }
6070 
6071   // Determine the implicit conversion sequences for each of the
6072   // arguments.
6073   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6074     if (ArgIdx < NumArgsInProto) {
6075       // (C++ 13.3.2p3): for F to be a viable function, there shall
6076       // exist for each argument an implicit conversion sequence
6077       // (13.3.3.1) that converts that argument to the corresponding
6078       // parameter of F.
6079       QualType ParamType = Proto->getArgType(ArgIdx);
6080       Candidate.Conversions[ArgIdx + 1]
6081         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6082                                 /*SuppressUserConversions=*/false,
6083                                 /*InOverloadResolution=*/false,
6084                                 /*AllowObjCWritebackConversion=*/
6085                                   getLangOpts().ObjCAutoRefCount);
6086       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6087         Candidate.Viable = false;
6088         Candidate.FailureKind = ovl_fail_bad_conversion;
6089         break;
6090       }
6091     } else {
6092       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6093       // argument for which there is no corresponding parameter is
6094       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6095       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6096     }
6097   }
6098 }
6099 
6100 /// \brief Add overload candidates for overloaded operators that are
6101 /// member functions.
6102 ///
6103 /// Add the overloaded operator candidates that are member functions
6104 /// for the operator Op that was used in an operator expression such
6105 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6106 /// CandidateSet will store the added overload candidates. (C++
6107 /// [over.match.oper]).
6108 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6109                                        SourceLocation OpLoc,
6110                                        ArrayRef<Expr *> Args,
6111                                        OverloadCandidateSet& CandidateSet,
6112                                        SourceRange OpRange) {
6113   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6114 
6115   // C++ [over.match.oper]p3:
6116   //   For a unary operator @ with an operand of a type whose
6117   //   cv-unqualified version is T1, and for a binary operator @ with
6118   //   a left operand of a type whose cv-unqualified version is T1 and
6119   //   a right operand of a type whose cv-unqualified version is T2,
6120   //   three sets of candidate functions, designated member
6121   //   candidates, non-member candidates and built-in candidates, are
6122   //   constructed as follows:
6123   QualType T1 = Args[0]->getType();
6124 
6125   //     -- If T1 is a complete class type or a class currently being
6126   //        defined, the set of member candidates is the result of the
6127   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6128   //        the set of member candidates is empty.
6129   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6130     // Complete the type if it can be completed.
6131     RequireCompleteType(OpLoc, T1, 0);
6132     // If the type is neither complete nor being defined, bail out now.
6133     if (!T1Rec->getDecl()->getDefinition())
6134       return;
6135 
6136     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6137     LookupQualifiedName(Operators, T1Rec->getDecl());
6138     Operators.suppressDiagnostics();
6139 
6140     for (LookupResult::iterator Oper = Operators.begin(),
6141                              OperEnd = Operators.end();
6142          Oper != OperEnd;
6143          ++Oper)
6144       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6145                          Args[0]->Classify(Context),
6146                          Args.slice(1),
6147                          CandidateSet,
6148                          /* SuppressUserConversions = */ false);
6149   }
6150 }
6151 
6152 /// AddBuiltinCandidate - Add a candidate for a built-in
6153 /// operator. ResultTy and ParamTys are the result and parameter types
6154 /// of the built-in candidate, respectively. Args and NumArgs are the
6155 /// arguments being passed to the candidate. IsAssignmentOperator
6156 /// should be true when this built-in candidate is an assignment
6157 /// operator. NumContextualBoolArguments is the number of arguments
6158 /// (at the beginning of the argument list) that will be contextually
6159 /// converted to bool.
6160 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6161                                ArrayRef<Expr *> Args,
6162                                OverloadCandidateSet& CandidateSet,
6163                                bool IsAssignmentOperator,
6164                                unsigned NumContextualBoolArguments) {
6165   // Overload resolution is always an unevaluated context.
6166   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6167 
6168   // Add this candidate
6169   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6170   Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
6171   Candidate.Function = 0;
6172   Candidate.IsSurrogate = false;
6173   Candidate.IgnoreObjectArgument = false;
6174   Candidate.BuiltinTypes.ResultTy = ResultTy;
6175   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6176     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6177 
6178   // Determine the implicit conversion sequences for each of the
6179   // arguments.
6180   Candidate.Viable = true;
6181   Candidate.ExplicitCallArguments = Args.size();
6182   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6183     // C++ [over.match.oper]p4:
6184     //   For the built-in assignment operators, conversions of the
6185     //   left operand are restricted as follows:
6186     //     -- no temporaries are introduced to hold the left operand, and
6187     //     -- no user-defined conversions are applied to the left
6188     //        operand to achieve a type match with the left-most
6189     //        parameter of a built-in candidate.
6190     //
6191     // We block these conversions by turning off user-defined
6192     // conversions, since that is the only way that initialization of
6193     // a reference to a non-class type can occur from something that
6194     // is not of the same type.
6195     if (ArgIdx < NumContextualBoolArguments) {
6196       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6197              "Contextual conversion to bool requires bool type");
6198       Candidate.Conversions[ArgIdx]
6199         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6200     } else {
6201       Candidate.Conversions[ArgIdx]
6202         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6203                                 ArgIdx == 0 && IsAssignmentOperator,
6204                                 /*InOverloadResolution=*/false,
6205                                 /*AllowObjCWritebackConversion=*/
6206                                   getLangOpts().ObjCAutoRefCount);
6207     }
6208     if (Candidate.Conversions[ArgIdx].isBad()) {
6209       Candidate.Viable = false;
6210       Candidate.FailureKind = ovl_fail_bad_conversion;
6211       break;
6212     }
6213   }
6214 }
6215 
6216 namespace {
6217 
6218 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6219 /// candidate operator functions for built-in operators (C++
6220 /// [over.built]). The types are separated into pointer types and
6221 /// enumeration types.
6222 class BuiltinCandidateTypeSet  {
6223   /// TypeSet - A set of types.
6224   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6225 
6226   /// PointerTypes - The set of pointer types that will be used in the
6227   /// built-in candidates.
6228   TypeSet PointerTypes;
6229 
6230   /// MemberPointerTypes - The set of member pointer types that will be
6231   /// used in the built-in candidates.
6232   TypeSet MemberPointerTypes;
6233 
6234   /// EnumerationTypes - The set of enumeration types that will be
6235   /// used in the built-in candidates.
6236   TypeSet EnumerationTypes;
6237 
6238   /// \brief The set of vector types that will be used in the built-in
6239   /// candidates.
6240   TypeSet VectorTypes;
6241 
6242   /// \brief A flag indicating non-record types are viable candidates
6243   bool HasNonRecordTypes;
6244 
6245   /// \brief A flag indicating whether either arithmetic or enumeration types
6246   /// were present in the candidate set.
6247   bool HasArithmeticOrEnumeralTypes;
6248 
6249   /// \brief A flag indicating whether the nullptr type was present in the
6250   /// candidate set.
6251   bool HasNullPtrType;
6252 
6253   /// Sema - The semantic analysis instance where we are building the
6254   /// candidate type set.
6255   Sema &SemaRef;
6256 
6257   /// Context - The AST context in which we will build the type sets.
6258   ASTContext &Context;
6259 
6260   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6261                                                const Qualifiers &VisibleQuals);
6262   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6263 
6264 public:
6265   /// iterator - Iterates through the types that are part of the set.
6266   typedef TypeSet::iterator iterator;
6267 
6268   BuiltinCandidateTypeSet(Sema &SemaRef)
6269     : HasNonRecordTypes(false),
6270       HasArithmeticOrEnumeralTypes(false),
6271       HasNullPtrType(false),
6272       SemaRef(SemaRef),
6273       Context(SemaRef.Context) { }
6274 
6275   void AddTypesConvertedFrom(QualType Ty,
6276                              SourceLocation Loc,
6277                              bool AllowUserConversions,
6278                              bool AllowExplicitConversions,
6279                              const Qualifiers &VisibleTypeConversionsQuals);
6280 
6281   /// pointer_begin - First pointer type found;
6282   iterator pointer_begin() { return PointerTypes.begin(); }
6283 
6284   /// pointer_end - Past the last pointer type found;
6285   iterator pointer_end() { return PointerTypes.end(); }
6286 
6287   /// member_pointer_begin - First member pointer type found;
6288   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6289 
6290   /// member_pointer_end - Past the last member pointer type found;
6291   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6292 
6293   /// enumeration_begin - First enumeration type found;
6294   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6295 
6296   /// enumeration_end - Past the last enumeration type found;
6297   iterator enumeration_end() { return EnumerationTypes.end(); }
6298 
6299   iterator vector_begin() { return VectorTypes.begin(); }
6300   iterator vector_end() { return VectorTypes.end(); }
6301 
6302   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6303   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6304   bool hasNullPtrType() const { return HasNullPtrType; }
6305 };
6306 
6307 } // end anonymous namespace
6308 
6309 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6310 /// the set of pointer types along with any more-qualified variants of
6311 /// that type. For example, if @p Ty is "int const *", this routine
6312 /// will add "int const *", "int const volatile *", "int const
6313 /// restrict *", and "int const volatile restrict *" to the set of
6314 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6315 /// false otherwise.
6316 ///
6317 /// FIXME: what to do about extended qualifiers?
6318 bool
6319 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6320                                              const Qualifiers &VisibleQuals) {
6321 
6322   // Insert this type.
6323   if (!PointerTypes.insert(Ty))
6324     return false;
6325 
6326   QualType PointeeTy;
6327   const PointerType *PointerTy = Ty->getAs<PointerType>();
6328   bool buildObjCPtr = false;
6329   if (!PointerTy) {
6330     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6331     PointeeTy = PTy->getPointeeType();
6332     buildObjCPtr = true;
6333   } else {
6334     PointeeTy = PointerTy->getPointeeType();
6335   }
6336 
6337   // Don't add qualified variants of arrays. For one, they're not allowed
6338   // (the qualifier would sink to the element type), and for another, the
6339   // only overload situation where it matters is subscript or pointer +- int,
6340   // and those shouldn't have qualifier variants anyway.
6341   if (PointeeTy->isArrayType())
6342     return true;
6343 
6344   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6345   bool hasVolatile = VisibleQuals.hasVolatile();
6346   bool hasRestrict = VisibleQuals.hasRestrict();
6347 
6348   // Iterate through all strict supersets of BaseCVR.
6349   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6350     if ((CVR | BaseCVR) != CVR) continue;
6351     // Skip over volatile if no volatile found anywhere in the types.
6352     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6353 
6354     // Skip over restrict if no restrict found anywhere in the types, or if
6355     // the type cannot be restrict-qualified.
6356     if ((CVR & Qualifiers::Restrict) &&
6357         (!hasRestrict ||
6358          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6359       continue;
6360 
6361     // Build qualified pointee type.
6362     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6363 
6364     // Build qualified pointer type.
6365     QualType QPointerTy;
6366     if (!buildObjCPtr)
6367       QPointerTy = Context.getPointerType(QPointeeTy);
6368     else
6369       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6370 
6371     // Insert qualified pointer type.
6372     PointerTypes.insert(QPointerTy);
6373   }
6374 
6375   return true;
6376 }
6377 
6378 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6379 /// to the set of pointer types along with any more-qualified variants of
6380 /// that type. For example, if @p Ty is "int const *", this routine
6381 /// will add "int const *", "int const volatile *", "int const
6382 /// restrict *", and "int const volatile restrict *" to the set of
6383 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6384 /// false otherwise.
6385 ///
6386 /// FIXME: what to do about extended qualifiers?
6387 bool
6388 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6389     QualType Ty) {
6390   // Insert this type.
6391   if (!MemberPointerTypes.insert(Ty))
6392     return false;
6393 
6394   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6395   assert(PointerTy && "type was not a member pointer type!");
6396 
6397   QualType PointeeTy = PointerTy->getPointeeType();
6398   // Don't add qualified variants of arrays. For one, they're not allowed
6399   // (the qualifier would sink to the element type), and for another, the
6400   // only overload situation where it matters is subscript or pointer +- int,
6401   // and those shouldn't have qualifier variants anyway.
6402   if (PointeeTy->isArrayType())
6403     return true;
6404   const Type *ClassTy = PointerTy->getClass();
6405 
6406   // Iterate through all strict supersets of the pointee type's CVR
6407   // qualifiers.
6408   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6409   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6410     if ((CVR | BaseCVR) != CVR) continue;
6411 
6412     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6413     MemberPointerTypes.insert(
6414       Context.getMemberPointerType(QPointeeTy, ClassTy));
6415   }
6416 
6417   return true;
6418 }
6419 
6420 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6421 /// Ty can be implicit converted to the given set of @p Types. We're
6422 /// primarily interested in pointer types and enumeration types. We also
6423 /// take member pointer types, for the conditional operator.
6424 /// AllowUserConversions is true if we should look at the conversion
6425 /// functions of a class type, and AllowExplicitConversions if we
6426 /// should also include the explicit conversion functions of a class
6427 /// type.
6428 void
6429 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6430                                                SourceLocation Loc,
6431                                                bool AllowUserConversions,
6432                                                bool AllowExplicitConversions,
6433                                                const Qualifiers &VisibleQuals) {
6434   // Only deal with canonical types.
6435   Ty = Context.getCanonicalType(Ty);
6436 
6437   // Look through reference types; they aren't part of the type of an
6438   // expression for the purposes of conversions.
6439   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6440     Ty = RefTy->getPointeeType();
6441 
6442   // If we're dealing with an array type, decay to the pointer.
6443   if (Ty->isArrayType())
6444     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6445 
6446   // Otherwise, we don't care about qualifiers on the type.
6447   Ty = Ty.getLocalUnqualifiedType();
6448 
6449   // Flag if we ever add a non-record type.
6450   const RecordType *TyRec = Ty->getAs<RecordType>();
6451   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6452 
6453   // Flag if we encounter an arithmetic type.
6454   HasArithmeticOrEnumeralTypes =
6455     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6456 
6457   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6458     PointerTypes.insert(Ty);
6459   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6460     // Insert our type, and its more-qualified variants, into the set
6461     // of types.
6462     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6463       return;
6464   } else if (Ty->isMemberPointerType()) {
6465     // Member pointers are far easier, since the pointee can't be converted.
6466     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6467       return;
6468   } else if (Ty->isEnumeralType()) {
6469     HasArithmeticOrEnumeralTypes = true;
6470     EnumerationTypes.insert(Ty);
6471   } else if (Ty->isVectorType()) {
6472     // We treat vector types as arithmetic types in many contexts as an
6473     // extension.
6474     HasArithmeticOrEnumeralTypes = true;
6475     VectorTypes.insert(Ty);
6476   } else if (Ty->isNullPtrType()) {
6477     HasNullPtrType = true;
6478   } else if (AllowUserConversions && TyRec) {
6479     // No conversion functions in incomplete types.
6480     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6481       return;
6482 
6483     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6484     std::pair<CXXRecordDecl::conversion_iterator,
6485               CXXRecordDecl::conversion_iterator>
6486       Conversions = ClassDecl->getVisibleConversionFunctions();
6487     for (CXXRecordDecl::conversion_iterator
6488            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6489       NamedDecl *D = I.getDecl();
6490       if (isa<UsingShadowDecl>(D))
6491         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6492 
6493       // Skip conversion function templates; they don't tell us anything
6494       // about which builtin types we can convert to.
6495       if (isa<FunctionTemplateDecl>(D))
6496         continue;
6497 
6498       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6499       if (AllowExplicitConversions || !Conv->isExplicit()) {
6500         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6501                               VisibleQuals);
6502       }
6503     }
6504   }
6505 }
6506 
6507 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6508 /// the volatile- and non-volatile-qualified assignment operators for the
6509 /// given type to the candidate set.
6510 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6511                                                    QualType T,
6512                                                    ArrayRef<Expr *> Args,
6513                                     OverloadCandidateSet &CandidateSet) {
6514   QualType ParamTypes[2];
6515 
6516   // T& operator=(T&, T)
6517   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6518   ParamTypes[1] = T;
6519   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6520                         /*IsAssignmentOperator=*/true);
6521 
6522   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6523     // volatile T& operator=(volatile T&, T)
6524     ParamTypes[0]
6525       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6526     ParamTypes[1] = T;
6527     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6528                           /*IsAssignmentOperator=*/true);
6529   }
6530 }
6531 
6532 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6533 /// if any, found in visible type conversion functions found in ArgExpr's type.
6534 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6535     Qualifiers VRQuals;
6536     const RecordType *TyRec;
6537     if (const MemberPointerType *RHSMPType =
6538         ArgExpr->getType()->getAs<MemberPointerType>())
6539       TyRec = RHSMPType->getClass()->getAs<RecordType>();
6540     else
6541       TyRec = ArgExpr->getType()->getAs<RecordType>();
6542     if (!TyRec) {
6543       // Just to be safe, assume the worst case.
6544       VRQuals.addVolatile();
6545       VRQuals.addRestrict();
6546       return VRQuals;
6547     }
6548 
6549     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6550     if (!ClassDecl->hasDefinition())
6551       return VRQuals;
6552 
6553     std::pair<CXXRecordDecl::conversion_iterator,
6554               CXXRecordDecl::conversion_iterator>
6555       Conversions = ClassDecl->getVisibleConversionFunctions();
6556 
6557     for (CXXRecordDecl::conversion_iterator
6558            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6559       NamedDecl *D = I.getDecl();
6560       if (isa<UsingShadowDecl>(D))
6561         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6562       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6563         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6564         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6565           CanTy = ResTypeRef->getPointeeType();
6566         // Need to go down the pointer/mempointer chain and add qualifiers
6567         // as see them.
6568         bool done = false;
6569         while (!done) {
6570           if (CanTy.isRestrictQualified())
6571             VRQuals.addRestrict();
6572           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6573             CanTy = ResTypePtr->getPointeeType();
6574           else if (const MemberPointerType *ResTypeMPtr =
6575                 CanTy->getAs<MemberPointerType>())
6576             CanTy = ResTypeMPtr->getPointeeType();
6577           else
6578             done = true;
6579           if (CanTy.isVolatileQualified())
6580             VRQuals.addVolatile();
6581           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6582             return VRQuals;
6583         }
6584       }
6585     }
6586     return VRQuals;
6587 }
6588 
6589 namespace {
6590 
6591 /// \brief Helper class to manage the addition of builtin operator overload
6592 /// candidates. It provides shared state and utility methods used throughout
6593 /// the process, as well as a helper method to add each group of builtin
6594 /// operator overloads from the standard to a candidate set.
6595 class BuiltinOperatorOverloadBuilder {
6596   // Common instance state available to all overload candidate addition methods.
6597   Sema &S;
6598   ArrayRef<Expr *> Args;
6599   Qualifiers VisibleTypeConversionsQuals;
6600   bool HasArithmeticOrEnumeralCandidateType;
6601   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6602   OverloadCandidateSet &CandidateSet;
6603 
6604   // Define some constants used to index and iterate over the arithemetic types
6605   // provided via the getArithmeticType() method below.
6606   // The "promoted arithmetic types" are the arithmetic
6607   // types are that preserved by promotion (C++ [over.built]p2).
6608   static const unsigned FirstIntegralType = 3;
6609   static const unsigned LastIntegralType = 20;
6610   static const unsigned FirstPromotedIntegralType = 3,
6611                         LastPromotedIntegralType = 11;
6612   static const unsigned FirstPromotedArithmeticType = 0,
6613                         LastPromotedArithmeticType = 11;
6614   static const unsigned NumArithmeticTypes = 20;
6615 
6616   /// \brief Get the canonical type for a given arithmetic type index.
6617   CanQualType getArithmeticType(unsigned index) {
6618     assert(index < NumArithmeticTypes);
6619     static CanQualType ASTContext::* const
6620       ArithmeticTypes[NumArithmeticTypes] = {
6621       // Start of promoted types.
6622       &ASTContext::FloatTy,
6623       &ASTContext::DoubleTy,
6624       &ASTContext::LongDoubleTy,
6625 
6626       // Start of integral types.
6627       &ASTContext::IntTy,
6628       &ASTContext::LongTy,
6629       &ASTContext::LongLongTy,
6630       &ASTContext::Int128Ty,
6631       &ASTContext::UnsignedIntTy,
6632       &ASTContext::UnsignedLongTy,
6633       &ASTContext::UnsignedLongLongTy,
6634       &ASTContext::UnsignedInt128Ty,
6635       // End of promoted types.
6636 
6637       &ASTContext::BoolTy,
6638       &ASTContext::CharTy,
6639       &ASTContext::WCharTy,
6640       &ASTContext::Char16Ty,
6641       &ASTContext::Char32Ty,
6642       &ASTContext::SignedCharTy,
6643       &ASTContext::ShortTy,
6644       &ASTContext::UnsignedCharTy,
6645       &ASTContext::UnsignedShortTy,
6646       // End of integral types.
6647       // FIXME: What about complex? What about half?
6648     };
6649     return S.Context.*ArithmeticTypes[index];
6650   }
6651 
6652   /// \brief Gets the canonical type resulting from the usual arithemetic
6653   /// converions for the given arithmetic types.
6654   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6655     // Accelerator table for performing the usual arithmetic conversions.
6656     // The rules are basically:
6657     //   - if either is floating-point, use the wider floating-point
6658     //   - if same signedness, use the higher rank
6659     //   - if same size, use unsigned of the higher rank
6660     //   - use the larger type
6661     // These rules, together with the axiom that higher ranks are
6662     // never smaller, are sufficient to precompute all of these results
6663     // *except* when dealing with signed types of higher rank.
6664     // (we could precompute SLL x UI for all known platforms, but it's
6665     // better not to make any assumptions).
6666     // We assume that int128 has a higher rank than long long on all platforms.
6667     enum PromotedType {
6668             Dep=-1,
6669             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6670     };
6671     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6672                                         [LastPromotedArithmeticType] = {
6673 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6674 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6675 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6676 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6677 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6678 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6679 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6680 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6681 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6682 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6683 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6684     };
6685 
6686     assert(L < LastPromotedArithmeticType);
6687     assert(R < LastPromotedArithmeticType);
6688     int Idx = ConversionsTable[L][R];
6689 
6690     // Fast path: the table gives us a concrete answer.
6691     if (Idx != Dep) return getArithmeticType(Idx);
6692 
6693     // Slow path: we need to compare widths.
6694     // An invariant is that the signed type has higher rank.
6695     CanQualType LT = getArithmeticType(L),
6696                 RT = getArithmeticType(R);
6697     unsigned LW = S.Context.getIntWidth(LT),
6698              RW = S.Context.getIntWidth(RT);
6699 
6700     // If they're different widths, use the signed type.
6701     if (LW > RW) return LT;
6702     else if (LW < RW) return RT;
6703 
6704     // Otherwise, use the unsigned type of the signed type's rank.
6705     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6706     assert(L == SLL || R == SLL);
6707     return S.Context.UnsignedLongLongTy;
6708   }
6709 
6710   /// \brief Helper method to factor out the common pattern of adding overloads
6711   /// for '++' and '--' builtin operators.
6712   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6713                                            bool HasVolatile,
6714                                            bool HasRestrict) {
6715     QualType ParamTypes[2] = {
6716       S.Context.getLValueReferenceType(CandidateTy),
6717       S.Context.IntTy
6718     };
6719 
6720     // Non-volatile version.
6721     if (Args.size() == 1)
6722       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6723     else
6724       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6725 
6726     // Use a heuristic to reduce number of builtin candidates in the set:
6727     // add volatile version only if there are conversions to a volatile type.
6728     if (HasVolatile) {
6729       ParamTypes[0] =
6730         S.Context.getLValueReferenceType(
6731           S.Context.getVolatileType(CandidateTy));
6732       if (Args.size() == 1)
6733         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6734       else
6735         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6736     }
6737 
6738     // Add restrict version only if there are conversions to a restrict type
6739     // and our candidate type is a non-restrict-qualified pointer.
6740     if (HasRestrict && CandidateTy->isAnyPointerType() &&
6741         !CandidateTy.isRestrictQualified()) {
6742       ParamTypes[0]
6743         = S.Context.getLValueReferenceType(
6744             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6745       if (Args.size() == 1)
6746         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6747       else
6748         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6749 
6750       if (HasVolatile) {
6751         ParamTypes[0]
6752           = S.Context.getLValueReferenceType(
6753               S.Context.getCVRQualifiedType(CandidateTy,
6754                                             (Qualifiers::Volatile |
6755                                              Qualifiers::Restrict)));
6756         if (Args.size() == 1)
6757           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6758         else
6759           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6760       }
6761     }
6762 
6763   }
6764 
6765 public:
6766   BuiltinOperatorOverloadBuilder(
6767     Sema &S, ArrayRef<Expr *> Args,
6768     Qualifiers VisibleTypeConversionsQuals,
6769     bool HasArithmeticOrEnumeralCandidateType,
6770     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6771     OverloadCandidateSet &CandidateSet)
6772     : S(S), Args(Args),
6773       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6774       HasArithmeticOrEnumeralCandidateType(
6775         HasArithmeticOrEnumeralCandidateType),
6776       CandidateTypes(CandidateTypes),
6777       CandidateSet(CandidateSet) {
6778     // Validate some of our static helper constants in debug builds.
6779     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6780            "Invalid first promoted integral type");
6781     assert(getArithmeticType(LastPromotedIntegralType - 1)
6782              == S.Context.UnsignedInt128Ty &&
6783            "Invalid last promoted integral type");
6784     assert(getArithmeticType(FirstPromotedArithmeticType)
6785              == S.Context.FloatTy &&
6786            "Invalid first promoted arithmetic type");
6787     assert(getArithmeticType(LastPromotedArithmeticType - 1)
6788              == S.Context.UnsignedInt128Ty &&
6789            "Invalid last promoted arithmetic type");
6790   }
6791 
6792   // C++ [over.built]p3:
6793   //
6794   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6795   //   is either volatile or empty, there exist candidate operator
6796   //   functions of the form
6797   //
6798   //       VQ T&      operator++(VQ T&);
6799   //       T          operator++(VQ T&, int);
6800   //
6801   // C++ [over.built]p4:
6802   //
6803   //   For every pair (T, VQ), where T is an arithmetic type other
6804   //   than bool, and VQ is either volatile or empty, there exist
6805   //   candidate operator functions of the form
6806   //
6807   //       VQ T&      operator--(VQ T&);
6808   //       T          operator--(VQ T&, int);
6809   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6810     if (!HasArithmeticOrEnumeralCandidateType)
6811       return;
6812 
6813     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6814          Arith < NumArithmeticTypes; ++Arith) {
6815       addPlusPlusMinusMinusStyleOverloads(
6816         getArithmeticType(Arith),
6817         VisibleTypeConversionsQuals.hasVolatile(),
6818         VisibleTypeConversionsQuals.hasRestrict());
6819     }
6820   }
6821 
6822   // C++ [over.built]p5:
6823   //
6824   //   For every pair (T, VQ), where T is a cv-qualified or
6825   //   cv-unqualified object type, and VQ is either volatile or
6826   //   empty, there exist candidate operator functions of the form
6827   //
6828   //       T*VQ&      operator++(T*VQ&);
6829   //       T*VQ&      operator--(T*VQ&);
6830   //       T*         operator++(T*VQ&, int);
6831   //       T*         operator--(T*VQ&, int);
6832   void addPlusPlusMinusMinusPointerOverloads() {
6833     for (BuiltinCandidateTypeSet::iterator
6834               Ptr = CandidateTypes[0].pointer_begin(),
6835            PtrEnd = CandidateTypes[0].pointer_end();
6836          Ptr != PtrEnd; ++Ptr) {
6837       // Skip pointer types that aren't pointers to object types.
6838       if (!(*Ptr)->getPointeeType()->isObjectType())
6839         continue;
6840 
6841       addPlusPlusMinusMinusStyleOverloads(*Ptr,
6842         (!(*Ptr).isVolatileQualified() &&
6843          VisibleTypeConversionsQuals.hasVolatile()),
6844         (!(*Ptr).isRestrictQualified() &&
6845          VisibleTypeConversionsQuals.hasRestrict()));
6846     }
6847   }
6848 
6849   // C++ [over.built]p6:
6850   //   For every cv-qualified or cv-unqualified object type T, there
6851   //   exist candidate operator functions of the form
6852   //
6853   //       T&         operator*(T*);
6854   //
6855   // C++ [over.built]p7:
6856   //   For every function type T that does not have cv-qualifiers or a
6857   //   ref-qualifier, there exist candidate operator functions of the form
6858   //       T&         operator*(T*);
6859   void addUnaryStarPointerOverloads() {
6860     for (BuiltinCandidateTypeSet::iterator
6861               Ptr = CandidateTypes[0].pointer_begin(),
6862            PtrEnd = CandidateTypes[0].pointer_end();
6863          Ptr != PtrEnd; ++Ptr) {
6864       QualType ParamTy = *Ptr;
6865       QualType PointeeTy = ParamTy->getPointeeType();
6866       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6867         continue;
6868 
6869       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6870         if (Proto->getTypeQuals() || Proto->getRefQualifier())
6871           continue;
6872 
6873       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6874                             &ParamTy, Args, CandidateSet);
6875     }
6876   }
6877 
6878   // C++ [over.built]p9:
6879   //  For every promoted arithmetic type T, there exist candidate
6880   //  operator functions of the form
6881   //
6882   //       T         operator+(T);
6883   //       T         operator-(T);
6884   void addUnaryPlusOrMinusArithmeticOverloads() {
6885     if (!HasArithmeticOrEnumeralCandidateType)
6886       return;
6887 
6888     for (unsigned Arith = FirstPromotedArithmeticType;
6889          Arith < LastPromotedArithmeticType; ++Arith) {
6890       QualType ArithTy = getArithmeticType(Arith);
6891       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
6892     }
6893 
6894     // Extension: We also add these operators for vector types.
6895     for (BuiltinCandidateTypeSet::iterator
6896               Vec = CandidateTypes[0].vector_begin(),
6897            VecEnd = CandidateTypes[0].vector_end();
6898          Vec != VecEnd; ++Vec) {
6899       QualType VecTy = *Vec;
6900       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
6901     }
6902   }
6903 
6904   // C++ [over.built]p8:
6905   //   For every type T, there exist candidate operator functions of
6906   //   the form
6907   //
6908   //       T*         operator+(T*);
6909   void addUnaryPlusPointerOverloads() {
6910     for (BuiltinCandidateTypeSet::iterator
6911               Ptr = CandidateTypes[0].pointer_begin(),
6912            PtrEnd = CandidateTypes[0].pointer_end();
6913          Ptr != PtrEnd; ++Ptr) {
6914       QualType ParamTy = *Ptr;
6915       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
6916     }
6917   }
6918 
6919   // C++ [over.built]p10:
6920   //   For every promoted integral type T, there exist candidate
6921   //   operator functions of the form
6922   //
6923   //        T         operator~(T);
6924   void addUnaryTildePromotedIntegralOverloads() {
6925     if (!HasArithmeticOrEnumeralCandidateType)
6926       return;
6927 
6928     for (unsigned Int = FirstPromotedIntegralType;
6929          Int < LastPromotedIntegralType; ++Int) {
6930       QualType IntTy = getArithmeticType(Int);
6931       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
6932     }
6933 
6934     // Extension: We also add this operator for vector types.
6935     for (BuiltinCandidateTypeSet::iterator
6936               Vec = CandidateTypes[0].vector_begin(),
6937            VecEnd = CandidateTypes[0].vector_end();
6938          Vec != VecEnd; ++Vec) {
6939       QualType VecTy = *Vec;
6940       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
6941     }
6942   }
6943 
6944   // C++ [over.match.oper]p16:
6945   //   For every pointer to member type T, there exist candidate operator
6946   //   functions of the form
6947   //
6948   //        bool operator==(T,T);
6949   //        bool operator!=(T,T);
6950   void addEqualEqualOrNotEqualMemberPointerOverloads() {
6951     /// Set of (canonical) types that we've already handled.
6952     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6953 
6954     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6955       for (BuiltinCandidateTypeSet::iterator
6956                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6957              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6958            MemPtr != MemPtrEnd;
6959            ++MemPtr) {
6960         // Don't add the same builtin candidate twice.
6961         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6962           continue;
6963 
6964         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6965         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
6966       }
6967     }
6968   }
6969 
6970   // C++ [over.built]p15:
6971   //
6972   //   For every T, where T is an enumeration type, a pointer type, or
6973   //   std::nullptr_t, there exist candidate operator functions of the form
6974   //
6975   //        bool       operator<(T, T);
6976   //        bool       operator>(T, T);
6977   //        bool       operator<=(T, T);
6978   //        bool       operator>=(T, T);
6979   //        bool       operator==(T, T);
6980   //        bool       operator!=(T, T);
6981   void addRelationalPointerOrEnumeralOverloads() {
6982     // C++ [over.match.oper]p3:
6983     //   [...]the built-in candidates include all of the candidate operator
6984     //   functions defined in 13.6 that, compared to the given operator, [...]
6985     //   do not have the same parameter-type-list as any non-template non-member
6986     //   candidate.
6987     //
6988     // Note that in practice, this only affects enumeration types because there
6989     // aren't any built-in candidates of record type, and a user-defined operator
6990     // must have an operand of record or enumeration type. Also, the only other
6991     // overloaded operator with enumeration arguments, operator=,
6992     // cannot be overloaded for enumeration types, so this is the only place
6993     // where we must suppress candidates like this.
6994     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6995       UserDefinedBinaryOperators;
6996 
6997     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6998       if (CandidateTypes[ArgIdx].enumeration_begin() !=
6999           CandidateTypes[ArgIdx].enumeration_end()) {
7000         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7001                                          CEnd = CandidateSet.end();
7002              C != CEnd; ++C) {
7003           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7004             continue;
7005 
7006           if (C->Function->isFunctionTemplateSpecialization())
7007             continue;
7008 
7009           QualType FirstParamType =
7010             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7011           QualType SecondParamType =
7012             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7013 
7014           // Skip if either parameter isn't of enumeral type.
7015           if (!FirstParamType->isEnumeralType() ||
7016               !SecondParamType->isEnumeralType())
7017             continue;
7018 
7019           // Add this operator to the set of known user-defined operators.
7020           UserDefinedBinaryOperators.insert(
7021             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7022                            S.Context.getCanonicalType(SecondParamType)));
7023         }
7024       }
7025     }
7026 
7027     /// Set of (canonical) types that we've already handled.
7028     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7029 
7030     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7031       for (BuiltinCandidateTypeSet::iterator
7032                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7033              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7034            Ptr != PtrEnd; ++Ptr) {
7035         // Don't add the same builtin candidate twice.
7036         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7037           continue;
7038 
7039         QualType ParamTypes[2] = { *Ptr, *Ptr };
7040         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7041       }
7042       for (BuiltinCandidateTypeSet::iterator
7043                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7044              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7045            Enum != EnumEnd; ++Enum) {
7046         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7047 
7048         // Don't add the same builtin candidate twice, or if a user defined
7049         // candidate exists.
7050         if (!AddedTypes.insert(CanonType) ||
7051             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7052                                                             CanonType)))
7053           continue;
7054 
7055         QualType ParamTypes[2] = { *Enum, *Enum };
7056         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7057       }
7058 
7059       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7060         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7061         if (AddedTypes.insert(NullPtrTy) &&
7062             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7063                                                              NullPtrTy))) {
7064           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7065           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7066                                 CandidateSet);
7067         }
7068       }
7069     }
7070   }
7071 
7072   // C++ [over.built]p13:
7073   //
7074   //   For every cv-qualified or cv-unqualified object type T
7075   //   there exist candidate operator functions of the form
7076   //
7077   //      T*         operator+(T*, ptrdiff_t);
7078   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7079   //      T*         operator-(T*, ptrdiff_t);
7080   //      T*         operator+(ptrdiff_t, T*);
7081   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7082   //
7083   // C++ [over.built]p14:
7084   //
7085   //   For every T, where T is a pointer to object type, there
7086   //   exist candidate operator functions of the form
7087   //
7088   //      ptrdiff_t  operator-(T, T);
7089   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7090     /// Set of (canonical) types that we've already handled.
7091     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7092 
7093     for (int Arg = 0; Arg < 2; ++Arg) {
7094       QualType AsymetricParamTypes[2] = {
7095         S.Context.getPointerDiffType(),
7096         S.Context.getPointerDiffType(),
7097       };
7098       for (BuiltinCandidateTypeSet::iterator
7099                 Ptr = CandidateTypes[Arg].pointer_begin(),
7100              PtrEnd = CandidateTypes[Arg].pointer_end();
7101            Ptr != PtrEnd; ++Ptr) {
7102         QualType PointeeTy = (*Ptr)->getPointeeType();
7103         if (!PointeeTy->isObjectType())
7104           continue;
7105 
7106         AsymetricParamTypes[Arg] = *Ptr;
7107         if (Arg == 0 || Op == OO_Plus) {
7108           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7109           // T* operator+(ptrdiff_t, T*);
7110           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7111         }
7112         if (Op == OO_Minus) {
7113           // ptrdiff_t operator-(T, T);
7114           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7115             continue;
7116 
7117           QualType ParamTypes[2] = { *Ptr, *Ptr };
7118           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7119                                 Args, CandidateSet);
7120         }
7121       }
7122     }
7123   }
7124 
7125   // C++ [over.built]p12:
7126   //
7127   //   For every pair of promoted arithmetic types L and R, there
7128   //   exist candidate operator functions of the form
7129   //
7130   //        LR         operator*(L, R);
7131   //        LR         operator/(L, R);
7132   //        LR         operator+(L, R);
7133   //        LR         operator-(L, R);
7134   //        bool       operator<(L, R);
7135   //        bool       operator>(L, R);
7136   //        bool       operator<=(L, R);
7137   //        bool       operator>=(L, R);
7138   //        bool       operator==(L, R);
7139   //        bool       operator!=(L, R);
7140   //
7141   //   where LR is the result of the usual arithmetic conversions
7142   //   between types L and R.
7143   //
7144   // C++ [over.built]p24:
7145   //
7146   //   For every pair of promoted arithmetic types L and R, there exist
7147   //   candidate operator functions of the form
7148   //
7149   //        LR       operator?(bool, L, R);
7150   //
7151   //   where LR is the result of the usual arithmetic conversions
7152   //   between types L and R.
7153   // Our candidates ignore the first parameter.
7154   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7155     if (!HasArithmeticOrEnumeralCandidateType)
7156       return;
7157 
7158     for (unsigned Left = FirstPromotedArithmeticType;
7159          Left < LastPromotedArithmeticType; ++Left) {
7160       for (unsigned Right = FirstPromotedArithmeticType;
7161            Right < LastPromotedArithmeticType; ++Right) {
7162         QualType LandR[2] = { getArithmeticType(Left),
7163                               getArithmeticType(Right) };
7164         QualType Result =
7165           isComparison ? S.Context.BoolTy
7166                        : getUsualArithmeticConversions(Left, Right);
7167         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7168       }
7169     }
7170 
7171     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7172     // conditional operator for vector types.
7173     for (BuiltinCandidateTypeSet::iterator
7174               Vec1 = CandidateTypes[0].vector_begin(),
7175            Vec1End = CandidateTypes[0].vector_end();
7176          Vec1 != Vec1End; ++Vec1) {
7177       for (BuiltinCandidateTypeSet::iterator
7178                 Vec2 = CandidateTypes[1].vector_begin(),
7179              Vec2End = CandidateTypes[1].vector_end();
7180            Vec2 != Vec2End; ++Vec2) {
7181         QualType LandR[2] = { *Vec1, *Vec2 };
7182         QualType Result = S.Context.BoolTy;
7183         if (!isComparison) {
7184           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7185             Result = *Vec1;
7186           else
7187             Result = *Vec2;
7188         }
7189 
7190         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7191       }
7192     }
7193   }
7194 
7195   // C++ [over.built]p17:
7196   //
7197   //   For every pair of promoted integral types L and R, there
7198   //   exist candidate operator functions of the form
7199   //
7200   //      LR         operator%(L, R);
7201   //      LR         operator&(L, R);
7202   //      LR         operator^(L, R);
7203   //      LR         operator|(L, R);
7204   //      L          operator<<(L, R);
7205   //      L          operator>>(L, R);
7206   //
7207   //   where LR is the result of the usual arithmetic conversions
7208   //   between types L and R.
7209   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7210     if (!HasArithmeticOrEnumeralCandidateType)
7211       return;
7212 
7213     for (unsigned Left = FirstPromotedIntegralType;
7214          Left < LastPromotedIntegralType; ++Left) {
7215       for (unsigned Right = FirstPromotedIntegralType;
7216            Right < LastPromotedIntegralType; ++Right) {
7217         QualType LandR[2] = { getArithmeticType(Left),
7218                               getArithmeticType(Right) };
7219         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7220             ? LandR[0]
7221             : getUsualArithmeticConversions(Left, Right);
7222         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7223       }
7224     }
7225   }
7226 
7227   // C++ [over.built]p20:
7228   //
7229   //   For every pair (T, VQ), where T is an enumeration or
7230   //   pointer to member type and VQ is either volatile or
7231   //   empty, there exist candidate operator functions of the form
7232   //
7233   //        VQ T&      operator=(VQ T&, T);
7234   void addAssignmentMemberPointerOrEnumeralOverloads() {
7235     /// Set of (canonical) types that we've already handled.
7236     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7237 
7238     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7239       for (BuiltinCandidateTypeSet::iterator
7240                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7241              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7242            Enum != EnumEnd; ++Enum) {
7243         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7244           continue;
7245 
7246         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7247       }
7248 
7249       for (BuiltinCandidateTypeSet::iterator
7250                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7251              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7252            MemPtr != MemPtrEnd; ++MemPtr) {
7253         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7254           continue;
7255 
7256         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7257       }
7258     }
7259   }
7260 
7261   // C++ [over.built]p19:
7262   //
7263   //   For every pair (T, VQ), where T is any type and VQ is either
7264   //   volatile or empty, there exist candidate operator functions
7265   //   of the form
7266   //
7267   //        T*VQ&      operator=(T*VQ&, T*);
7268   //
7269   // C++ [over.built]p21:
7270   //
7271   //   For every pair (T, VQ), where T is a cv-qualified or
7272   //   cv-unqualified object type and VQ is either volatile or
7273   //   empty, there exist candidate operator functions of the form
7274   //
7275   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7276   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7277   void addAssignmentPointerOverloads(bool isEqualOp) {
7278     /// Set of (canonical) types that we've already handled.
7279     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7280 
7281     for (BuiltinCandidateTypeSet::iterator
7282               Ptr = CandidateTypes[0].pointer_begin(),
7283            PtrEnd = CandidateTypes[0].pointer_end();
7284          Ptr != PtrEnd; ++Ptr) {
7285       // If this is operator=, keep track of the builtin candidates we added.
7286       if (isEqualOp)
7287         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7288       else if (!(*Ptr)->getPointeeType()->isObjectType())
7289         continue;
7290 
7291       // non-volatile version
7292       QualType ParamTypes[2] = {
7293         S.Context.getLValueReferenceType(*Ptr),
7294         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7295       };
7296       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7297                             /*IsAssigmentOperator=*/ isEqualOp);
7298 
7299       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7300                           VisibleTypeConversionsQuals.hasVolatile();
7301       if (NeedVolatile) {
7302         // volatile version
7303         ParamTypes[0] =
7304           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7305         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7306                               /*IsAssigmentOperator=*/isEqualOp);
7307       }
7308 
7309       if (!(*Ptr).isRestrictQualified() &&
7310           VisibleTypeConversionsQuals.hasRestrict()) {
7311         // restrict version
7312         ParamTypes[0]
7313           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7314         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7315                               /*IsAssigmentOperator=*/isEqualOp);
7316 
7317         if (NeedVolatile) {
7318           // volatile restrict version
7319           ParamTypes[0]
7320             = S.Context.getLValueReferenceType(
7321                 S.Context.getCVRQualifiedType(*Ptr,
7322                                               (Qualifiers::Volatile |
7323                                                Qualifiers::Restrict)));
7324           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7325                                 /*IsAssigmentOperator=*/isEqualOp);
7326         }
7327       }
7328     }
7329 
7330     if (isEqualOp) {
7331       for (BuiltinCandidateTypeSet::iterator
7332                 Ptr = CandidateTypes[1].pointer_begin(),
7333              PtrEnd = CandidateTypes[1].pointer_end();
7334            Ptr != PtrEnd; ++Ptr) {
7335         // Make sure we don't add the same candidate twice.
7336         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7337           continue;
7338 
7339         QualType ParamTypes[2] = {
7340           S.Context.getLValueReferenceType(*Ptr),
7341           *Ptr,
7342         };
7343 
7344         // non-volatile version
7345         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7346                               /*IsAssigmentOperator=*/true);
7347 
7348         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7349                            VisibleTypeConversionsQuals.hasVolatile();
7350         if (NeedVolatile) {
7351           // volatile version
7352           ParamTypes[0] =
7353             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7354           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7355                                 /*IsAssigmentOperator=*/true);
7356         }
7357 
7358         if (!(*Ptr).isRestrictQualified() &&
7359             VisibleTypeConversionsQuals.hasRestrict()) {
7360           // restrict version
7361           ParamTypes[0]
7362             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7363           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7364                                 /*IsAssigmentOperator=*/true);
7365 
7366           if (NeedVolatile) {
7367             // volatile restrict version
7368             ParamTypes[0]
7369               = S.Context.getLValueReferenceType(
7370                   S.Context.getCVRQualifiedType(*Ptr,
7371                                                 (Qualifiers::Volatile |
7372                                                  Qualifiers::Restrict)));
7373             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7374                                   /*IsAssigmentOperator=*/true);
7375           }
7376         }
7377       }
7378     }
7379   }
7380 
7381   // C++ [over.built]p18:
7382   //
7383   //   For every triple (L, VQ, R), where L is an arithmetic type,
7384   //   VQ is either volatile or empty, and R is a promoted
7385   //   arithmetic type, there exist candidate operator functions of
7386   //   the form
7387   //
7388   //        VQ L&      operator=(VQ L&, R);
7389   //        VQ L&      operator*=(VQ L&, R);
7390   //        VQ L&      operator/=(VQ L&, R);
7391   //        VQ L&      operator+=(VQ L&, R);
7392   //        VQ L&      operator-=(VQ L&, R);
7393   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7394     if (!HasArithmeticOrEnumeralCandidateType)
7395       return;
7396 
7397     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7398       for (unsigned Right = FirstPromotedArithmeticType;
7399            Right < LastPromotedArithmeticType; ++Right) {
7400         QualType ParamTypes[2];
7401         ParamTypes[1] = getArithmeticType(Right);
7402 
7403         // Add this built-in operator as a candidate (VQ is empty).
7404         ParamTypes[0] =
7405           S.Context.getLValueReferenceType(getArithmeticType(Left));
7406         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7407                               /*IsAssigmentOperator=*/isEqualOp);
7408 
7409         // Add this built-in operator as a candidate (VQ is 'volatile').
7410         if (VisibleTypeConversionsQuals.hasVolatile()) {
7411           ParamTypes[0] =
7412             S.Context.getVolatileType(getArithmeticType(Left));
7413           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7414           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7415                                 /*IsAssigmentOperator=*/isEqualOp);
7416         }
7417       }
7418     }
7419 
7420     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7421     for (BuiltinCandidateTypeSet::iterator
7422               Vec1 = CandidateTypes[0].vector_begin(),
7423            Vec1End = CandidateTypes[0].vector_end();
7424          Vec1 != Vec1End; ++Vec1) {
7425       for (BuiltinCandidateTypeSet::iterator
7426                 Vec2 = CandidateTypes[1].vector_begin(),
7427              Vec2End = CandidateTypes[1].vector_end();
7428            Vec2 != Vec2End; ++Vec2) {
7429         QualType ParamTypes[2];
7430         ParamTypes[1] = *Vec2;
7431         // Add this built-in operator as a candidate (VQ is empty).
7432         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7433         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7434                               /*IsAssigmentOperator=*/isEqualOp);
7435 
7436         // Add this built-in operator as a candidate (VQ is 'volatile').
7437         if (VisibleTypeConversionsQuals.hasVolatile()) {
7438           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7439           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7440           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7441                                 /*IsAssigmentOperator=*/isEqualOp);
7442         }
7443       }
7444     }
7445   }
7446 
7447   // C++ [over.built]p22:
7448   //
7449   //   For every triple (L, VQ, R), where L is an integral type, VQ
7450   //   is either volatile or empty, and R is a promoted integral
7451   //   type, there exist candidate operator functions of the form
7452   //
7453   //        VQ L&       operator%=(VQ L&, R);
7454   //        VQ L&       operator<<=(VQ L&, R);
7455   //        VQ L&       operator>>=(VQ L&, R);
7456   //        VQ L&       operator&=(VQ L&, R);
7457   //        VQ L&       operator^=(VQ L&, R);
7458   //        VQ L&       operator|=(VQ L&, R);
7459   void addAssignmentIntegralOverloads() {
7460     if (!HasArithmeticOrEnumeralCandidateType)
7461       return;
7462 
7463     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7464       for (unsigned Right = FirstPromotedIntegralType;
7465            Right < LastPromotedIntegralType; ++Right) {
7466         QualType ParamTypes[2];
7467         ParamTypes[1] = getArithmeticType(Right);
7468 
7469         // Add this built-in operator as a candidate (VQ is empty).
7470         ParamTypes[0] =
7471           S.Context.getLValueReferenceType(getArithmeticType(Left));
7472         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7473         if (VisibleTypeConversionsQuals.hasVolatile()) {
7474           // Add this built-in operator as a candidate (VQ is 'volatile').
7475           ParamTypes[0] = getArithmeticType(Left);
7476           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7477           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7478           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7479         }
7480       }
7481     }
7482   }
7483 
7484   // C++ [over.operator]p23:
7485   //
7486   //   There also exist candidate operator functions of the form
7487   //
7488   //        bool        operator!(bool);
7489   //        bool        operator&&(bool, bool);
7490   //        bool        operator||(bool, bool);
7491   void addExclaimOverload() {
7492     QualType ParamTy = S.Context.BoolTy;
7493     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7494                           /*IsAssignmentOperator=*/false,
7495                           /*NumContextualBoolArguments=*/1);
7496   }
7497   void addAmpAmpOrPipePipeOverload() {
7498     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7499     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7500                           /*IsAssignmentOperator=*/false,
7501                           /*NumContextualBoolArguments=*/2);
7502   }
7503 
7504   // C++ [over.built]p13:
7505   //
7506   //   For every cv-qualified or cv-unqualified object type T there
7507   //   exist candidate operator functions of the form
7508   //
7509   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7510   //        T&         operator[](T*, ptrdiff_t);
7511   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7512   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7513   //        T&         operator[](ptrdiff_t, T*);
7514   void addSubscriptOverloads() {
7515     for (BuiltinCandidateTypeSet::iterator
7516               Ptr = CandidateTypes[0].pointer_begin(),
7517            PtrEnd = CandidateTypes[0].pointer_end();
7518          Ptr != PtrEnd; ++Ptr) {
7519       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7520       QualType PointeeType = (*Ptr)->getPointeeType();
7521       if (!PointeeType->isObjectType())
7522         continue;
7523 
7524       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7525 
7526       // T& operator[](T*, ptrdiff_t)
7527       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7528     }
7529 
7530     for (BuiltinCandidateTypeSet::iterator
7531               Ptr = CandidateTypes[1].pointer_begin(),
7532            PtrEnd = CandidateTypes[1].pointer_end();
7533          Ptr != PtrEnd; ++Ptr) {
7534       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7535       QualType PointeeType = (*Ptr)->getPointeeType();
7536       if (!PointeeType->isObjectType())
7537         continue;
7538 
7539       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7540 
7541       // T& operator[](ptrdiff_t, T*)
7542       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7543     }
7544   }
7545 
7546   // C++ [over.built]p11:
7547   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7548   //    C1 is the same type as C2 or is a derived class of C2, T is an object
7549   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7550   //    there exist candidate operator functions of the form
7551   //
7552   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7553   //
7554   //    where CV12 is the union of CV1 and CV2.
7555   void addArrowStarOverloads() {
7556     for (BuiltinCandidateTypeSet::iterator
7557              Ptr = CandidateTypes[0].pointer_begin(),
7558            PtrEnd = CandidateTypes[0].pointer_end();
7559          Ptr != PtrEnd; ++Ptr) {
7560       QualType C1Ty = (*Ptr);
7561       QualType C1;
7562       QualifierCollector Q1;
7563       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7564       if (!isa<RecordType>(C1))
7565         continue;
7566       // heuristic to reduce number of builtin candidates in the set.
7567       // Add volatile/restrict version only if there are conversions to a
7568       // volatile/restrict type.
7569       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7570         continue;
7571       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7572         continue;
7573       for (BuiltinCandidateTypeSet::iterator
7574                 MemPtr = CandidateTypes[1].member_pointer_begin(),
7575              MemPtrEnd = CandidateTypes[1].member_pointer_end();
7576            MemPtr != MemPtrEnd; ++MemPtr) {
7577         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7578         QualType C2 = QualType(mptr->getClass(), 0);
7579         C2 = C2.getUnqualifiedType();
7580         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7581           break;
7582         QualType ParamTypes[2] = { *Ptr, *MemPtr };
7583         // build CV12 T&
7584         QualType T = mptr->getPointeeType();
7585         if (!VisibleTypeConversionsQuals.hasVolatile() &&
7586             T.isVolatileQualified())
7587           continue;
7588         if (!VisibleTypeConversionsQuals.hasRestrict() &&
7589             T.isRestrictQualified())
7590           continue;
7591         T = Q1.apply(S.Context, T);
7592         QualType ResultTy = S.Context.getLValueReferenceType(T);
7593         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7594       }
7595     }
7596   }
7597 
7598   // Note that we don't consider the first argument, since it has been
7599   // contextually converted to bool long ago. The candidates below are
7600   // therefore added as binary.
7601   //
7602   // C++ [over.built]p25:
7603   //   For every type T, where T is a pointer, pointer-to-member, or scoped
7604   //   enumeration type, there exist candidate operator functions of the form
7605   //
7606   //        T        operator?(bool, T, T);
7607   //
7608   void addConditionalOperatorOverloads() {
7609     /// Set of (canonical) types that we've already handled.
7610     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7611 
7612     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7613       for (BuiltinCandidateTypeSet::iterator
7614                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7615              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7616            Ptr != PtrEnd; ++Ptr) {
7617         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7618           continue;
7619 
7620         QualType ParamTypes[2] = { *Ptr, *Ptr };
7621         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
7622       }
7623 
7624       for (BuiltinCandidateTypeSet::iterator
7625                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7626              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7627            MemPtr != MemPtrEnd; ++MemPtr) {
7628         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7629           continue;
7630 
7631         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7632         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
7633       }
7634 
7635       if (S.getLangOpts().CPlusPlus11) {
7636         for (BuiltinCandidateTypeSet::iterator
7637                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7638                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7639              Enum != EnumEnd; ++Enum) {
7640           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7641             continue;
7642 
7643           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7644             continue;
7645 
7646           QualType ParamTypes[2] = { *Enum, *Enum };
7647           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
7648         }
7649       }
7650     }
7651   }
7652 };
7653 
7654 } // end anonymous namespace
7655 
7656 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
7657 /// operator overloads to the candidate set (C++ [over.built]), based
7658 /// on the operator @p Op and the arguments given. For example, if the
7659 /// operator is a binary '+', this routine might add "int
7660 /// operator+(int, int)" to cover integer addition.
7661 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7662                                         SourceLocation OpLoc,
7663                                         ArrayRef<Expr *> Args,
7664                                         OverloadCandidateSet &CandidateSet) {
7665   // Find all of the types that the arguments can convert to, but only
7666   // if the operator we're looking at has built-in operator candidates
7667   // that make use of these types. Also record whether we encounter non-record
7668   // candidate types or either arithmetic or enumeral candidate types.
7669   Qualifiers VisibleTypeConversionsQuals;
7670   VisibleTypeConversionsQuals.addConst();
7671   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7672     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7673 
7674   bool HasNonRecordCandidateType = false;
7675   bool HasArithmeticOrEnumeralCandidateType = false;
7676   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7677   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7678     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7679     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7680                                                  OpLoc,
7681                                                  true,
7682                                                  (Op == OO_Exclaim ||
7683                                                   Op == OO_AmpAmp ||
7684                                                   Op == OO_PipePipe),
7685                                                  VisibleTypeConversionsQuals);
7686     HasNonRecordCandidateType = HasNonRecordCandidateType ||
7687         CandidateTypes[ArgIdx].hasNonRecordTypes();
7688     HasArithmeticOrEnumeralCandidateType =
7689         HasArithmeticOrEnumeralCandidateType ||
7690         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7691   }
7692 
7693   // Exit early when no non-record types have been added to the candidate set
7694   // for any of the arguments to the operator.
7695   //
7696   // We can't exit early for !, ||, or &&, since there we have always have
7697   // 'bool' overloads.
7698   if (!HasNonRecordCandidateType &&
7699       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7700     return;
7701 
7702   // Setup an object to manage the common state for building overloads.
7703   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
7704                                            VisibleTypeConversionsQuals,
7705                                            HasArithmeticOrEnumeralCandidateType,
7706                                            CandidateTypes, CandidateSet);
7707 
7708   // Dispatch over the operation to add in only those overloads which apply.
7709   switch (Op) {
7710   case OO_None:
7711   case NUM_OVERLOADED_OPERATORS:
7712     llvm_unreachable("Expected an overloaded operator");
7713 
7714   case OO_New:
7715   case OO_Delete:
7716   case OO_Array_New:
7717   case OO_Array_Delete:
7718   case OO_Call:
7719     llvm_unreachable(
7720                     "Special operators don't use AddBuiltinOperatorCandidates");
7721 
7722   case OO_Comma:
7723   case OO_Arrow:
7724     // C++ [over.match.oper]p3:
7725     //   -- For the operator ',', the unary operator '&', or the
7726     //      operator '->', the built-in candidates set is empty.
7727     break;
7728 
7729   case OO_Plus: // '+' is either unary or binary
7730     if (Args.size() == 1)
7731       OpBuilder.addUnaryPlusPointerOverloads();
7732     // Fall through.
7733 
7734   case OO_Minus: // '-' is either unary or binary
7735     if (Args.size() == 1) {
7736       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7737     } else {
7738       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7739       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7740     }
7741     break;
7742 
7743   case OO_Star: // '*' is either unary or binary
7744     if (Args.size() == 1)
7745       OpBuilder.addUnaryStarPointerOverloads();
7746     else
7747       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7748     break;
7749 
7750   case OO_Slash:
7751     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7752     break;
7753 
7754   case OO_PlusPlus:
7755   case OO_MinusMinus:
7756     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7757     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7758     break;
7759 
7760   case OO_EqualEqual:
7761   case OO_ExclaimEqual:
7762     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7763     // Fall through.
7764 
7765   case OO_Less:
7766   case OO_Greater:
7767   case OO_LessEqual:
7768   case OO_GreaterEqual:
7769     OpBuilder.addRelationalPointerOrEnumeralOverloads();
7770     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7771     break;
7772 
7773   case OO_Percent:
7774   case OO_Caret:
7775   case OO_Pipe:
7776   case OO_LessLess:
7777   case OO_GreaterGreater:
7778     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7779     break;
7780 
7781   case OO_Amp: // '&' is either unary or binary
7782     if (Args.size() == 1)
7783       // C++ [over.match.oper]p3:
7784       //   -- For the operator ',', the unary operator '&', or the
7785       //      operator '->', the built-in candidates set is empty.
7786       break;
7787 
7788     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7789     break;
7790 
7791   case OO_Tilde:
7792     OpBuilder.addUnaryTildePromotedIntegralOverloads();
7793     break;
7794 
7795   case OO_Equal:
7796     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7797     // Fall through.
7798 
7799   case OO_PlusEqual:
7800   case OO_MinusEqual:
7801     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7802     // Fall through.
7803 
7804   case OO_StarEqual:
7805   case OO_SlashEqual:
7806     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7807     break;
7808 
7809   case OO_PercentEqual:
7810   case OO_LessLessEqual:
7811   case OO_GreaterGreaterEqual:
7812   case OO_AmpEqual:
7813   case OO_CaretEqual:
7814   case OO_PipeEqual:
7815     OpBuilder.addAssignmentIntegralOverloads();
7816     break;
7817 
7818   case OO_Exclaim:
7819     OpBuilder.addExclaimOverload();
7820     break;
7821 
7822   case OO_AmpAmp:
7823   case OO_PipePipe:
7824     OpBuilder.addAmpAmpOrPipePipeOverload();
7825     break;
7826 
7827   case OO_Subscript:
7828     OpBuilder.addSubscriptOverloads();
7829     break;
7830 
7831   case OO_ArrowStar:
7832     OpBuilder.addArrowStarOverloads();
7833     break;
7834 
7835   case OO_Conditional:
7836     OpBuilder.addConditionalOperatorOverloads();
7837     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7838     break;
7839   }
7840 }
7841 
7842 /// \brief Add function candidates found via argument-dependent lookup
7843 /// to the set of overloading candidates.
7844 ///
7845 /// This routine performs argument-dependent name lookup based on the
7846 /// given function name (which may also be an operator name) and adds
7847 /// all of the overload candidates found by ADL to the overload
7848 /// candidate set (C++ [basic.lookup.argdep]).
7849 void
7850 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7851                                            bool Operator, SourceLocation Loc,
7852                                            ArrayRef<Expr *> Args,
7853                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
7854                                            OverloadCandidateSet& CandidateSet,
7855                                            bool PartialOverloading) {
7856   ADLResult Fns;
7857 
7858   // FIXME: This approach for uniquing ADL results (and removing
7859   // redundant candidates from the set) relies on pointer-equality,
7860   // which means we need to key off the canonical decl.  However,
7861   // always going back to the canonical decl might not get us the
7862   // right set of default arguments.  What default arguments are
7863   // we supposed to consider on ADL candidates, anyway?
7864 
7865   // FIXME: Pass in the explicit template arguments?
7866   ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
7867 
7868   // Erase all of the candidates we already knew about.
7869   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7870                                    CandEnd = CandidateSet.end();
7871        Cand != CandEnd; ++Cand)
7872     if (Cand->Function) {
7873       Fns.erase(Cand->Function);
7874       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7875         Fns.erase(FunTmpl);
7876     }
7877 
7878   // For each of the ADL candidates we found, add it to the overload
7879   // set.
7880   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7881     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7882     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7883       if (ExplicitTemplateArgs)
7884         continue;
7885 
7886       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7887                            PartialOverloading);
7888     } else
7889       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7890                                    FoundDecl, ExplicitTemplateArgs,
7891                                    Args, CandidateSet);
7892   }
7893 }
7894 
7895 /// isBetterOverloadCandidate - Determines whether the first overload
7896 /// candidate is a better candidate than the second (C++ 13.3.3p1).
7897 bool
7898 isBetterOverloadCandidate(Sema &S,
7899                           const OverloadCandidate &Cand1,
7900                           const OverloadCandidate &Cand2,
7901                           SourceLocation Loc,
7902                           bool UserDefinedConversion) {
7903   // Define viable functions to be better candidates than non-viable
7904   // functions.
7905   if (!Cand2.Viable)
7906     return Cand1.Viable;
7907   else if (!Cand1.Viable)
7908     return false;
7909 
7910   // C++ [over.match.best]p1:
7911   //
7912   //   -- if F is a static member function, ICS1(F) is defined such
7913   //      that ICS1(F) is neither better nor worse than ICS1(G) for
7914   //      any function G, and, symmetrically, ICS1(G) is neither
7915   //      better nor worse than ICS1(F).
7916   unsigned StartArg = 0;
7917   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7918     StartArg = 1;
7919 
7920   // C++ [over.match.best]p1:
7921   //   A viable function F1 is defined to be a better function than another
7922   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7923   //   conversion sequence than ICSi(F2), and then...
7924   unsigned NumArgs = Cand1.NumConversions;
7925   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7926   bool HasBetterConversion = false;
7927   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7928     switch (CompareImplicitConversionSequences(S,
7929                                                Cand1.Conversions[ArgIdx],
7930                                                Cand2.Conversions[ArgIdx])) {
7931     case ImplicitConversionSequence::Better:
7932       // Cand1 has a better conversion sequence.
7933       HasBetterConversion = true;
7934       break;
7935 
7936     case ImplicitConversionSequence::Worse:
7937       // Cand1 can't be better than Cand2.
7938       return false;
7939 
7940     case ImplicitConversionSequence::Indistinguishable:
7941       // Do nothing.
7942       break;
7943     }
7944   }
7945 
7946   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7947   //       ICSj(F2), or, if not that,
7948   if (HasBetterConversion)
7949     return true;
7950 
7951   //     - F1 is a non-template function and F2 is a function template
7952   //       specialization, or, if not that,
7953   if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7954       Cand2.Function && Cand2.Function->getPrimaryTemplate())
7955     return true;
7956 
7957   //   -- F1 and F2 are function template specializations, and the function
7958   //      template for F1 is more specialized than the template for F2
7959   //      according to the partial ordering rules described in 14.5.5.2, or,
7960   //      if not that,
7961   if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7962       Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7963     if (FunctionTemplateDecl *BetterTemplate
7964           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7965                                          Cand2.Function->getPrimaryTemplate(),
7966                                          Loc,
7967                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7968                                                              : TPOC_Call,
7969                                          Cand1.ExplicitCallArguments))
7970       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7971   }
7972 
7973   //   -- the context is an initialization by user-defined conversion
7974   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7975   //      from the return type of F1 to the destination type (i.e.,
7976   //      the type of the entity being initialized) is a better
7977   //      conversion sequence than the standard conversion sequence
7978   //      from the return type of F2 to the destination type.
7979   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7980       isa<CXXConversionDecl>(Cand1.Function) &&
7981       isa<CXXConversionDecl>(Cand2.Function)) {
7982     // First check whether we prefer one of the conversion functions over the
7983     // other. This only distinguishes the results in non-standard, extension
7984     // cases such as the conversion from a lambda closure type to a function
7985     // pointer or block.
7986     ImplicitConversionSequence::CompareKind FuncResult
7987       = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7988     if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7989       return FuncResult;
7990 
7991     switch (CompareStandardConversionSequences(S,
7992                                                Cand1.FinalConversion,
7993                                                Cand2.FinalConversion)) {
7994     case ImplicitConversionSequence::Better:
7995       // Cand1 has a better conversion sequence.
7996       return true;
7997 
7998     case ImplicitConversionSequence::Worse:
7999       // Cand1 can't be better than Cand2.
8000       return false;
8001 
8002     case ImplicitConversionSequence::Indistinguishable:
8003       // Do nothing
8004       break;
8005     }
8006   }
8007 
8008   return false;
8009 }
8010 
8011 /// \brief Computes the best viable function (C++ 13.3.3)
8012 /// within an overload candidate set.
8013 ///
8014 /// \param Loc The location of the function name (or operator symbol) for
8015 /// which overload resolution occurs.
8016 ///
8017 /// \param Best If overload resolution was successful or found a deleted
8018 /// function, \p Best points to the candidate function found.
8019 ///
8020 /// \returns The result of overload resolution.
8021 OverloadingResult
8022 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8023                                          iterator &Best,
8024                                          bool UserDefinedConversion) {
8025   // Find the best viable function.
8026   Best = end();
8027   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8028     if (Cand->Viable)
8029       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8030                                                      UserDefinedConversion))
8031         Best = Cand;
8032   }
8033 
8034   // If we didn't find any viable functions, abort.
8035   if (Best == end())
8036     return OR_No_Viable_Function;
8037 
8038   // Make sure that this function is better than every other viable
8039   // function. If not, we have an ambiguity.
8040   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8041     if (Cand->Viable &&
8042         Cand != Best &&
8043         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8044                                    UserDefinedConversion)) {
8045       Best = end();
8046       return OR_Ambiguous;
8047     }
8048   }
8049 
8050   // Best is the best viable function.
8051   if (Best->Function &&
8052       (Best->Function->isDeleted() ||
8053        S.isFunctionConsideredUnavailable(Best->Function)))
8054     return OR_Deleted;
8055 
8056   return OR_Success;
8057 }
8058 
8059 namespace {
8060 
8061 enum OverloadCandidateKind {
8062   oc_function,
8063   oc_method,
8064   oc_constructor,
8065   oc_function_template,
8066   oc_method_template,
8067   oc_constructor_template,
8068   oc_implicit_default_constructor,
8069   oc_implicit_copy_constructor,
8070   oc_implicit_move_constructor,
8071   oc_implicit_copy_assignment,
8072   oc_implicit_move_assignment,
8073   oc_implicit_inherited_constructor
8074 };
8075 
8076 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8077                                                 FunctionDecl *Fn,
8078                                                 std::string &Description) {
8079   bool isTemplate = false;
8080 
8081   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8082     isTemplate = true;
8083     Description = S.getTemplateArgumentBindingsText(
8084       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8085   }
8086 
8087   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8088     if (!Ctor->isImplicit())
8089       return isTemplate ? oc_constructor_template : oc_constructor;
8090 
8091     if (Ctor->getInheritedConstructor())
8092       return oc_implicit_inherited_constructor;
8093 
8094     if (Ctor->isDefaultConstructor())
8095       return oc_implicit_default_constructor;
8096 
8097     if (Ctor->isMoveConstructor())
8098       return oc_implicit_move_constructor;
8099 
8100     assert(Ctor->isCopyConstructor() &&
8101            "unexpected sort of implicit constructor");
8102     return oc_implicit_copy_constructor;
8103   }
8104 
8105   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8106     // This actually gets spelled 'candidate function' for now, but
8107     // it doesn't hurt to split it out.
8108     if (!Meth->isImplicit())
8109       return isTemplate ? oc_method_template : oc_method;
8110 
8111     if (Meth->isMoveAssignmentOperator())
8112       return oc_implicit_move_assignment;
8113 
8114     if (Meth->isCopyAssignmentOperator())
8115       return oc_implicit_copy_assignment;
8116 
8117     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8118     return oc_method;
8119   }
8120 
8121   return isTemplate ? oc_function_template : oc_function;
8122 }
8123 
8124 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8125   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8126   if (!Ctor) return;
8127 
8128   Ctor = Ctor->getInheritedConstructor();
8129   if (!Ctor) return;
8130 
8131   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8132 }
8133 
8134 } // end anonymous namespace
8135 
8136 // Notes the location of an overload candidate.
8137 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8138   std::string FnDesc;
8139   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8140   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8141                              << (unsigned) K << FnDesc;
8142   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8143   Diag(Fn->getLocation(), PD);
8144   MaybeEmitInheritedConstructorNote(*this, Fn);
8145 }
8146 
8147 //Notes the location of all overload candidates designated through
8148 // OverloadedExpr
8149 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8150   assert(OverloadedExpr->getType() == Context.OverloadTy);
8151 
8152   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8153   OverloadExpr *OvlExpr = Ovl.Expression;
8154 
8155   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8156                             IEnd = OvlExpr->decls_end();
8157        I != IEnd; ++I) {
8158     if (FunctionTemplateDecl *FunTmpl =
8159                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8160       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8161     } else if (FunctionDecl *Fun
8162                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8163       NoteOverloadCandidate(Fun, DestType);
8164     }
8165   }
8166 }
8167 
8168 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8169 /// "lead" diagnostic; it will be given two arguments, the source and
8170 /// target types of the conversion.
8171 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8172                                  Sema &S,
8173                                  SourceLocation CaretLoc,
8174                                  const PartialDiagnostic &PDiag) const {
8175   S.Diag(CaretLoc, PDiag)
8176     << Ambiguous.getFromType() << Ambiguous.getToType();
8177   // FIXME: The note limiting machinery is borrowed from
8178   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8179   // refactoring here.
8180   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8181   unsigned CandsShown = 0;
8182   AmbiguousConversionSequence::const_iterator I, E;
8183   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8184     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8185       break;
8186     ++CandsShown;
8187     S.NoteOverloadCandidate(*I);
8188   }
8189   if (I != E)
8190     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8191 }
8192 
8193 namespace {
8194 
8195 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8196   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8197   assert(Conv.isBad());
8198   assert(Cand->Function && "for now, candidate must be a function");
8199   FunctionDecl *Fn = Cand->Function;
8200 
8201   // There's a conversion slot for the object argument if this is a
8202   // non-constructor method.  Note that 'I' corresponds the
8203   // conversion-slot index.
8204   bool isObjectArgument = false;
8205   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8206     if (I == 0)
8207       isObjectArgument = true;
8208     else
8209       I--;
8210   }
8211 
8212   std::string FnDesc;
8213   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8214 
8215   Expr *FromExpr = Conv.Bad.FromExpr;
8216   QualType FromTy = Conv.Bad.getFromType();
8217   QualType ToTy = Conv.Bad.getToType();
8218 
8219   if (FromTy == S.Context.OverloadTy) {
8220     assert(FromExpr && "overload set argument came from implicit argument?");
8221     Expr *E = FromExpr->IgnoreParens();
8222     if (isa<UnaryOperator>(E))
8223       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8224     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8225 
8226     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8227       << (unsigned) FnKind << FnDesc
8228       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8229       << ToTy << Name << I+1;
8230     MaybeEmitInheritedConstructorNote(S, Fn);
8231     return;
8232   }
8233 
8234   // Do some hand-waving analysis to see if the non-viability is due
8235   // to a qualifier mismatch.
8236   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8237   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8238   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8239     CToTy = RT->getPointeeType();
8240   else {
8241     // TODO: detect and diagnose the full richness of const mismatches.
8242     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8243       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8244         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8245   }
8246 
8247   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8248       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8249     Qualifiers FromQs = CFromTy.getQualifiers();
8250     Qualifiers ToQs = CToTy.getQualifiers();
8251 
8252     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8253       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8254         << (unsigned) FnKind << FnDesc
8255         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8256         << FromTy
8257         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8258         << (unsigned) isObjectArgument << I+1;
8259       MaybeEmitInheritedConstructorNote(S, Fn);
8260       return;
8261     }
8262 
8263     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8264       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8265         << (unsigned) FnKind << FnDesc
8266         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8267         << FromTy
8268         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8269         << (unsigned) isObjectArgument << I+1;
8270       MaybeEmitInheritedConstructorNote(S, Fn);
8271       return;
8272     }
8273 
8274     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8275       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8276       << (unsigned) FnKind << FnDesc
8277       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8278       << FromTy
8279       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8280       << (unsigned) isObjectArgument << I+1;
8281       MaybeEmitInheritedConstructorNote(S, Fn);
8282       return;
8283     }
8284 
8285     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8286     assert(CVR && "unexpected qualifiers mismatch");
8287 
8288     if (isObjectArgument) {
8289       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8290         << (unsigned) FnKind << FnDesc
8291         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8292         << FromTy << (CVR - 1);
8293     } else {
8294       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8295         << (unsigned) FnKind << FnDesc
8296         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8297         << FromTy << (CVR - 1) << I+1;
8298     }
8299     MaybeEmitInheritedConstructorNote(S, Fn);
8300     return;
8301   }
8302 
8303   // Special diagnostic for failure to convert an initializer list, since
8304   // telling the user that it has type void is not useful.
8305   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8306     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8307       << (unsigned) FnKind << FnDesc
8308       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8309       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8310     MaybeEmitInheritedConstructorNote(S, Fn);
8311     return;
8312   }
8313 
8314   // Diagnose references or pointers to incomplete types differently,
8315   // since it's far from impossible that the incompleteness triggered
8316   // the failure.
8317   QualType TempFromTy = FromTy.getNonReferenceType();
8318   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8319     TempFromTy = PTy->getPointeeType();
8320   if (TempFromTy->isIncompleteType()) {
8321     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8322       << (unsigned) FnKind << FnDesc
8323       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8324       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8325     MaybeEmitInheritedConstructorNote(S, Fn);
8326     return;
8327   }
8328 
8329   // Diagnose base -> derived pointer conversions.
8330   unsigned BaseToDerivedConversion = 0;
8331   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8332     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8333       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8334                                                FromPtrTy->getPointeeType()) &&
8335           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8336           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8337           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8338                           FromPtrTy->getPointeeType()))
8339         BaseToDerivedConversion = 1;
8340     }
8341   } else if (const ObjCObjectPointerType *FromPtrTy
8342                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8343     if (const ObjCObjectPointerType *ToPtrTy
8344                                         = ToTy->getAs<ObjCObjectPointerType>())
8345       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8346         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8347           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8348                                                 FromPtrTy->getPointeeType()) &&
8349               FromIface->isSuperClassOf(ToIface))
8350             BaseToDerivedConversion = 2;
8351   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8352     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8353         !FromTy->isIncompleteType() &&
8354         !ToRefTy->getPointeeType()->isIncompleteType() &&
8355         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8356       BaseToDerivedConversion = 3;
8357     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8358                ToTy.getNonReferenceType().getCanonicalType() ==
8359                FromTy.getNonReferenceType().getCanonicalType()) {
8360       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8361         << (unsigned) FnKind << FnDesc
8362         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8363         << (unsigned) isObjectArgument << I + 1;
8364       MaybeEmitInheritedConstructorNote(S, Fn);
8365       return;
8366     }
8367   }
8368 
8369   if (BaseToDerivedConversion) {
8370     S.Diag(Fn->getLocation(),
8371            diag::note_ovl_candidate_bad_base_to_derived_conv)
8372       << (unsigned) FnKind << FnDesc
8373       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8374       << (BaseToDerivedConversion - 1)
8375       << FromTy << ToTy << I+1;
8376     MaybeEmitInheritedConstructorNote(S, Fn);
8377     return;
8378   }
8379 
8380   if (isa<ObjCObjectPointerType>(CFromTy) &&
8381       isa<PointerType>(CToTy)) {
8382       Qualifiers FromQs = CFromTy.getQualifiers();
8383       Qualifiers ToQs = CToTy.getQualifiers();
8384       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8385         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8386         << (unsigned) FnKind << FnDesc
8387         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8388         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8389         MaybeEmitInheritedConstructorNote(S, Fn);
8390         return;
8391       }
8392   }
8393 
8394   // Emit the generic diagnostic and, optionally, add the hints to it.
8395   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8396   FDiag << (unsigned) FnKind << FnDesc
8397     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8398     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8399     << (unsigned) (Cand->Fix.Kind);
8400 
8401   // If we can fix the conversion, suggest the FixIts.
8402   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8403        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8404     FDiag << *HI;
8405   S.Diag(Fn->getLocation(), FDiag);
8406 
8407   MaybeEmitInheritedConstructorNote(S, Fn);
8408 }
8409 
8410 /// Additional arity mismatch diagnosis specific to a function overload
8411 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8412 /// over a candidate in any candidate set.
8413 bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8414                         unsigned NumArgs) {
8415   FunctionDecl *Fn = Cand->Function;
8416   unsigned MinParams = Fn->getMinRequiredArguments();
8417 
8418   // With invalid overloaded operators, it's possible that we think we
8419   // have an arity mismatch when in fact it looks like we have the
8420   // right number of arguments, because only overloaded operators have
8421   // the weird behavior of overloading member and non-member functions.
8422   // Just don't report anything.
8423   if (Fn->isInvalidDecl() &&
8424       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8425     return true;
8426 
8427   if (NumArgs < MinParams) {
8428     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8429            (Cand->FailureKind == ovl_fail_bad_deduction &&
8430             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8431   } else {
8432     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8433            (Cand->FailureKind == ovl_fail_bad_deduction &&
8434             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8435   }
8436 
8437   return false;
8438 }
8439 
8440 /// General arity mismatch diagnosis over a candidate in a candidate set.
8441 void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8442   assert(isa<FunctionDecl>(D) &&
8443       "The templated declaration should at least be a function"
8444       " when diagnosing bad template argument deduction due to too many"
8445       " or too few arguments");
8446 
8447   FunctionDecl *Fn = cast<FunctionDecl>(D);
8448 
8449   // TODO: treat calls to a missing default constructor as a special case
8450   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8451   unsigned MinParams = Fn->getMinRequiredArguments();
8452 
8453   // at least / at most / exactly
8454   unsigned mode, modeCount;
8455   if (NumFormalArgs < MinParams) {
8456     if (MinParams != FnTy->getNumArgs() ||
8457         FnTy->isVariadic() || FnTy->isTemplateVariadic())
8458       mode = 0; // "at least"
8459     else
8460       mode = 2; // "exactly"
8461     modeCount = MinParams;
8462   } else {
8463     if (MinParams != FnTy->getNumArgs())
8464       mode = 1; // "at most"
8465     else
8466       mode = 2; // "exactly"
8467     modeCount = FnTy->getNumArgs();
8468   }
8469 
8470   std::string Description;
8471   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8472 
8473   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8474     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8475       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8476       << Fn->getParamDecl(0) << NumFormalArgs;
8477   else
8478     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8479       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8480       << modeCount << NumFormalArgs;
8481   MaybeEmitInheritedConstructorNote(S, Fn);
8482 }
8483 
8484 /// Arity mismatch diagnosis specific to a function overload candidate.
8485 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8486                            unsigned NumFormalArgs) {
8487   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8488     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8489 }
8490 
8491 TemplateDecl *getDescribedTemplate(Decl *Templated) {
8492   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8493     return FD->getDescribedFunctionTemplate();
8494   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8495     return RD->getDescribedClassTemplate();
8496 
8497   llvm_unreachable("Unsupported: Getting the described template declaration"
8498                    " for bad deduction diagnosis");
8499 }
8500 
8501 /// Diagnose a failed template-argument deduction.
8502 void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8503                           DeductionFailureInfo &DeductionFailure,
8504                           unsigned NumArgs) {
8505   TemplateParameter Param = DeductionFailure.getTemplateParameter();
8506   NamedDecl *ParamD;
8507   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8508   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8509   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8510   switch (DeductionFailure.Result) {
8511   case Sema::TDK_Success:
8512     llvm_unreachable("TDK_success while diagnosing bad deduction");
8513 
8514   case Sema::TDK_Incomplete: {
8515     assert(ParamD && "no parameter found for incomplete deduction result");
8516     S.Diag(Templated->getLocation(),
8517            diag::note_ovl_candidate_incomplete_deduction)
8518         << ParamD->getDeclName();
8519     MaybeEmitInheritedConstructorNote(S, Templated);
8520     return;
8521   }
8522 
8523   case Sema::TDK_Underqualified: {
8524     assert(ParamD && "no parameter found for bad qualifiers deduction result");
8525     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8526 
8527     QualType Param = DeductionFailure.getFirstArg()->getAsType();
8528 
8529     // Param will have been canonicalized, but it should just be a
8530     // qualified version of ParamD, so move the qualifiers to that.
8531     QualifierCollector Qs;
8532     Qs.strip(Param);
8533     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8534     assert(S.Context.hasSameType(Param, NonCanonParam));
8535 
8536     // Arg has also been canonicalized, but there's nothing we can do
8537     // about that.  It also doesn't matter as much, because it won't
8538     // have any template parameters in it (because deduction isn't
8539     // done on dependent types).
8540     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
8541 
8542     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8543         << ParamD->getDeclName() << Arg << NonCanonParam;
8544     MaybeEmitInheritedConstructorNote(S, Templated);
8545     return;
8546   }
8547 
8548   case Sema::TDK_Inconsistent: {
8549     assert(ParamD && "no parameter found for inconsistent deduction result");
8550     int which = 0;
8551     if (isa<TemplateTypeParmDecl>(ParamD))
8552       which = 0;
8553     else if (isa<NonTypeTemplateParmDecl>(ParamD))
8554       which = 1;
8555     else {
8556       which = 2;
8557     }
8558 
8559     S.Diag(Templated->getLocation(),
8560            diag::note_ovl_candidate_inconsistent_deduction)
8561         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8562         << *DeductionFailure.getSecondArg();
8563     MaybeEmitInheritedConstructorNote(S, Templated);
8564     return;
8565   }
8566 
8567   case Sema::TDK_InvalidExplicitArguments:
8568     assert(ParamD && "no parameter found for invalid explicit arguments");
8569     if (ParamD->getDeclName())
8570       S.Diag(Templated->getLocation(),
8571              diag::note_ovl_candidate_explicit_arg_mismatch_named)
8572           << ParamD->getDeclName();
8573     else {
8574       int index = 0;
8575       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8576         index = TTP->getIndex();
8577       else if (NonTypeTemplateParmDecl *NTTP
8578                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8579         index = NTTP->getIndex();
8580       else
8581         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8582       S.Diag(Templated->getLocation(),
8583              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8584           << (index + 1);
8585     }
8586     MaybeEmitInheritedConstructorNote(S, Templated);
8587     return;
8588 
8589   case Sema::TDK_TooManyArguments:
8590   case Sema::TDK_TooFewArguments:
8591     DiagnoseArityMismatch(S, Templated, NumArgs);
8592     return;
8593 
8594   case Sema::TDK_InstantiationDepth:
8595     S.Diag(Templated->getLocation(),
8596            diag::note_ovl_candidate_instantiation_depth);
8597     MaybeEmitInheritedConstructorNote(S, Templated);
8598     return;
8599 
8600   case Sema::TDK_SubstitutionFailure: {
8601     // Format the template argument list into the argument string.
8602     SmallString<128> TemplateArgString;
8603     if (TemplateArgumentList *Args =
8604             DeductionFailure.getTemplateArgumentList()) {
8605       TemplateArgString = " ";
8606       TemplateArgString += S.getTemplateArgumentBindingsText(
8607           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
8608     }
8609 
8610     // If this candidate was disabled by enable_if, say so.
8611     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
8612     if (PDiag && PDiag->second.getDiagID() ==
8613           diag::err_typename_nested_not_found_enable_if) {
8614       // FIXME: Use the source range of the condition, and the fully-qualified
8615       //        name of the enable_if template. These are both present in PDiag.
8616       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8617         << "'enable_if'" << TemplateArgString;
8618       return;
8619     }
8620 
8621     // Format the SFINAE diagnostic into the argument string.
8622     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8623     //        formatted message in another diagnostic.
8624     SmallString<128> SFINAEArgString;
8625     SourceRange R;
8626     if (PDiag) {
8627       SFINAEArgString = ": ";
8628       R = SourceRange(PDiag->first, PDiag->first);
8629       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8630     }
8631 
8632     S.Diag(Templated->getLocation(),
8633            diag::note_ovl_candidate_substitution_failure)
8634         << TemplateArgString << SFINAEArgString << R;
8635     MaybeEmitInheritedConstructorNote(S, Templated);
8636     return;
8637   }
8638 
8639   case Sema::TDK_FailedOverloadResolution: {
8640     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8641     S.Diag(Templated->getLocation(),
8642            diag::note_ovl_candidate_failed_overload_resolution)
8643         << R.Expression->getName();
8644     return;
8645   }
8646 
8647   case Sema::TDK_NonDeducedMismatch: {
8648     // FIXME: Provide a source location to indicate what we couldn't match.
8649     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8650     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
8651     if (FirstTA.getKind() == TemplateArgument::Template &&
8652         SecondTA.getKind() == TemplateArgument::Template) {
8653       TemplateName FirstTN = FirstTA.getAsTemplate();
8654       TemplateName SecondTN = SecondTA.getAsTemplate();
8655       if (FirstTN.getKind() == TemplateName::Template &&
8656           SecondTN.getKind() == TemplateName::Template) {
8657         if (FirstTN.getAsTemplateDecl()->getName() ==
8658             SecondTN.getAsTemplateDecl()->getName()) {
8659           // FIXME: This fixes a bad diagnostic where both templates are named
8660           // the same.  This particular case is a bit difficult since:
8661           // 1) It is passed as a string to the diagnostic printer.
8662           // 2) The diagnostic printer only attempts to find a better
8663           //    name for types, not decls.
8664           // Ideally, this should folded into the diagnostic printer.
8665           S.Diag(Templated->getLocation(),
8666                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8667               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8668           return;
8669         }
8670       }
8671     }
8672     S.Diag(Templated->getLocation(),
8673            diag::note_ovl_candidate_non_deduced_mismatch)
8674         << FirstTA << SecondTA;
8675     return;
8676   }
8677   // TODO: diagnose these individually, then kill off
8678   // note_ovl_candidate_bad_deduction, which is uselessly vague.
8679   case Sema::TDK_MiscellaneousDeductionFailure:
8680     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8681     MaybeEmitInheritedConstructorNote(S, Templated);
8682     return;
8683   }
8684 }
8685 
8686 /// Diagnose a failed template-argument deduction, for function calls.
8687 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8688   unsigned TDK = Cand->DeductionFailure.Result;
8689   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8690     if (CheckArityMismatch(S, Cand, NumArgs))
8691       return;
8692   }
8693   DiagnoseBadDeduction(S, Cand->Function, // pattern
8694                        Cand->DeductionFailure, NumArgs);
8695 }
8696 
8697 /// CUDA: diagnose an invalid call across targets.
8698 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8699   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8700   FunctionDecl *Callee = Cand->Function;
8701 
8702   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8703                            CalleeTarget = S.IdentifyCUDATarget(Callee);
8704 
8705   std::string FnDesc;
8706   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8707 
8708   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8709       << (unsigned) FnKind << CalleeTarget << CallerTarget;
8710 }
8711 
8712 /// Generates a 'note' diagnostic for an overload candidate.  We've
8713 /// already generated a primary error at the call site.
8714 ///
8715 /// It really does need to be a single diagnostic with its caret
8716 /// pointed at the candidate declaration.  Yes, this creates some
8717 /// major challenges of technical writing.  Yes, this makes pointing
8718 /// out problems with specific arguments quite awkward.  It's still
8719 /// better than generating twenty screens of text for every failed
8720 /// overload.
8721 ///
8722 /// It would be great to be able to express per-candidate problems
8723 /// more richly for those diagnostic clients that cared, but we'd
8724 /// still have to be just as careful with the default diagnostics.
8725 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8726                            unsigned NumArgs) {
8727   FunctionDecl *Fn = Cand->Function;
8728 
8729   // Note deleted candidates, but only if they're viable.
8730   if (Cand->Viable && (Fn->isDeleted() ||
8731       S.isFunctionConsideredUnavailable(Fn))) {
8732     std::string FnDesc;
8733     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8734 
8735     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8736       << FnKind << FnDesc
8737       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8738     MaybeEmitInheritedConstructorNote(S, Fn);
8739     return;
8740   }
8741 
8742   // We don't really have anything else to say about viable candidates.
8743   if (Cand->Viable) {
8744     S.NoteOverloadCandidate(Fn);
8745     return;
8746   }
8747 
8748   switch (Cand->FailureKind) {
8749   case ovl_fail_too_many_arguments:
8750   case ovl_fail_too_few_arguments:
8751     return DiagnoseArityMismatch(S, Cand, NumArgs);
8752 
8753   case ovl_fail_bad_deduction:
8754     return DiagnoseBadDeduction(S, Cand, NumArgs);
8755 
8756   case ovl_fail_trivial_conversion:
8757   case ovl_fail_bad_final_conversion:
8758   case ovl_fail_final_conversion_not_exact:
8759     return S.NoteOverloadCandidate(Fn);
8760 
8761   case ovl_fail_bad_conversion: {
8762     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8763     for (unsigned N = Cand->NumConversions; I != N; ++I)
8764       if (Cand->Conversions[I].isBad())
8765         return DiagnoseBadConversion(S, Cand, I);
8766 
8767     // FIXME: this currently happens when we're called from SemaInit
8768     // when user-conversion overload fails.  Figure out how to handle
8769     // those conditions and diagnose them well.
8770     return S.NoteOverloadCandidate(Fn);
8771   }
8772 
8773   case ovl_fail_bad_target:
8774     return DiagnoseBadTarget(S, Cand);
8775   }
8776 }
8777 
8778 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8779   // Desugar the type of the surrogate down to a function type,
8780   // retaining as many typedefs as possible while still showing
8781   // the function type (and, therefore, its parameter types).
8782   QualType FnType = Cand->Surrogate->getConversionType();
8783   bool isLValueReference = false;
8784   bool isRValueReference = false;
8785   bool isPointer = false;
8786   if (const LValueReferenceType *FnTypeRef =
8787         FnType->getAs<LValueReferenceType>()) {
8788     FnType = FnTypeRef->getPointeeType();
8789     isLValueReference = true;
8790   } else if (const RValueReferenceType *FnTypeRef =
8791                FnType->getAs<RValueReferenceType>()) {
8792     FnType = FnTypeRef->getPointeeType();
8793     isRValueReference = true;
8794   }
8795   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8796     FnType = FnTypePtr->getPointeeType();
8797     isPointer = true;
8798   }
8799   // Desugar down to a function type.
8800   FnType = QualType(FnType->getAs<FunctionType>(), 0);
8801   // Reconstruct the pointer/reference as appropriate.
8802   if (isPointer) FnType = S.Context.getPointerType(FnType);
8803   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8804   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8805 
8806   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8807     << FnType;
8808   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8809 }
8810 
8811 void NoteBuiltinOperatorCandidate(Sema &S,
8812                                   StringRef Opc,
8813                                   SourceLocation OpLoc,
8814                                   OverloadCandidate *Cand) {
8815   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8816   std::string TypeStr("operator");
8817   TypeStr += Opc;
8818   TypeStr += "(";
8819   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8820   if (Cand->NumConversions == 1) {
8821     TypeStr += ")";
8822     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8823   } else {
8824     TypeStr += ", ";
8825     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8826     TypeStr += ")";
8827     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8828   }
8829 }
8830 
8831 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8832                                   OverloadCandidate *Cand) {
8833   unsigned NoOperands = Cand->NumConversions;
8834   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8835     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8836     if (ICS.isBad()) break; // all meaningless after first invalid
8837     if (!ICS.isAmbiguous()) continue;
8838 
8839     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8840                               S.PDiag(diag::note_ambiguous_type_conversion));
8841   }
8842 }
8843 
8844 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8845   if (Cand->Function)
8846     return Cand->Function->getLocation();
8847   if (Cand->IsSurrogate)
8848     return Cand->Surrogate->getLocation();
8849   return SourceLocation();
8850 }
8851 
8852 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
8853   switch ((Sema::TemplateDeductionResult)DFI.Result) {
8854   case Sema::TDK_Success:
8855     llvm_unreachable("TDK_success while diagnosing bad deduction");
8856 
8857   case Sema::TDK_Invalid:
8858   case Sema::TDK_Incomplete:
8859     return 1;
8860 
8861   case Sema::TDK_Underqualified:
8862   case Sema::TDK_Inconsistent:
8863     return 2;
8864 
8865   case Sema::TDK_SubstitutionFailure:
8866   case Sema::TDK_NonDeducedMismatch:
8867   case Sema::TDK_MiscellaneousDeductionFailure:
8868     return 3;
8869 
8870   case Sema::TDK_InstantiationDepth:
8871   case Sema::TDK_FailedOverloadResolution:
8872     return 4;
8873 
8874   case Sema::TDK_InvalidExplicitArguments:
8875     return 5;
8876 
8877   case Sema::TDK_TooManyArguments:
8878   case Sema::TDK_TooFewArguments:
8879     return 6;
8880   }
8881   llvm_unreachable("Unhandled deduction result");
8882 }
8883 
8884 struct CompareOverloadCandidatesForDisplay {
8885   Sema &S;
8886   CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8887 
8888   bool operator()(const OverloadCandidate *L,
8889                   const OverloadCandidate *R) {
8890     // Fast-path this check.
8891     if (L == R) return false;
8892 
8893     // Order first by viability.
8894     if (L->Viable) {
8895       if (!R->Viable) return true;
8896 
8897       // TODO: introduce a tri-valued comparison for overload
8898       // candidates.  Would be more worthwhile if we had a sort
8899       // that could exploit it.
8900       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8901       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8902     } else if (R->Viable)
8903       return false;
8904 
8905     assert(L->Viable == R->Viable);
8906 
8907     // Criteria by which we can sort non-viable candidates:
8908     if (!L->Viable) {
8909       // 1. Arity mismatches come after other candidates.
8910       if (L->FailureKind == ovl_fail_too_many_arguments ||
8911           L->FailureKind == ovl_fail_too_few_arguments)
8912         return false;
8913       if (R->FailureKind == ovl_fail_too_many_arguments ||
8914           R->FailureKind == ovl_fail_too_few_arguments)
8915         return true;
8916 
8917       // 2. Bad conversions come first and are ordered by the number
8918       // of bad conversions and quality of good conversions.
8919       if (L->FailureKind == ovl_fail_bad_conversion) {
8920         if (R->FailureKind != ovl_fail_bad_conversion)
8921           return true;
8922 
8923         // The conversion that can be fixed with a smaller number of changes,
8924         // comes first.
8925         unsigned numLFixes = L->Fix.NumConversionsFixed;
8926         unsigned numRFixes = R->Fix.NumConversionsFixed;
8927         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8928         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8929         if (numLFixes != numRFixes) {
8930           if (numLFixes < numRFixes)
8931             return true;
8932           else
8933             return false;
8934         }
8935 
8936         // If there's any ordering between the defined conversions...
8937         // FIXME: this might not be transitive.
8938         assert(L->NumConversions == R->NumConversions);
8939 
8940         int leftBetter = 0;
8941         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8942         for (unsigned E = L->NumConversions; I != E; ++I) {
8943           switch (CompareImplicitConversionSequences(S,
8944                                                      L->Conversions[I],
8945                                                      R->Conversions[I])) {
8946           case ImplicitConversionSequence::Better:
8947             leftBetter++;
8948             break;
8949 
8950           case ImplicitConversionSequence::Worse:
8951             leftBetter--;
8952             break;
8953 
8954           case ImplicitConversionSequence::Indistinguishable:
8955             break;
8956           }
8957         }
8958         if (leftBetter > 0) return true;
8959         if (leftBetter < 0) return false;
8960 
8961       } else if (R->FailureKind == ovl_fail_bad_conversion)
8962         return false;
8963 
8964       if (L->FailureKind == ovl_fail_bad_deduction) {
8965         if (R->FailureKind != ovl_fail_bad_deduction)
8966           return true;
8967 
8968         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8969           return RankDeductionFailure(L->DeductionFailure)
8970                < RankDeductionFailure(R->DeductionFailure);
8971       } else if (R->FailureKind == ovl_fail_bad_deduction)
8972         return false;
8973 
8974       // TODO: others?
8975     }
8976 
8977     // Sort everything else by location.
8978     SourceLocation LLoc = GetLocationForCandidate(L);
8979     SourceLocation RLoc = GetLocationForCandidate(R);
8980 
8981     // Put candidates without locations (e.g. builtins) at the end.
8982     if (LLoc.isInvalid()) return false;
8983     if (RLoc.isInvalid()) return true;
8984 
8985     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8986   }
8987 };
8988 
8989 /// CompleteNonViableCandidate - Normally, overload resolution only
8990 /// computes up to the first. Produces the FixIt set if possible.
8991 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8992                                 ArrayRef<Expr *> Args) {
8993   assert(!Cand->Viable);
8994 
8995   // Don't do anything on failures other than bad conversion.
8996   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8997 
8998   // We only want the FixIts if all the arguments can be corrected.
8999   bool Unfixable = false;
9000   // Use a implicit copy initialization to check conversion fixes.
9001   Cand->Fix.setConversionChecker(TryCopyInitialization);
9002 
9003   // Skip forward to the first bad conversion.
9004   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9005   unsigned ConvCount = Cand->NumConversions;
9006   while (true) {
9007     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9008     ConvIdx++;
9009     if (Cand->Conversions[ConvIdx - 1].isBad()) {
9010       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9011       break;
9012     }
9013   }
9014 
9015   if (ConvIdx == ConvCount)
9016     return;
9017 
9018   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9019          "remaining conversion is initialized?");
9020 
9021   // FIXME: this should probably be preserved from the overload
9022   // operation somehow.
9023   bool SuppressUserConversions = false;
9024 
9025   const FunctionProtoType* Proto;
9026   unsigned ArgIdx = ConvIdx;
9027 
9028   if (Cand->IsSurrogate) {
9029     QualType ConvType
9030       = Cand->Surrogate->getConversionType().getNonReferenceType();
9031     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9032       ConvType = ConvPtrType->getPointeeType();
9033     Proto = ConvType->getAs<FunctionProtoType>();
9034     ArgIdx--;
9035   } else if (Cand->Function) {
9036     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9037     if (isa<CXXMethodDecl>(Cand->Function) &&
9038         !isa<CXXConstructorDecl>(Cand->Function))
9039       ArgIdx--;
9040   } else {
9041     // Builtin binary operator with a bad first conversion.
9042     assert(ConvCount <= 3);
9043     for (; ConvIdx != ConvCount; ++ConvIdx)
9044       Cand->Conversions[ConvIdx]
9045         = TryCopyInitialization(S, Args[ConvIdx],
9046                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9047                                 SuppressUserConversions,
9048                                 /*InOverloadResolution*/ true,
9049                                 /*AllowObjCWritebackConversion=*/
9050                                   S.getLangOpts().ObjCAutoRefCount);
9051     return;
9052   }
9053 
9054   // Fill in the rest of the conversions.
9055   unsigned NumArgsInProto = Proto->getNumArgs();
9056   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9057     if (ArgIdx < NumArgsInProto) {
9058       Cand->Conversions[ConvIdx]
9059         = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
9060                                 SuppressUserConversions,
9061                                 /*InOverloadResolution=*/true,
9062                                 /*AllowObjCWritebackConversion=*/
9063                                   S.getLangOpts().ObjCAutoRefCount);
9064       // Store the FixIt in the candidate if it exists.
9065       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9066         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9067     }
9068     else
9069       Cand->Conversions[ConvIdx].setEllipsis();
9070   }
9071 }
9072 
9073 } // end anonymous namespace
9074 
9075 /// PrintOverloadCandidates - When overload resolution fails, prints
9076 /// diagnostic messages containing the candidates in the candidate
9077 /// set.
9078 void OverloadCandidateSet::NoteCandidates(Sema &S,
9079                                           OverloadCandidateDisplayKind OCD,
9080                                           ArrayRef<Expr *> Args,
9081                                           StringRef Opc,
9082                                           SourceLocation OpLoc) {
9083   // Sort the candidates by viability and position.  Sorting directly would
9084   // be prohibitive, so we make a set of pointers and sort those.
9085   SmallVector<OverloadCandidate*, 32> Cands;
9086   if (OCD == OCD_AllCandidates) Cands.reserve(size());
9087   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9088     if (Cand->Viable)
9089       Cands.push_back(Cand);
9090     else if (OCD == OCD_AllCandidates) {
9091       CompleteNonViableCandidate(S, Cand, Args);
9092       if (Cand->Function || Cand->IsSurrogate)
9093         Cands.push_back(Cand);
9094       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9095       // want to list every possible builtin candidate.
9096     }
9097   }
9098 
9099   std::sort(Cands.begin(), Cands.end(),
9100             CompareOverloadCandidatesForDisplay(S));
9101 
9102   bool ReportedAmbiguousConversions = false;
9103 
9104   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9105   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9106   unsigned CandsShown = 0;
9107   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9108     OverloadCandidate *Cand = *I;
9109 
9110     // Set an arbitrary limit on the number of candidate functions we'll spam
9111     // the user with.  FIXME: This limit should depend on details of the
9112     // candidate list.
9113     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9114       break;
9115     }
9116     ++CandsShown;
9117 
9118     if (Cand->Function)
9119       NoteFunctionCandidate(S, Cand, Args.size());
9120     else if (Cand->IsSurrogate)
9121       NoteSurrogateCandidate(S, Cand);
9122     else {
9123       assert(Cand->Viable &&
9124              "Non-viable built-in candidates are not added to Cands.");
9125       // Generally we only see ambiguities including viable builtin
9126       // operators if overload resolution got screwed up by an
9127       // ambiguous user-defined conversion.
9128       //
9129       // FIXME: It's quite possible for different conversions to see
9130       // different ambiguities, though.
9131       if (!ReportedAmbiguousConversions) {
9132         NoteAmbiguousUserConversions(S, OpLoc, Cand);
9133         ReportedAmbiguousConversions = true;
9134       }
9135 
9136       // If this is a viable builtin, print it.
9137       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9138     }
9139   }
9140 
9141   if (I != E)
9142     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9143 }
9144 
9145 static SourceLocation
9146 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9147   return Cand->Specialization ? Cand->Specialization->getLocation()
9148                               : SourceLocation();
9149 }
9150 
9151 struct CompareTemplateSpecCandidatesForDisplay {
9152   Sema &S;
9153   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9154 
9155   bool operator()(const TemplateSpecCandidate *L,
9156                   const TemplateSpecCandidate *R) {
9157     // Fast-path this check.
9158     if (L == R)
9159       return false;
9160 
9161     // Assuming that both candidates are not matches...
9162 
9163     // Sort by the ranking of deduction failures.
9164     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9165       return RankDeductionFailure(L->DeductionFailure) <
9166              RankDeductionFailure(R->DeductionFailure);
9167 
9168     // Sort everything else by location.
9169     SourceLocation LLoc = GetLocationForCandidate(L);
9170     SourceLocation RLoc = GetLocationForCandidate(R);
9171 
9172     // Put candidates without locations (e.g. builtins) at the end.
9173     if (LLoc.isInvalid())
9174       return false;
9175     if (RLoc.isInvalid())
9176       return true;
9177 
9178     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9179   }
9180 };
9181 
9182 /// Diagnose a template argument deduction failure.
9183 /// We are treating these failures as overload failures due to bad
9184 /// deductions.
9185 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9186   DiagnoseBadDeduction(S, Specialization, // pattern
9187                        DeductionFailure, /*NumArgs=*/0);
9188 }
9189 
9190 void TemplateSpecCandidateSet::destroyCandidates() {
9191   for (iterator i = begin(), e = end(); i != e; ++i) {
9192     i->DeductionFailure.Destroy();
9193   }
9194 }
9195 
9196 void TemplateSpecCandidateSet::clear() {
9197   destroyCandidates();
9198   Candidates.clear();
9199 }
9200 
9201 /// NoteCandidates - When no template specialization match is found, prints
9202 /// diagnostic messages containing the non-matching specializations that form
9203 /// the candidate set.
9204 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9205 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9206 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9207   // Sort the candidates by position (assuming no candidate is a match).
9208   // Sorting directly would be prohibitive, so we make a set of pointers
9209   // and sort those.
9210   SmallVector<TemplateSpecCandidate *, 32> Cands;
9211   Cands.reserve(size());
9212   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9213     if (Cand->Specialization)
9214       Cands.push_back(Cand);
9215     // Otherwise, this is a non matching builtin candidate.  We do not,
9216     // in general, want to list every possible builtin candidate.
9217   }
9218 
9219   std::sort(Cands.begin(), Cands.end(),
9220             CompareTemplateSpecCandidatesForDisplay(S));
9221 
9222   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9223   // for generalization purposes (?).
9224   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9225 
9226   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9227   unsigned CandsShown = 0;
9228   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9229     TemplateSpecCandidate *Cand = *I;
9230 
9231     // Set an arbitrary limit on the number of candidates we'll spam
9232     // the user with.  FIXME: This limit should depend on details of the
9233     // candidate list.
9234     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9235       break;
9236     ++CandsShown;
9237 
9238     assert(Cand->Specialization &&
9239            "Non-matching built-in candidates are not added to Cands.");
9240     Cand->NoteDeductionFailure(S);
9241   }
9242 
9243   if (I != E)
9244     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9245 }
9246 
9247 // [PossiblyAFunctionType]  -->   [Return]
9248 // NonFunctionType --> NonFunctionType
9249 // R (A) --> R(A)
9250 // R (*)(A) --> R (A)
9251 // R (&)(A) --> R (A)
9252 // R (S::*)(A) --> R (A)
9253 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9254   QualType Ret = PossiblyAFunctionType;
9255   if (const PointerType *ToTypePtr =
9256     PossiblyAFunctionType->getAs<PointerType>())
9257     Ret = ToTypePtr->getPointeeType();
9258   else if (const ReferenceType *ToTypeRef =
9259     PossiblyAFunctionType->getAs<ReferenceType>())
9260     Ret = ToTypeRef->getPointeeType();
9261   else if (const MemberPointerType *MemTypePtr =
9262     PossiblyAFunctionType->getAs<MemberPointerType>())
9263     Ret = MemTypePtr->getPointeeType();
9264   Ret =
9265     Context.getCanonicalType(Ret).getUnqualifiedType();
9266   return Ret;
9267 }
9268 
9269 // A helper class to help with address of function resolution
9270 // - allows us to avoid passing around all those ugly parameters
9271 class AddressOfFunctionResolver
9272 {
9273   Sema& S;
9274   Expr* SourceExpr;
9275   const QualType& TargetType;
9276   QualType TargetFunctionType; // Extracted function type from target type
9277 
9278   bool Complain;
9279   //DeclAccessPair& ResultFunctionAccessPair;
9280   ASTContext& Context;
9281 
9282   bool TargetTypeIsNonStaticMemberFunction;
9283   bool FoundNonTemplateFunction;
9284   bool StaticMemberFunctionFromBoundPointer;
9285 
9286   OverloadExpr::FindResult OvlExprInfo;
9287   OverloadExpr *OvlExpr;
9288   TemplateArgumentListInfo OvlExplicitTemplateArgs;
9289   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9290   TemplateSpecCandidateSet FailedCandidates;
9291 
9292 public:
9293   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9294                             const QualType &TargetType, bool Complain)
9295       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9296         Complain(Complain), Context(S.getASTContext()),
9297         TargetTypeIsNonStaticMemberFunction(
9298             !!TargetType->getAs<MemberPointerType>()),
9299         FoundNonTemplateFunction(false),
9300         StaticMemberFunctionFromBoundPointer(false),
9301         OvlExprInfo(OverloadExpr::find(SourceExpr)),
9302         OvlExpr(OvlExprInfo.Expression),
9303         FailedCandidates(OvlExpr->getNameLoc()) {
9304     ExtractUnqualifiedFunctionTypeFromTargetType();
9305 
9306     if (TargetFunctionType->isFunctionType()) {
9307       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9308         if (!UME->isImplicitAccess() &&
9309             !S.ResolveSingleFunctionTemplateSpecialization(UME))
9310           StaticMemberFunctionFromBoundPointer = true;
9311     } else if (OvlExpr->hasExplicitTemplateArgs()) {
9312       DeclAccessPair dap;
9313       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9314               OvlExpr, false, &dap)) {
9315         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9316           if (!Method->isStatic()) {
9317             // If the target type is a non-function type and the function found
9318             // is a non-static member function, pretend as if that was the
9319             // target, it's the only possible type to end up with.
9320             TargetTypeIsNonStaticMemberFunction = true;
9321 
9322             // And skip adding the function if its not in the proper form.
9323             // We'll diagnose this due to an empty set of functions.
9324             if (!OvlExprInfo.HasFormOfMemberPointer)
9325               return;
9326           }
9327 
9328         Matches.push_back(std::make_pair(dap, Fn));
9329       }
9330       return;
9331     }
9332 
9333     if (OvlExpr->hasExplicitTemplateArgs())
9334       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9335 
9336     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9337       // C++ [over.over]p4:
9338       //   If more than one function is selected, [...]
9339       if (Matches.size() > 1) {
9340         if (FoundNonTemplateFunction)
9341           EliminateAllTemplateMatches();
9342         else
9343           EliminateAllExceptMostSpecializedTemplate();
9344       }
9345     }
9346   }
9347 
9348 private:
9349   bool isTargetTypeAFunction() const {
9350     return TargetFunctionType->isFunctionType();
9351   }
9352 
9353   // [ToType]     [Return]
9354 
9355   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9356   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9357   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9358   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9359     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9360   }
9361 
9362   // return true if any matching specializations were found
9363   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9364                                    const DeclAccessPair& CurAccessFunPair) {
9365     if (CXXMethodDecl *Method
9366               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9367       // Skip non-static function templates when converting to pointer, and
9368       // static when converting to member pointer.
9369       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9370         return false;
9371     }
9372     else if (TargetTypeIsNonStaticMemberFunction)
9373       return false;
9374 
9375     // C++ [over.over]p2:
9376     //   If the name is a function template, template argument deduction is
9377     //   done (14.8.2.2), and if the argument deduction succeeds, the
9378     //   resulting template argument list is used to generate a single
9379     //   function template specialization, which is added to the set of
9380     //   overloaded functions considered.
9381     FunctionDecl *Specialization = 0;
9382     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9383     if (Sema::TemplateDeductionResult Result
9384           = S.DeduceTemplateArguments(FunctionTemplate,
9385                                       &OvlExplicitTemplateArgs,
9386                                       TargetFunctionType, Specialization,
9387                                       Info, /*InOverloadResolution=*/true)) {
9388       // Make a note of the failed deduction for diagnostics.
9389       FailedCandidates.addCandidate()
9390           .set(FunctionTemplate->getTemplatedDecl(),
9391                MakeDeductionFailureInfo(Context, Result, Info));
9392       (void)Result;
9393       return false;
9394     }
9395 
9396     // Template argument deduction ensures that we have an exact match or
9397     // compatible pointer-to-function arguments that would be adjusted by ICS.
9398     // This function template specicalization works.
9399     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9400     assert(S.isSameOrCompatibleFunctionType(
9401               Context.getCanonicalType(Specialization->getType()),
9402               Context.getCanonicalType(TargetFunctionType)));
9403     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9404     return true;
9405   }
9406 
9407   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9408                                       const DeclAccessPair& CurAccessFunPair) {
9409     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9410       // Skip non-static functions when converting to pointer, and static
9411       // when converting to member pointer.
9412       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9413         return false;
9414     }
9415     else if (TargetTypeIsNonStaticMemberFunction)
9416       return false;
9417 
9418     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9419       if (S.getLangOpts().CUDA)
9420         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9421           if (S.CheckCUDATarget(Caller, FunDecl))
9422             return false;
9423 
9424       // If any candidate has a placeholder return type, trigger its deduction
9425       // now.
9426       if (S.getLangOpts().CPlusPlus1y &&
9427           FunDecl->getResultType()->isUndeducedType() &&
9428           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9429         return false;
9430 
9431       QualType ResultTy;
9432       if (Context.hasSameUnqualifiedType(TargetFunctionType,
9433                                          FunDecl->getType()) ||
9434           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9435                                  ResultTy)) {
9436         Matches.push_back(std::make_pair(CurAccessFunPair,
9437           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9438         FoundNonTemplateFunction = true;
9439         return true;
9440       }
9441     }
9442 
9443     return false;
9444   }
9445 
9446   bool FindAllFunctionsThatMatchTargetTypeExactly() {
9447     bool Ret = false;
9448 
9449     // If the overload expression doesn't have the form of a pointer to
9450     // member, don't try to convert it to a pointer-to-member type.
9451     if (IsInvalidFormOfPointerToMemberFunction())
9452       return false;
9453 
9454     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9455                                E = OvlExpr->decls_end();
9456          I != E; ++I) {
9457       // Look through any using declarations to find the underlying function.
9458       NamedDecl *Fn = (*I)->getUnderlyingDecl();
9459 
9460       // C++ [over.over]p3:
9461       //   Non-member functions and static member functions match
9462       //   targets of type "pointer-to-function" or "reference-to-function."
9463       //   Nonstatic member functions match targets of
9464       //   type "pointer-to-member-function."
9465       // Note that according to DR 247, the containing class does not matter.
9466       if (FunctionTemplateDecl *FunctionTemplate
9467                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
9468         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9469           Ret = true;
9470       }
9471       // If we have explicit template arguments supplied, skip non-templates.
9472       else if (!OvlExpr->hasExplicitTemplateArgs() &&
9473                AddMatchingNonTemplateFunction(Fn, I.getPair()))
9474         Ret = true;
9475     }
9476     assert(Ret || Matches.empty());
9477     return Ret;
9478   }
9479 
9480   void EliminateAllExceptMostSpecializedTemplate() {
9481     //   [...] and any given function template specialization F1 is
9482     //   eliminated if the set contains a second function template
9483     //   specialization whose function template is more specialized
9484     //   than the function template of F1 according to the partial
9485     //   ordering rules of 14.5.5.2.
9486 
9487     // The algorithm specified above is quadratic. We instead use a
9488     // two-pass algorithm (similar to the one used to identify the
9489     // best viable function in an overload set) that identifies the
9490     // best function template (if it exists).
9491 
9492     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9493     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9494       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9495 
9496     // TODO: It looks like FailedCandidates does not serve much purpose
9497     // here, since the no_viable diagnostic has index 0.
9498     UnresolvedSetIterator Result = S.getMostSpecialized(
9499         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, TPOC_Other, 0,
9500         SourceExpr->getLocStart(), S.PDiag(),
9501         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9502                                                      .second->getDeclName(),
9503         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9504         Complain, TargetFunctionType);
9505 
9506     if (Result != MatchesCopy.end()) {
9507       // Make it the first and only element
9508       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9509       Matches[0].second = cast<FunctionDecl>(*Result);
9510       Matches.resize(1);
9511     }
9512   }
9513 
9514   void EliminateAllTemplateMatches() {
9515     //   [...] any function template specializations in the set are
9516     //   eliminated if the set also contains a non-template function, [...]
9517     for (unsigned I = 0, N = Matches.size(); I != N; ) {
9518       if (Matches[I].second->getPrimaryTemplate() == 0)
9519         ++I;
9520       else {
9521         Matches[I] = Matches[--N];
9522         Matches.set_size(N);
9523       }
9524     }
9525   }
9526 
9527 public:
9528   void ComplainNoMatchesFound() const {
9529     assert(Matches.empty());
9530     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9531         << OvlExpr->getName() << TargetFunctionType
9532         << OvlExpr->getSourceRange();
9533     FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9534     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9535   }
9536 
9537   bool IsInvalidFormOfPointerToMemberFunction() const {
9538     return TargetTypeIsNonStaticMemberFunction &&
9539       !OvlExprInfo.HasFormOfMemberPointer;
9540   }
9541 
9542   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9543       // TODO: Should we condition this on whether any functions might
9544       // have matched, or is it more appropriate to do that in callers?
9545       // TODO: a fixit wouldn't hurt.
9546       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9547         << TargetType << OvlExpr->getSourceRange();
9548   }
9549 
9550   bool IsStaticMemberFunctionFromBoundPointer() const {
9551     return StaticMemberFunctionFromBoundPointer;
9552   }
9553 
9554   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9555     S.Diag(OvlExpr->getLocStart(),
9556            diag::err_invalid_form_pointer_member_function)
9557       << OvlExpr->getSourceRange();
9558   }
9559 
9560   void ComplainOfInvalidConversion() const {
9561     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9562       << OvlExpr->getName() << TargetType;
9563   }
9564 
9565   void ComplainMultipleMatchesFound() const {
9566     assert(Matches.size() > 1);
9567     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9568       << OvlExpr->getName()
9569       << OvlExpr->getSourceRange();
9570     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9571   }
9572 
9573   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9574 
9575   int getNumMatches() const { return Matches.size(); }
9576 
9577   FunctionDecl* getMatchingFunctionDecl() const {
9578     if (Matches.size() != 1) return 0;
9579     return Matches[0].second;
9580   }
9581 
9582   const DeclAccessPair* getMatchingFunctionAccessPair() const {
9583     if (Matches.size() != 1) return 0;
9584     return &Matches[0].first;
9585   }
9586 };
9587 
9588 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9589 /// an overloaded function (C++ [over.over]), where @p From is an
9590 /// expression with overloaded function type and @p ToType is the type
9591 /// we're trying to resolve to. For example:
9592 ///
9593 /// @code
9594 /// int f(double);
9595 /// int f(int);
9596 ///
9597 /// int (*pfd)(double) = f; // selects f(double)
9598 /// @endcode
9599 ///
9600 /// This routine returns the resulting FunctionDecl if it could be
9601 /// resolved, and NULL otherwise. When @p Complain is true, this
9602 /// routine will emit diagnostics if there is an error.
9603 FunctionDecl *
9604 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9605                                          QualType TargetType,
9606                                          bool Complain,
9607                                          DeclAccessPair &FoundResult,
9608                                          bool *pHadMultipleCandidates) {
9609   assert(AddressOfExpr->getType() == Context.OverloadTy);
9610 
9611   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9612                                      Complain);
9613   int NumMatches = Resolver.getNumMatches();
9614   FunctionDecl* Fn = 0;
9615   if (NumMatches == 0 && Complain) {
9616     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9617       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9618     else
9619       Resolver.ComplainNoMatchesFound();
9620   }
9621   else if (NumMatches > 1 && Complain)
9622     Resolver.ComplainMultipleMatchesFound();
9623   else if (NumMatches == 1) {
9624     Fn = Resolver.getMatchingFunctionDecl();
9625     assert(Fn);
9626     FoundResult = *Resolver.getMatchingFunctionAccessPair();
9627     if (Complain) {
9628       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9629         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9630       else
9631         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9632     }
9633   }
9634 
9635   if (pHadMultipleCandidates)
9636     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9637   return Fn;
9638 }
9639 
9640 /// \brief Given an expression that refers to an overloaded function, try to
9641 /// resolve that overloaded function expression down to a single function.
9642 ///
9643 /// This routine can only resolve template-ids that refer to a single function
9644 /// template, where that template-id refers to a single template whose template
9645 /// arguments are either provided by the template-id or have defaults,
9646 /// as described in C++0x [temp.arg.explicit]p3.
9647 FunctionDecl *
9648 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9649                                                   bool Complain,
9650                                                   DeclAccessPair *FoundResult) {
9651   // C++ [over.over]p1:
9652   //   [...] [Note: any redundant set of parentheses surrounding the
9653   //   overloaded function name is ignored (5.1). ]
9654   // C++ [over.over]p1:
9655   //   [...] The overloaded function name can be preceded by the &
9656   //   operator.
9657 
9658   // If we didn't actually find any template-ids, we're done.
9659   if (!ovl->hasExplicitTemplateArgs())
9660     return 0;
9661 
9662   TemplateArgumentListInfo ExplicitTemplateArgs;
9663   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9664   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
9665 
9666   // Look through all of the overloaded functions, searching for one
9667   // whose type matches exactly.
9668   FunctionDecl *Matched = 0;
9669   for (UnresolvedSetIterator I = ovl->decls_begin(),
9670          E = ovl->decls_end(); I != E; ++I) {
9671     // C++0x [temp.arg.explicit]p3:
9672     //   [...] In contexts where deduction is done and fails, or in contexts
9673     //   where deduction is not done, if a template argument list is
9674     //   specified and it, along with any default template arguments,
9675     //   identifies a single function template specialization, then the
9676     //   template-id is an lvalue for the function template specialization.
9677     FunctionTemplateDecl *FunctionTemplate
9678       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9679 
9680     // C++ [over.over]p2:
9681     //   If the name is a function template, template argument deduction is
9682     //   done (14.8.2.2), and if the argument deduction succeeds, the
9683     //   resulting template argument list is used to generate a single
9684     //   function template specialization, which is added to the set of
9685     //   overloaded functions considered.
9686     FunctionDecl *Specialization = 0;
9687     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9688     if (TemplateDeductionResult Result
9689           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9690                                     Specialization, Info,
9691                                     /*InOverloadResolution=*/true)) {
9692       // Make a note of the failed deduction for diagnostics.
9693       // TODO: Actually use the failed-deduction info?
9694       FailedCandidates.addCandidate()
9695           .set(FunctionTemplate->getTemplatedDecl(),
9696                MakeDeductionFailureInfo(Context, Result, Info));
9697       (void)Result;
9698       continue;
9699     }
9700 
9701     assert(Specialization && "no specialization and no error?");
9702 
9703     // Multiple matches; we can't resolve to a single declaration.
9704     if (Matched) {
9705       if (Complain) {
9706         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9707           << ovl->getName();
9708         NoteAllOverloadCandidates(ovl);
9709       }
9710       return 0;
9711     }
9712 
9713     Matched = Specialization;
9714     if (FoundResult) *FoundResult = I.getPair();
9715   }
9716 
9717   if (Matched && getLangOpts().CPlusPlus1y &&
9718       Matched->getResultType()->isUndeducedType() &&
9719       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9720     return 0;
9721 
9722   return Matched;
9723 }
9724 
9725 
9726 
9727 
9728 // Resolve and fix an overloaded expression that can be resolved
9729 // because it identifies a single function template specialization.
9730 //
9731 // Last three arguments should only be supplied if Complain = true
9732 //
9733 // Return true if it was logically possible to so resolve the
9734 // expression, regardless of whether or not it succeeded.  Always
9735 // returns true if 'complain' is set.
9736 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9737                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
9738                    bool complain, const SourceRange& OpRangeForComplaining,
9739                                            QualType DestTypeForComplaining,
9740                                             unsigned DiagIDForComplaining) {
9741   assert(SrcExpr.get()->getType() == Context.OverloadTy);
9742 
9743   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9744 
9745   DeclAccessPair found;
9746   ExprResult SingleFunctionExpression;
9747   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9748                            ovl.Expression, /*complain*/ false, &found)) {
9749     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9750       SrcExpr = ExprError();
9751       return true;
9752     }
9753 
9754     // It is only correct to resolve to an instance method if we're
9755     // resolving a form that's permitted to be a pointer to member.
9756     // Otherwise we'll end up making a bound member expression, which
9757     // is illegal in all the contexts we resolve like this.
9758     if (!ovl.HasFormOfMemberPointer &&
9759         isa<CXXMethodDecl>(fn) &&
9760         cast<CXXMethodDecl>(fn)->isInstance()) {
9761       if (!complain) return false;
9762 
9763       Diag(ovl.Expression->getExprLoc(),
9764            diag::err_bound_member_function)
9765         << 0 << ovl.Expression->getSourceRange();
9766 
9767       // TODO: I believe we only end up here if there's a mix of
9768       // static and non-static candidates (otherwise the expression
9769       // would have 'bound member' type, not 'overload' type).
9770       // Ideally we would note which candidate was chosen and why
9771       // the static candidates were rejected.
9772       SrcExpr = ExprError();
9773       return true;
9774     }
9775 
9776     // Fix the expression to refer to 'fn'.
9777     SingleFunctionExpression =
9778       Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9779 
9780     // If desired, do function-to-pointer decay.
9781     if (doFunctionPointerConverion) {
9782       SingleFunctionExpression =
9783         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9784       if (SingleFunctionExpression.isInvalid()) {
9785         SrcExpr = ExprError();
9786         return true;
9787       }
9788     }
9789   }
9790 
9791   if (!SingleFunctionExpression.isUsable()) {
9792     if (complain) {
9793       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9794         << ovl.Expression->getName()
9795         << DestTypeForComplaining
9796         << OpRangeForComplaining
9797         << ovl.Expression->getQualifierLoc().getSourceRange();
9798       NoteAllOverloadCandidates(SrcExpr.get());
9799 
9800       SrcExpr = ExprError();
9801       return true;
9802     }
9803 
9804     return false;
9805   }
9806 
9807   SrcExpr = SingleFunctionExpression;
9808   return true;
9809 }
9810 
9811 /// \brief Add a single candidate to the overload set.
9812 static void AddOverloadedCallCandidate(Sema &S,
9813                                        DeclAccessPair FoundDecl,
9814                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9815                                        ArrayRef<Expr *> Args,
9816                                        OverloadCandidateSet &CandidateSet,
9817                                        bool PartialOverloading,
9818                                        bool KnownValid) {
9819   NamedDecl *Callee = FoundDecl.getDecl();
9820   if (isa<UsingShadowDecl>(Callee))
9821     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9822 
9823   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9824     if (ExplicitTemplateArgs) {
9825       assert(!KnownValid && "Explicit template arguments?");
9826       return;
9827     }
9828     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9829                            PartialOverloading);
9830     return;
9831   }
9832 
9833   if (FunctionTemplateDecl *FuncTemplate
9834       = dyn_cast<FunctionTemplateDecl>(Callee)) {
9835     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9836                                    ExplicitTemplateArgs, Args, CandidateSet);
9837     return;
9838   }
9839 
9840   assert(!KnownValid && "unhandled case in overloaded call candidate");
9841 }
9842 
9843 /// \brief Add the overload candidates named by callee and/or found by argument
9844 /// dependent lookup to the given overload set.
9845 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9846                                        ArrayRef<Expr *> Args,
9847                                        OverloadCandidateSet &CandidateSet,
9848                                        bool PartialOverloading) {
9849 
9850 #ifndef NDEBUG
9851   // Verify that ArgumentDependentLookup is consistent with the rules
9852   // in C++0x [basic.lookup.argdep]p3:
9853   //
9854   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9855   //   and let Y be the lookup set produced by argument dependent
9856   //   lookup (defined as follows). If X contains
9857   //
9858   //     -- a declaration of a class member, or
9859   //
9860   //     -- a block-scope function declaration that is not a
9861   //        using-declaration, or
9862   //
9863   //     -- a declaration that is neither a function or a function
9864   //        template
9865   //
9866   //   then Y is empty.
9867 
9868   if (ULE->requiresADL()) {
9869     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9870            E = ULE->decls_end(); I != E; ++I) {
9871       assert(!(*I)->getDeclContext()->isRecord());
9872       assert(isa<UsingShadowDecl>(*I) ||
9873              !(*I)->getDeclContext()->isFunctionOrMethod());
9874       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9875     }
9876   }
9877 #endif
9878 
9879   // It would be nice to avoid this copy.
9880   TemplateArgumentListInfo TABuffer;
9881   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9882   if (ULE->hasExplicitTemplateArgs()) {
9883     ULE->copyTemplateArgumentsInto(TABuffer);
9884     ExplicitTemplateArgs = &TABuffer;
9885   }
9886 
9887   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9888          E = ULE->decls_end(); I != E; ++I)
9889     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9890                                CandidateSet, PartialOverloading,
9891                                /*KnownValid*/ true);
9892 
9893   if (ULE->requiresADL())
9894     AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9895                                          ULE->getExprLoc(),
9896                                          Args, ExplicitTemplateArgs,
9897                                          CandidateSet, PartialOverloading);
9898 }
9899 
9900 /// Determine whether a declaration with the specified name could be moved into
9901 /// a different namespace.
9902 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
9903   switch (Name.getCXXOverloadedOperator()) {
9904   case OO_New: case OO_Array_New:
9905   case OO_Delete: case OO_Array_Delete:
9906     return false;
9907 
9908   default:
9909     return true;
9910   }
9911 }
9912 
9913 /// Attempt to recover from an ill-formed use of a non-dependent name in a
9914 /// template, where the non-dependent name was declared after the template
9915 /// was defined. This is common in code written for a compilers which do not
9916 /// correctly implement two-stage name lookup.
9917 ///
9918 /// Returns true if a viable candidate was found and a diagnostic was issued.
9919 static bool
9920 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9921                        const CXXScopeSpec &SS, LookupResult &R,
9922                        TemplateArgumentListInfo *ExplicitTemplateArgs,
9923                        ArrayRef<Expr *> Args) {
9924   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9925     return false;
9926 
9927   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9928     if (DC->isTransparentContext())
9929       continue;
9930 
9931     SemaRef.LookupQualifiedName(R, DC);
9932 
9933     if (!R.empty()) {
9934       R.suppressDiagnostics();
9935 
9936       if (isa<CXXRecordDecl>(DC)) {
9937         // Don't diagnose names we find in classes; we get much better
9938         // diagnostics for these from DiagnoseEmptyLookup.
9939         R.clear();
9940         return false;
9941       }
9942 
9943       OverloadCandidateSet Candidates(FnLoc);
9944       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9945         AddOverloadedCallCandidate(SemaRef, I.getPair(),
9946                                    ExplicitTemplateArgs, Args,
9947                                    Candidates, false, /*KnownValid*/ false);
9948 
9949       OverloadCandidateSet::iterator Best;
9950       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9951         // No viable functions. Don't bother the user with notes for functions
9952         // which don't work and shouldn't be found anyway.
9953         R.clear();
9954         return false;
9955       }
9956 
9957       // Find the namespaces where ADL would have looked, and suggest
9958       // declaring the function there instead.
9959       Sema::AssociatedNamespaceSet AssociatedNamespaces;
9960       Sema::AssociatedClassSet AssociatedClasses;
9961       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
9962                                                  AssociatedNamespaces,
9963                                                  AssociatedClasses);
9964       Sema::AssociatedNamespaceSet SuggestedNamespaces;
9965       if (canBeDeclaredInNamespace(R.getLookupName())) {
9966         DeclContext *Std = SemaRef.getStdNamespace();
9967         for (Sema::AssociatedNamespaceSet::iterator
9968                it = AssociatedNamespaces.begin(),
9969                end = AssociatedNamespaces.end(); it != end; ++it) {
9970           // Never suggest declaring a function within namespace 'std'.
9971           if (Std && Std->Encloses(*it))
9972             continue;
9973 
9974           // Never suggest declaring a function within a namespace with a
9975           // reserved name, like __gnu_cxx.
9976           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9977           if (NS &&
9978               NS->getQualifiedNameAsString().find("__") != std::string::npos)
9979             continue;
9980 
9981           SuggestedNamespaces.insert(*it);
9982         }
9983       }
9984 
9985       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9986         << R.getLookupName();
9987       if (SuggestedNamespaces.empty()) {
9988         SemaRef.Diag(Best->Function->getLocation(),
9989                      diag::note_not_found_by_two_phase_lookup)
9990           << R.getLookupName() << 0;
9991       } else if (SuggestedNamespaces.size() == 1) {
9992         SemaRef.Diag(Best->Function->getLocation(),
9993                      diag::note_not_found_by_two_phase_lookup)
9994           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9995       } else {
9996         // FIXME: It would be useful to list the associated namespaces here,
9997         // but the diagnostics infrastructure doesn't provide a way to produce
9998         // a localized representation of a list of items.
9999         SemaRef.Diag(Best->Function->getLocation(),
10000                      diag::note_not_found_by_two_phase_lookup)
10001           << R.getLookupName() << 2;
10002       }
10003 
10004       // Try to recover by calling this function.
10005       return true;
10006     }
10007 
10008     R.clear();
10009   }
10010 
10011   return false;
10012 }
10013 
10014 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10015 /// template, where the non-dependent operator was declared after the template
10016 /// was defined.
10017 ///
10018 /// Returns true if a viable candidate was found and a diagnostic was issued.
10019 static bool
10020 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10021                                SourceLocation OpLoc,
10022                                ArrayRef<Expr *> Args) {
10023   DeclarationName OpName =
10024     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10025   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10026   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10027                                 /*ExplicitTemplateArgs=*/0, Args);
10028 }
10029 
10030 namespace {
10031 class BuildRecoveryCallExprRAII {
10032   Sema &SemaRef;
10033 public:
10034   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10035     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10036     SemaRef.IsBuildingRecoveryCallExpr = true;
10037   }
10038 
10039   ~BuildRecoveryCallExprRAII() {
10040     SemaRef.IsBuildingRecoveryCallExpr = false;
10041   }
10042 };
10043 
10044 }
10045 
10046 /// Attempts to recover from a call where no functions were found.
10047 ///
10048 /// Returns true if new candidates were found.
10049 static ExprResult
10050 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10051                       UnresolvedLookupExpr *ULE,
10052                       SourceLocation LParenLoc,
10053                       llvm::MutableArrayRef<Expr *> Args,
10054                       SourceLocation RParenLoc,
10055                       bool EmptyLookup, bool AllowTypoCorrection) {
10056   // Do not try to recover if it is already building a recovery call.
10057   // This stops infinite loops for template instantiations like
10058   //
10059   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10060   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10061   //
10062   if (SemaRef.IsBuildingRecoveryCallExpr)
10063     return ExprError();
10064   BuildRecoveryCallExprRAII RCE(SemaRef);
10065 
10066   CXXScopeSpec SS;
10067   SS.Adopt(ULE->getQualifierLoc());
10068   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10069 
10070   TemplateArgumentListInfo TABuffer;
10071   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
10072   if (ULE->hasExplicitTemplateArgs()) {
10073     ULE->copyTemplateArgumentsInto(TABuffer);
10074     ExplicitTemplateArgs = &TABuffer;
10075   }
10076 
10077   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10078                  Sema::LookupOrdinaryName);
10079   FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10080                                   ExplicitTemplateArgs != 0);
10081   NoTypoCorrectionCCC RejectAll;
10082   CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10083       (CorrectionCandidateCallback*)&Validator :
10084       (CorrectionCandidateCallback*)&RejectAll;
10085   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10086                               ExplicitTemplateArgs, Args) &&
10087       (!EmptyLookup ||
10088        SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
10089                                    ExplicitTemplateArgs, Args)))
10090     return ExprError();
10091 
10092   assert(!R.empty() && "lookup results empty despite recovery");
10093 
10094   // Build an implicit member call if appropriate.  Just drop the
10095   // casts and such from the call, we don't really care.
10096   ExprResult NewFn = ExprError();
10097   if ((*R.begin())->isCXXClassMember())
10098     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10099                                                     R, ExplicitTemplateArgs);
10100   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10101     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10102                                         ExplicitTemplateArgs);
10103   else
10104     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10105 
10106   if (NewFn.isInvalid())
10107     return ExprError();
10108 
10109   // This shouldn't cause an infinite loop because we're giving it
10110   // an expression with viable lookup results, which should never
10111   // end up here.
10112   return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
10113                                MultiExprArg(Args.data(), Args.size()),
10114                                RParenLoc);
10115 }
10116 
10117 /// \brief Constructs and populates an OverloadedCandidateSet from
10118 /// the given function.
10119 /// \returns true when an the ExprResult output parameter has been set.
10120 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10121                                   UnresolvedLookupExpr *ULE,
10122                                   MultiExprArg Args,
10123                                   SourceLocation RParenLoc,
10124                                   OverloadCandidateSet *CandidateSet,
10125                                   ExprResult *Result) {
10126 #ifndef NDEBUG
10127   if (ULE->requiresADL()) {
10128     // To do ADL, we must have found an unqualified name.
10129     assert(!ULE->getQualifier() && "qualified name with ADL");
10130 
10131     // We don't perform ADL for implicit declarations of builtins.
10132     // Verify that this was correctly set up.
10133     FunctionDecl *F;
10134     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10135         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10136         F->getBuiltinID() && F->isImplicit())
10137       llvm_unreachable("performing ADL for builtin");
10138 
10139     // We don't perform ADL in C.
10140     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10141   }
10142 #endif
10143 
10144   UnbridgedCastsSet UnbridgedCasts;
10145   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10146     *Result = ExprError();
10147     return true;
10148   }
10149 
10150   // Add the functions denoted by the callee to the set of candidate
10151   // functions, including those from argument-dependent lookup.
10152   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10153 
10154   // If we found nothing, try to recover.
10155   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10156   // out if it fails.
10157   if (CandidateSet->empty()) {
10158     // In Microsoft mode, if we are inside a template class member function then
10159     // create a type dependent CallExpr. The goal is to postpone name lookup
10160     // to instantiation time to be able to search into type dependent base
10161     // classes.
10162     if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
10163         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10164       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10165                                             Context.DependentTy, VK_RValue,
10166                                             RParenLoc);
10167       CE->setTypeDependent(true);
10168       *Result = Owned(CE);
10169       return true;
10170     }
10171     return false;
10172   }
10173 
10174   UnbridgedCasts.restore();
10175   return false;
10176 }
10177 
10178 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10179 /// the completed call expression. If overload resolution fails, emits
10180 /// diagnostics and returns ExprError()
10181 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10182                                            UnresolvedLookupExpr *ULE,
10183                                            SourceLocation LParenLoc,
10184                                            MultiExprArg Args,
10185                                            SourceLocation RParenLoc,
10186                                            Expr *ExecConfig,
10187                                            OverloadCandidateSet *CandidateSet,
10188                                            OverloadCandidateSet::iterator *Best,
10189                                            OverloadingResult OverloadResult,
10190                                            bool AllowTypoCorrection) {
10191   if (CandidateSet->empty())
10192     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10193                                  RParenLoc, /*EmptyLookup=*/true,
10194                                  AllowTypoCorrection);
10195 
10196   switch (OverloadResult) {
10197   case OR_Success: {
10198     FunctionDecl *FDecl = (*Best)->Function;
10199     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10200     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10201       return ExprError();
10202     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10203     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10204                                          ExecConfig);
10205   }
10206 
10207   case OR_No_Viable_Function: {
10208     // Try to recover by looking for viable functions which the user might
10209     // have meant to call.
10210     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10211                                                 Args, RParenLoc,
10212                                                 /*EmptyLookup=*/false,
10213                                                 AllowTypoCorrection);
10214     if (!Recovery.isInvalid())
10215       return Recovery;
10216 
10217     SemaRef.Diag(Fn->getLocStart(),
10218          diag::err_ovl_no_viable_function_in_call)
10219       << ULE->getName() << Fn->getSourceRange();
10220     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10221     break;
10222   }
10223 
10224   case OR_Ambiguous:
10225     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10226       << ULE->getName() << Fn->getSourceRange();
10227     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10228     break;
10229 
10230   case OR_Deleted: {
10231     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10232       << (*Best)->Function->isDeleted()
10233       << ULE->getName()
10234       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10235       << Fn->getSourceRange();
10236     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10237 
10238     // We emitted an error for the unvailable/deleted function call but keep
10239     // the call in the AST.
10240     FunctionDecl *FDecl = (*Best)->Function;
10241     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10242     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10243                                          ExecConfig);
10244   }
10245   }
10246 
10247   // Overload resolution failed.
10248   return ExprError();
10249 }
10250 
10251 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10252 /// (which eventually refers to the declaration Func) and the call
10253 /// arguments Args/NumArgs, attempt to resolve the function call down
10254 /// to a specific function. If overload resolution succeeds, returns
10255 /// the call expression produced by overload resolution.
10256 /// Otherwise, emits diagnostics and returns ExprError.
10257 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10258                                          UnresolvedLookupExpr *ULE,
10259                                          SourceLocation LParenLoc,
10260                                          MultiExprArg Args,
10261                                          SourceLocation RParenLoc,
10262                                          Expr *ExecConfig,
10263                                          bool AllowTypoCorrection) {
10264   OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10265   ExprResult result;
10266 
10267   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10268                              &result))
10269     return result;
10270 
10271   OverloadCandidateSet::iterator Best;
10272   OverloadingResult OverloadResult =
10273       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10274 
10275   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10276                                   RParenLoc, ExecConfig, &CandidateSet,
10277                                   &Best, OverloadResult,
10278                                   AllowTypoCorrection);
10279 }
10280 
10281 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10282   return Functions.size() > 1 ||
10283     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10284 }
10285 
10286 /// \brief Create a unary operation that may resolve to an overloaded
10287 /// operator.
10288 ///
10289 /// \param OpLoc The location of the operator itself (e.g., '*').
10290 ///
10291 /// \param OpcIn The UnaryOperator::Opcode that describes this
10292 /// operator.
10293 ///
10294 /// \param Fns The set of non-member functions that will be
10295 /// considered by overload resolution. The caller needs to build this
10296 /// set based on the context using, e.g.,
10297 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10298 /// set should not contain any member functions; those will be added
10299 /// by CreateOverloadedUnaryOp().
10300 ///
10301 /// \param Input The input argument.
10302 ExprResult
10303 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10304                               const UnresolvedSetImpl &Fns,
10305                               Expr *Input) {
10306   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10307 
10308   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10309   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10310   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10311   // TODO: provide better source location info.
10312   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10313 
10314   if (checkPlaceholderForOverload(*this, Input))
10315     return ExprError();
10316 
10317   Expr *Args[2] = { Input, 0 };
10318   unsigned NumArgs = 1;
10319 
10320   // For post-increment and post-decrement, add the implicit '0' as
10321   // the second argument, so that we know this is a post-increment or
10322   // post-decrement.
10323   if (Opc == UO_PostInc || Opc == UO_PostDec) {
10324     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10325     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10326                                      SourceLocation());
10327     NumArgs = 2;
10328   }
10329 
10330   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10331 
10332   if (Input->isTypeDependent()) {
10333     if (Fns.empty())
10334       return Owned(new (Context) UnaryOperator(Input,
10335                                                Opc,
10336                                                Context.DependentTy,
10337                                                VK_RValue, OK_Ordinary,
10338                                                OpLoc));
10339 
10340     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10341     UnresolvedLookupExpr *Fn
10342       = UnresolvedLookupExpr::Create(Context, NamingClass,
10343                                      NestedNameSpecifierLoc(), OpNameInfo,
10344                                      /*ADL*/ true, IsOverloaded(Fns),
10345                                      Fns.begin(), Fns.end());
10346     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
10347                                                    Context.DependentTy,
10348                                                    VK_RValue,
10349                                                    OpLoc, false));
10350   }
10351 
10352   // Build an empty overload set.
10353   OverloadCandidateSet CandidateSet(OpLoc);
10354 
10355   // Add the candidates from the given function set.
10356   AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10357 
10358   // Add operator candidates that are member functions.
10359   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10360 
10361   // Add candidates from ADL.
10362   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10363                                        ArgsArray, /*ExplicitTemplateArgs*/ 0,
10364                                        CandidateSet);
10365 
10366   // Add builtin operator candidates.
10367   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10368 
10369   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10370 
10371   // Perform overload resolution.
10372   OverloadCandidateSet::iterator Best;
10373   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10374   case OR_Success: {
10375     // We found a built-in operator or an overloaded operator.
10376     FunctionDecl *FnDecl = Best->Function;
10377 
10378     if (FnDecl) {
10379       // We matched an overloaded operator. Build a call to that
10380       // operator.
10381 
10382       // Convert the arguments.
10383       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10384         CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
10385 
10386         ExprResult InputRes =
10387           PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10388                                               Best->FoundDecl, Method);
10389         if (InputRes.isInvalid())
10390           return ExprError();
10391         Input = InputRes.take();
10392       } else {
10393         // Convert the arguments.
10394         ExprResult InputInit
10395           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10396                                                       Context,
10397                                                       FnDecl->getParamDecl(0)),
10398                                       SourceLocation(),
10399                                       Input);
10400         if (InputInit.isInvalid())
10401           return ExprError();
10402         Input = InputInit.take();
10403       }
10404 
10405       // Determine the result type.
10406       QualType ResultTy = FnDecl->getResultType();
10407       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10408       ResultTy = ResultTy.getNonLValueExprType(Context);
10409 
10410       // Build the actual expression node.
10411       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10412                                                 HadMultipleCandidates, OpLoc);
10413       if (FnExpr.isInvalid())
10414         return ExprError();
10415 
10416       Args[0] = Input;
10417       CallExpr *TheCall =
10418         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
10419                                           ResultTy, VK, OpLoc, false);
10420 
10421       if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10422                               FnDecl))
10423         return ExprError();
10424 
10425       return MaybeBindToTemporary(TheCall);
10426     } else {
10427       // We matched a built-in operator. Convert the arguments, then
10428       // break out so that we will build the appropriate built-in
10429       // operator node.
10430       ExprResult InputRes =
10431         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10432                                   Best->Conversions[0], AA_Passing);
10433       if (InputRes.isInvalid())
10434         return ExprError();
10435       Input = InputRes.take();
10436       break;
10437     }
10438   }
10439 
10440   case OR_No_Viable_Function:
10441     // This is an erroneous use of an operator which can be overloaded by
10442     // a non-member function. Check for non-member operators which were
10443     // defined too late to be candidates.
10444     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10445       // FIXME: Recover by calling the found function.
10446       return ExprError();
10447 
10448     // No viable function; fall through to handling this as a
10449     // built-in operator, which will produce an error message for us.
10450     break;
10451 
10452   case OR_Ambiguous:
10453     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10454         << UnaryOperator::getOpcodeStr(Opc)
10455         << Input->getType()
10456         << Input->getSourceRange();
10457     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
10458                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10459     return ExprError();
10460 
10461   case OR_Deleted:
10462     Diag(OpLoc, diag::err_ovl_deleted_oper)
10463       << Best->Function->isDeleted()
10464       << UnaryOperator::getOpcodeStr(Opc)
10465       << getDeletedOrUnavailableSuffix(Best->Function)
10466       << Input->getSourceRange();
10467     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10468                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10469     return ExprError();
10470   }
10471 
10472   // Either we found no viable overloaded operator or we matched a
10473   // built-in operator. In either case, fall through to trying to
10474   // build a built-in operation.
10475   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10476 }
10477 
10478 /// \brief Create a binary operation that may resolve to an overloaded
10479 /// operator.
10480 ///
10481 /// \param OpLoc The location of the operator itself (e.g., '+').
10482 ///
10483 /// \param OpcIn The BinaryOperator::Opcode that describes this
10484 /// operator.
10485 ///
10486 /// \param Fns The set of non-member functions that will be
10487 /// considered by overload resolution. The caller needs to build this
10488 /// set based on the context using, e.g.,
10489 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10490 /// set should not contain any member functions; those will be added
10491 /// by CreateOverloadedBinOp().
10492 ///
10493 /// \param LHS Left-hand argument.
10494 /// \param RHS Right-hand argument.
10495 ExprResult
10496 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10497                             unsigned OpcIn,
10498                             const UnresolvedSetImpl &Fns,
10499                             Expr *LHS, Expr *RHS) {
10500   Expr *Args[2] = { LHS, RHS };
10501   LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10502 
10503   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10504   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10505   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10506 
10507   // If either side is type-dependent, create an appropriate dependent
10508   // expression.
10509   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10510     if (Fns.empty()) {
10511       // If there are no functions to store, just build a dependent
10512       // BinaryOperator or CompoundAssignment.
10513       if (Opc <= BO_Assign || Opc > BO_OrAssign)
10514         return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10515                                                   Context.DependentTy,
10516                                                   VK_RValue, OK_Ordinary,
10517                                                   OpLoc,
10518                                                   FPFeatures.fp_contract));
10519 
10520       return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10521                                                         Context.DependentTy,
10522                                                         VK_LValue,
10523                                                         OK_Ordinary,
10524                                                         Context.DependentTy,
10525                                                         Context.DependentTy,
10526                                                         OpLoc,
10527                                                         FPFeatures.fp_contract));
10528     }
10529 
10530     // FIXME: save results of ADL from here?
10531     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10532     // TODO: provide better source location info in DNLoc component.
10533     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10534     UnresolvedLookupExpr *Fn
10535       = UnresolvedLookupExpr::Create(Context, NamingClass,
10536                                      NestedNameSpecifierLoc(), OpNameInfo,
10537                                      /*ADL*/ true, IsOverloaded(Fns),
10538                                      Fns.begin(), Fns.end());
10539     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10540                                                 Context.DependentTy, VK_RValue,
10541                                                 OpLoc, FPFeatures.fp_contract));
10542   }
10543 
10544   // Always do placeholder-like conversions on the RHS.
10545   if (checkPlaceholderForOverload(*this, Args[1]))
10546     return ExprError();
10547 
10548   // Do placeholder-like conversion on the LHS; note that we should
10549   // not get here with a PseudoObject LHS.
10550   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10551   if (checkPlaceholderForOverload(*this, Args[0]))
10552     return ExprError();
10553 
10554   // If this is the assignment operator, we only perform overload resolution
10555   // if the left-hand side is a class or enumeration type. This is actually
10556   // a hack. The standard requires that we do overload resolution between the
10557   // various built-in candidates, but as DR507 points out, this can lead to
10558   // problems. So we do it this way, which pretty much follows what GCC does.
10559   // Note that we go the traditional code path for compound assignment forms.
10560   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10561     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10562 
10563   // If this is the .* operator, which is not overloadable, just
10564   // create a built-in binary operator.
10565   if (Opc == BO_PtrMemD)
10566     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10567 
10568   // Build an empty overload set.
10569   OverloadCandidateSet CandidateSet(OpLoc);
10570 
10571   // Add the candidates from the given function set.
10572   AddFunctionCandidates(Fns, Args, CandidateSet, false);
10573 
10574   // Add operator candidates that are member functions.
10575   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10576 
10577   // Add candidates from ADL.
10578   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10579                                        OpLoc, Args,
10580                                        /*ExplicitTemplateArgs*/ 0,
10581                                        CandidateSet);
10582 
10583   // Add builtin operator candidates.
10584   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10585 
10586   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10587 
10588   // Perform overload resolution.
10589   OverloadCandidateSet::iterator Best;
10590   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10591     case OR_Success: {
10592       // We found a built-in operator or an overloaded operator.
10593       FunctionDecl *FnDecl = Best->Function;
10594 
10595       if (FnDecl) {
10596         // We matched an overloaded operator. Build a call to that
10597         // operator.
10598 
10599         // Convert the arguments.
10600         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10601           // Best->Access is only meaningful for class members.
10602           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10603 
10604           ExprResult Arg1 =
10605             PerformCopyInitialization(
10606               InitializedEntity::InitializeParameter(Context,
10607                                                      FnDecl->getParamDecl(0)),
10608               SourceLocation(), Owned(Args[1]));
10609           if (Arg1.isInvalid())
10610             return ExprError();
10611 
10612           ExprResult Arg0 =
10613             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10614                                                 Best->FoundDecl, Method);
10615           if (Arg0.isInvalid())
10616             return ExprError();
10617           Args[0] = Arg0.takeAs<Expr>();
10618           Args[1] = RHS = Arg1.takeAs<Expr>();
10619         } else {
10620           // Convert the arguments.
10621           ExprResult Arg0 = PerformCopyInitialization(
10622             InitializedEntity::InitializeParameter(Context,
10623                                                    FnDecl->getParamDecl(0)),
10624             SourceLocation(), Owned(Args[0]));
10625           if (Arg0.isInvalid())
10626             return ExprError();
10627 
10628           ExprResult Arg1 =
10629             PerformCopyInitialization(
10630               InitializedEntity::InitializeParameter(Context,
10631                                                      FnDecl->getParamDecl(1)),
10632               SourceLocation(), Owned(Args[1]));
10633           if (Arg1.isInvalid())
10634             return ExprError();
10635           Args[0] = LHS = Arg0.takeAs<Expr>();
10636           Args[1] = RHS = Arg1.takeAs<Expr>();
10637         }
10638 
10639         // Determine the result type.
10640         QualType ResultTy = FnDecl->getResultType();
10641         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10642         ResultTy = ResultTy.getNonLValueExprType(Context);
10643 
10644         // Build the actual expression node.
10645         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10646                                                   Best->FoundDecl,
10647                                                   HadMultipleCandidates, OpLoc);
10648         if (FnExpr.isInvalid())
10649           return ExprError();
10650 
10651         CXXOperatorCallExpr *TheCall =
10652           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10653                                             Args, ResultTy, VK, OpLoc,
10654                                             FPFeatures.fp_contract);
10655 
10656         if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10657                                 FnDecl))
10658           return ExprError();
10659 
10660         ArrayRef<const Expr *> ArgsArray(Args, 2);
10661         // Cut off the implicit 'this'.
10662         if (isa<CXXMethodDecl>(FnDecl))
10663           ArgsArray = ArgsArray.slice(1);
10664         checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10665                   TheCall->getSourceRange(), VariadicDoesNotApply);
10666 
10667         return MaybeBindToTemporary(TheCall);
10668       } else {
10669         // We matched a built-in operator. Convert the arguments, then
10670         // break out so that we will build the appropriate built-in
10671         // operator node.
10672         ExprResult ArgsRes0 =
10673           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10674                                     Best->Conversions[0], AA_Passing);
10675         if (ArgsRes0.isInvalid())
10676           return ExprError();
10677         Args[0] = ArgsRes0.take();
10678 
10679         ExprResult ArgsRes1 =
10680           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10681                                     Best->Conversions[1], AA_Passing);
10682         if (ArgsRes1.isInvalid())
10683           return ExprError();
10684         Args[1] = ArgsRes1.take();
10685         break;
10686       }
10687     }
10688 
10689     case OR_No_Viable_Function: {
10690       // C++ [over.match.oper]p9:
10691       //   If the operator is the operator , [...] and there are no
10692       //   viable functions, then the operator is assumed to be the
10693       //   built-in operator and interpreted according to clause 5.
10694       if (Opc == BO_Comma)
10695         break;
10696 
10697       // For class as left operand for assignment or compound assigment
10698       // operator do not fall through to handling in built-in, but report that
10699       // no overloaded assignment operator found
10700       ExprResult Result = ExprError();
10701       if (Args[0]->getType()->isRecordType() &&
10702           Opc >= BO_Assign && Opc <= BO_OrAssign) {
10703         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10704              << BinaryOperator::getOpcodeStr(Opc)
10705              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10706       } else {
10707         // This is an erroneous use of an operator which can be overloaded by
10708         // a non-member function. Check for non-member operators which were
10709         // defined too late to be candidates.
10710         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10711           // FIXME: Recover by calling the found function.
10712           return ExprError();
10713 
10714         // No viable function; try to create a built-in operation, which will
10715         // produce an error. Then, show the non-viable candidates.
10716         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10717       }
10718       assert(Result.isInvalid() &&
10719              "C++ binary operator overloading is missing candidates!");
10720       if (Result.isInvalid())
10721         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10722                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
10723       return Result;
10724     }
10725 
10726     case OR_Ambiguous:
10727       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10728           << BinaryOperator::getOpcodeStr(Opc)
10729           << Args[0]->getType() << Args[1]->getType()
10730           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10731       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10732                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10733       return ExprError();
10734 
10735     case OR_Deleted:
10736       if (isImplicitlyDeleted(Best->Function)) {
10737         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10738         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10739           << Context.getRecordType(Method->getParent())
10740           << getSpecialMember(Method);
10741 
10742         // The user probably meant to call this special member. Just
10743         // explain why it's deleted.
10744         NoteDeletedFunction(Method);
10745         return ExprError();
10746       } else {
10747         Diag(OpLoc, diag::err_ovl_deleted_oper)
10748           << Best->Function->isDeleted()
10749           << BinaryOperator::getOpcodeStr(Opc)
10750           << getDeletedOrUnavailableSuffix(Best->Function)
10751           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10752       }
10753       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10754                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10755       return ExprError();
10756   }
10757 
10758   // We matched a built-in operator; build it.
10759   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10760 }
10761 
10762 ExprResult
10763 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10764                                          SourceLocation RLoc,
10765                                          Expr *Base, Expr *Idx) {
10766   Expr *Args[2] = { Base, Idx };
10767   DeclarationName OpName =
10768       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10769 
10770   // If either side is type-dependent, create an appropriate dependent
10771   // expression.
10772   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10773 
10774     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10775     // CHECKME: no 'operator' keyword?
10776     DeclarationNameInfo OpNameInfo(OpName, LLoc);
10777     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10778     UnresolvedLookupExpr *Fn
10779       = UnresolvedLookupExpr::Create(Context, NamingClass,
10780                                      NestedNameSpecifierLoc(), OpNameInfo,
10781                                      /*ADL*/ true, /*Overloaded*/ false,
10782                                      UnresolvedSetIterator(),
10783                                      UnresolvedSetIterator());
10784     // Can't add any actual overloads yet
10785 
10786     return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10787                                                    Args,
10788                                                    Context.DependentTy,
10789                                                    VK_RValue,
10790                                                    RLoc, false));
10791   }
10792 
10793   // Handle placeholders on both operands.
10794   if (checkPlaceholderForOverload(*this, Args[0]))
10795     return ExprError();
10796   if (checkPlaceholderForOverload(*this, Args[1]))
10797     return ExprError();
10798 
10799   // Build an empty overload set.
10800   OverloadCandidateSet CandidateSet(LLoc);
10801 
10802   // Subscript can only be overloaded as a member function.
10803 
10804   // Add operator candidates that are member functions.
10805   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10806 
10807   // Add builtin operator candidates.
10808   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10809 
10810   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10811 
10812   // Perform overload resolution.
10813   OverloadCandidateSet::iterator Best;
10814   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10815     case OR_Success: {
10816       // We found a built-in operator or an overloaded operator.
10817       FunctionDecl *FnDecl = Best->Function;
10818 
10819       if (FnDecl) {
10820         // We matched an overloaded operator. Build a call to that
10821         // operator.
10822 
10823         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10824 
10825         // Convert the arguments.
10826         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10827         ExprResult Arg0 =
10828           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10829                                               Best->FoundDecl, Method);
10830         if (Arg0.isInvalid())
10831           return ExprError();
10832         Args[0] = Arg0.take();
10833 
10834         // Convert the arguments.
10835         ExprResult InputInit
10836           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10837                                                       Context,
10838                                                       FnDecl->getParamDecl(0)),
10839                                       SourceLocation(),
10840                                       Owned(Args[1]));
10841         if (InputInit.isInvalid())
10842           return ExprError();
10843 
10844         Args[1] = InputInit.takeAs<Expr>();
10845 
10846         // Determine the result type
10847         QualType ResultTy = FnDecl->getResultType();
10848         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10849         ResultTy = ResultTy.getNonLValueExprType(Context);
10850 
10851         // Build the actual expression node.
10852         DeclarationNameInfo OpLocInfo(OpName, LLoc);
10853         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10854         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10855                                                   Best->FoundDecl,
10856                                                   HadMultipleCandidates,
10857                                                   OpLocInfo.getLoc(),
10858                                                   OpLocInfo.getInfo());
10859         if (FnExpr.isInvalid())
10860           return ExprError();
10861 
10862         CXXOperatorCallExpr *TheCall =
10863           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10864                                             FnExpr.take(), Args,
10865                                             ResultTy, VK, RLoc,
10866                                             false);
10867 
10868         if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10869                                 FnDecl))
10870           return ExprError();
10871 
10872         return MaybeBindToTemporary(TheCall);
10873       } else {
10874         // We matched a built-in operator. Convert the arguments, then
10875         // break out so that we will build the appropriate built-in
10876         // operator node.
10877         ExprResult ArgsRes0 =
10878           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10879                                     Best->Conversions[0], AA_Passing);
10880         if (ArgsRes0.isInvalid())
10881           return ExprError();
10882         Args[0] = ArgsRes0.take();
10883 
10884         ExprResult ArgsRes1 =
10885           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10886                                     Best->Conversions[1], AA_Passing);
10887         if (ArgsRes1.isInvalid())
10888           return ExprError();
10889         Args[1] = ArgsRes1.take();
10890 
10891         break;
10892       }
10893     }
10894 
10895     case OR_No_Viable_Function: {
10896       if (CandidateSet.empty())
10897         Diag(LLoc, diag::err_ovl_no_oper)
10898           << Args[0]->getType() << /*subscript*/ 0
10899           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10900       else
10901         Diag(LLoc, diag::err_ovl_no_viable_subscript)
10902           << Args[0]->getType()
10903           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10904       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10905                                   "[]", LLoc);
10906       return ExprError();
10907     }
10908 
10909     case OR_Ambiguous:
10910       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10911           << "[]"
10912           << Args[0]->getType() << Args[1]->getType()
10913           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10914       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10915                                   "[]", LLoc);
10916       return ExprError();
10917 
10918     case OR_Deleted:
10919       Diag(LLoc, diag::err_ovl_deleted_oper)
10920         << Best->Function->isDeleted() << "[]"
10921         << getDeletedOrUnavailableSuffix(Best->Function)
10922         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10923       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10924                                   "[]", LLoc);
10925       return ExprError();
10926     }
10927 
10928   // We matched a built-in operator; build it.
10929   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10930 }
10931 
10932 /// BuildCallToMemberFunction - Build a call to a member
10933 /// function. MemExpr is the expression that refers to the member
10934 /// function (and includes the object parameter), Args/NumArgs are the
10935 /// arguments to the function call (not including the object
10936 /// parameter). The caller needs to validate that the member
10937 /// expression refers to a non-static member function or an overloaded
10938 /// member function.
10939 ExprResult
10940 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10941                                 SourceLocation LParenLoc,
10942                                 MultiExprArg Args,
10943                                 SourceLocation RParenLoc) {
10944   assert(MemExprE->getType() == Context.BoundMemberTy ||
10945          MemExprE->getType() == Context.OverloadTy);
10946 
10947   // Dig out the member expression. This holds both the object
10948   // argument and the member function we're referring to.
10949   Expr *NakedMemExpr = MemExprE->IgnoreParens();
10950 
10951   // Determine whether this is a call to a pointer-to-member function.
10952   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10953     assert(op->getType() == Context.BoundMemberTy);
10954     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10955 
10956     QualType fnType =
10957       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10958 
10959     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10960     QualType resultType = proto->getCallResultType(Context);
10961     ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10962 
10963     // Check that the object type isn't more qualified than the
10964     // member function we're calling.
10965     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10966 
10967     QualType objectType = op->getLHS()->getType();
10968     if (op->getOpcode() == BO_PtrMemI)
10969       objectType = objectType->castAs<PointerType>()->getPointeeType();
10970     Qualifiers objectQuals = objectType.getQualifiers();
10971 
10972     Qualifiers difference = objectQuals - funcQuals;
10973     difference.removeObjCGCAttr();
10974     difference.removeAddressSpace();
10975     if (difference) {
10976       std::string qualsString = difference.getAsString();
10977       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10978         << fnType.getUnqualifiedType()
10979         << qualsString
10980         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10981     }
10982 
10983     CXXMemberCallExpr *call
10984       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
10985                                         resultType, valueKind, RParenLoc);
10986 
10987     if (CheckCallReturnType(proto->getResultType(),
10988                             op->getRHS()->getLocStart(),
10989                             call, 0))
10990       return ExprError();
10991 
10992     if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
10993       return ExprError();
10994 
10995     if (CheckOtherCall(call, proto))
10996       return ExprError();
10997 
10998     return MaybeBindToTemporary(call);
10999   }
11000 
11001   UnbridgedCastsSet UnbridgedCasts;
11002   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11003     return ExprError();
11004 
11005   MemberExpr *MemExpr;
11006   CXXMethodDecl *Method = 0;
11007   DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
11008   NestedNameSpecifier *Qualifier = 0;
11009   if (isa<MemberExpr>(NakedMemExpr)) {
11010     MemExpr = cast<MemberExpr>(NakedMemExpr);
11011     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11012     FoundDecl = MemExpr->getFoundDecl();
11013     Qualifier = MemExpr->getQualifier();
11014     UnbridgedCasts.restore();
11015   } else {
11016     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11017     Qualifier = UnresExpr->getQualifier();
11018 
11019     QualType ObjectType = UnresExpr->getBaseType();
11020     Expr::Classification ObjectClassification
11021       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11022                             : UnresExpr->getBase()->Classify(Context);
11023 
11024     // Add overload candidates
11025     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
11026 
11027     // FIXME: avoid copy.
11028     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11029     if (UnresExpr->hasExplicitTemplateArgs()) {
11030       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11031       TemplateArgs = &TemplateArgsBuffer;
11032     }
11033 
11034     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11035            E = UnresExpr->decls_end(); I != E; ++I) {
11036 
11037       NamedDecl *Func = *I;
11038       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11039       if (isa<UsingShadowDecl>(Func))
11040         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11041 
11042 
11043       // Microsoft supports direct constructor calls.
11044       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11045         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11046                              Args, CandidateSet);
11047       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11048         // If explicit template arguments were provided, we can't call a
11049         // non-template member function.
11050         if (TemplateArgs)
11051           continue;
11052 
11053         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11054                            ObjectClassification, Args, CandidateSet,
11055                            /*SuppressUserConversions=*/false);
11056       } else {
11057         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11058                                    I.getPair(), ActingDC, TemplateArgs,
11059                                    ObjectType,  ObjectClassification,
11060                                    Args, CandidateSet,
11061                                    /*SuppressUsedConversions=*/false);
11062       }
11063     }
11064 
11065     DeclarationName DeclName = UnresExpr->getMemberName();
11066 
11067     UnbridgedCasts.restore();
11068 
11069     OverloadCandidateSet::iterator Best;
11070     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11071                                             Best)) {
11072     case OR_Success:
11073       Method = cast<CXXMethodDecl>(Best->Function);
11074       FoundDecl = Best->FoundDecl;
11075       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11076       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11077         return ExprError();
11078       // If FoundDecl is different from Method (such as if one is a template
11079       // and the other a specialization), make sure DiagnoseUseOfDecl is
11080       // called on both.
11081       // FIXME: This would be more comprehensively addressed by modifying
11082       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11083       // being used.
11084       if (Method != FoundDecl.getDecl() &&
11085                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11086         return ExprError();
11087       break;
11088 
11089     case OR_No_Viable_Function:
11090       Diag(UnresExpr->getMemberLoc(),
11091            diag::err_ovl_no_viable_member_function_in_call)
11092         << DeclName << MemExprE->getSourceRange();
11093       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11094       // FIXME: Leaking incoming expressions!
11095       return ExprError();
11096 
11097     case OR_Ambiguous:
11098       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11099         << DeclName << MemExprE->getSourceRange();
11100       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11101       // FIXME: Leaking incoming expressions!
11102       return ExprError();
11103 
11104     case OR_Deleted:
11105       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11106         << Best->Function->isDeleted()
11107         << DeclName
11108         << getDeletedOrUnavailableSuffix(Best->Function)
11109         << MemExprE->getSourceRange();
11110       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11111       // FIXME: Leaking incoming expressions!
11112       return ExprError();
11113     }
11114 
11115     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11116 
11117     // If overload resolution picked a static member, build a
11118     // non-member call based on that function.
11119     if (Method->isStatic()) {
11120       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11121                                    RParenLoc);
11122     }
11123 
11124     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11125   }
11126 
11127   QualType ResultType = Method->getResultType();
11128   ExprValueKind VK = Expr::getValueKindForType(ResultType);
11129   ResultType = ResultType.getNonLValueExprType(Context);
11130 
11131   assert(Method && "Member call to something that isn't a method?");
11132   CXXMemberCallExpr *TheCall =
11133     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11134                                     ResultType, VK, RParenLoc);
11135 
11136   // Check for a valid return type.
11137   if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
11138                           TheCall, Method))
11139     return ExprError();
11140 
11141   // Convert the object argument (for a non-static member function call).
11142   // We only need to do this if there was actually an overload; otherwise
11143   // it was done at lookup.
11144   if (!Method->isStatic()) {
11145     ExprResult ObjectArg =
11146       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11147                                           FoundDecl, Method);
11148     if (ObjectArg.isInvalid())
11149       return ExprError();
11150     MemExpr->setBase(ObjectArg.take());
11151   }
11152 
11153   // Convert the rest of the arguments
11154   const FunctionProtoType *Proto =
11155     Method->getType()->getAs<FunctionProtoType>();
11156   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11157                               RParenLoc))
11158     return ExprError();
11159 
11160   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11161 
11162   if (CheckFunctionCall(Method, TheCall, Proto))
11163     return ExprError();
11164 
11165   if ((isa<CXXConstructorDecl>(CurContext) ||
11166        isa<CXXDestructorDecl>(CurContext)) &&
11167       TheCall->getMethodDecl()->isPure()) {
11168     const CXXMethodDecl *MD = TheCall->getMethodDecl();
11169 
11170     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11171       Diag(MemExpr->getLocStart(),
11172            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11173         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11174         << MD->getParent()->getDeclName();
11175 
11176       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11177     }
11178   }
11179   return MaybeBindToTemporary(TheCall);
11180 }
11181 
11182 /// BuildCallToObjectOfClassType - Build a call to an object of class
11183 /// type (C++ [over.call.object]), which can end up invoking an
11184 /// overloaded function call operator (@c operator()) or performing a
11185 /// user-defined conversion on the object argument.
11186 ExprResult
11187 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11188                                    SourceLocation LParenLoc,
11189                                    MultiExprArg Args,
11190                                    SourceLocation RParenLoc) {
11191   if (checkPlaceholderForOverload(*this, Obj))
11192     return ExprError();
11193   ExprResult Object = Owned(Obj);
11194 
11195   UnbridgedCastsSet UnbridgedCasts;
11196   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11197     return ExprError();
11198 
11199   assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11200   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11201 
11202   // C++ [over.call.object]p1:
11203   //  If the primary-expression E in the function call syntax
11204   //  evaluates to a class object of type "cv T", then the set of
11205   //  candidate functions includes at least the function call
11206   //  operators of T. The function call operators of T are obtained by
11207   //  ordinary lookup of the name operator() in the context of
11208   //  (E).operator().
11209   OverloadCandidateSet CandidateSet(LParenLoc);
11210   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11211 
11212   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11213                           diag::err_incomplete_object_call, Object.get()))
11214     return true;
11215 
11216   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11217   LookupQualifiedName(R, Record->getDecl());
11218   R.suppressDiagnostics();
11219 
11220   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11221        Oper != OperEnd; ++Oper) {
11222     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11223                        Object.get()->Classify(Context),
11224                        Args, CandidateSet,
11225                        /*SuppressUserConversions=*/ false);
11226   }
11227 
11228   // C++ [over.call.object]p2:
11229   //   In addition, for each (non-explicit in C++0x) conversion function
11230   //   declared in T of the form
11231   //
11232   //        operator conversion-type-id () cv-qualifier;
11233   //
11234   //   where cv-qualifier is the same cv-qualification as, or a
11235   //   greater cv-qualification than, cv, and where conversion-type-id
11236   //   denotes the type "pointer to function of (P1,...,Pn) returning
11237   //   R", or the type "reference to pointer to function of
11238   //   (P1,...,Pn) returning R", or the type "reference to function
11239   //   of (P1,...,Pn) returning R", a surrogate call function [...]
11240   //   is also considered as a candidate function. Similarly,
11241   //   surrogate call functions are added to the set of candidate
11242   //   functions for each conversion function declared in an
11243   //   accessible base class provided the function is not hidden
11244   //   within T by another intervening declaration.
11245   std::pair<CXXRecordDecl::conversion_iterator,
11246             CXXRecordDecl::conversion_iterator> Conversions
11247     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11248   for (CXXRecordDecl::conversion_iterator
11249          I = Conversions.first, E = Conversions.second; I != E; ++I) {
11250     NamedDecl *D = *I;
11251     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11252     if (isa<UsingShadowDecl>(D))
11253       D = cast<UsingShadowDecl>(D)->getTargetDecl();
11254 
11255     // Skip over templated conversion functions; they aren't
11256     // surrogates.
11257     if (isa<FunctionTemplateDecl>(D))
11258       continue;
11259 
11260     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11261     if (!Conv->isExplicit()) {
11262       // Strip the reference type (if any) and then the pointer type (if
11263       // any) to get down to what might be a function type.
11264       QualType ConvType = Conv->getConversionType().getNonReferenceType();
11265       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11266         ConvType = ConvPtrType->getPointeeType();
11267 
11268       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11269       {
11270         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11271                               Object.get(), Args, CandidateSet);
11272       }
11273     }
11274   }
11275 
11276   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11277 
11278   // Perform overload resolution.
11279   OverloadCandidateSet::iterator Best;
11280   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11281                              Best)) {
11282   case OR_Success:
11283     // Overload resolution succeeded; we'll build the appropriate call
11284     // below.
11285     break;
11286 
11287   case OR_No_Viable_Function:
11288     if (CandidateSet.empty())
11289       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11290         << Object.get()->getType() << /*call*/ 1
11291         << Object.get()->getSourceRange();
11292     else
11293       Diag(Object.get()->getLocStart(),
11294            diag::err_ovl_no_viable_object_call)
11295         << Object.get()->getType() << Object.get()->getSourceRange();
11296     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11297     break;
11298 
11299   case OR_Ambiguous:
11300     Diag(Object.get()->getLocStart(),
11301          diag::err_ovl_ambiguous_object_call)
11302       << Object.get()->getType() << Object.get()->getSourceRange();
11303     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11304     break;
11305 
11306   case OR_Deleted:
11307     Diag(Object.get()->getLocStart(),
11308          diag::err_ovl_deleted_object_call)
11309       << Best->Function->isDeleted()
11310       << Object.get()->getType()
11311       << getDeletedOrUnavailableSuffix(Best->Function)
11312       << Object.get()->getSourceRange();
11313     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11314     break;
11315   }
11316 
11317   if (Best == CandidateSet.end())
11318     return true;
11319 
11320   UnbridgedCasts.restore();
11321 
11322   if (Best->Function == 0) {
11323     // Since there is no function declaration, this is one of the
11324     // surrogate candidates. Dig out the conversion function.
11325     CXXConversionDecl *Conv
11326       = cast<CXXConversionDecl>(
11327                          Best->Conversions[0].UserDefined.ConversionFunction);
11328 
11329     CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11330     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11331       return ExprError();
11332     assert(Conv == Best->FoundDecl.getDecl() &&
11333              "Found Decl & conversion-to-functionptr should be same, right?!");
11334     // We selected one of the surrogate functions that converts the
11335     // object parameter to a function pointer. Perform the conversion
11336     // on the object argument, then let ActOnCallExpr finish the job.
11337 
11338     // Create an implicit member expr to refer to the conversion operator.
11339     // and then call it.
11340     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11341                                              Conv, HadMultipleCandidates);
11342     if (Call.isInvalid())
11343       return ExprError();
11344     // Record usage of conversion in an implicit cast.
11345     Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11346                                           CK_UserDefinedConversion,
11347                                           Call.get(), 0, VK_RValue));
11348 
11349     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11350   }
11351 
11352   CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11353 
11354   // We found an overloaded operator(). Build a CXXOperatorCallExpr
11355   // that calls this method, using Object for the implicit object
11356   // parameter and passing along the remaining arguments.
11357   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11358 
11359   // An error diagnostic has already been printed when parsing the declaration.
11360   if (Method->isInvalidDecl())
11361     return ExprError();
11362 
11363   const FunctionProtoType *Proto =
11364     Method->getType()->getAs<FunctionProtoType>();
11365 
11366   unsigned NumArgsInProto = Proto->getNumArgs();
11367   unsigned NumArgsToCheck = Args.size();
11368 
11369   // Build the full argument list for the method call (the
11370   // implicit object parameter is placed at the beginning of the
11371   // list).
11372   Expr **MethodArgs;
11373   if (Args.size() < NumArgsInProto) {
11374     NumArgsToCheck = NumArgsInProto;
11375     MethodArgs = new Expr*[NumArgsInProto + 1];
11376   } else {
11377     MethodArgs = new Expr*[Args.size() + 1];
11378   }
11379   MethodArgs[0] = Object.get();
11380   for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
11381     MethodArgs[ArgIdx + 1] = Args[ArgIdx];
11382 
11383   DeclarationNameInfo OpLocInfo(
11384                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11385   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11386   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11387                                            HadMultipleCandidates,
11388                                            OpLocInfo.getLoc(),
11389                                            OpLocInfo.getInfo());
11390   if (NewFn.isInvalid())
11391     return true;
11392 
11393   // Once we've built TheCall, all of the expressions are properly
11394   // owned.
11395   QualType ResultTy = Method->getResultType();
11396   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11397   ResultTy = ResultTy.getNonLValueExprType(Context);
11398 
11399   CXXOperatorCallExpr *TheCall =
11400     new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11401                                       llvm::makeArrayRef(MethodArgs, Args.size()+1),
11402                                       ResultTy, VK, RParenLoc, false);
11403   delete [] MethodArgs;
11404 
11405   if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11406                           Method))
11407     return true;
11408 
11409   // We may have default arguments. If so, we need to allocate more
11410   // slots in the call for them.
11411   if (Args.size() < NumArgsInProto)
11412     TheCall->setNumArgs(Context, NumArgsInProto + 1);
11413   else if (Args.size() > NumArgsInProto)
11414     NumArgsToCheck = NumArgsInProto;
11415 
11416   bool IsError = false;
11417 
11418   // Initialize the implicit object parameter.
11419   ExprResult ObjRes =
11420     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11421                                         Best->FoundDecl, Method);
11422   if (ObjRes.isInvalid())
11423     IsError = true;
11424   else
11425     Object = ObjRes;
11426   TheCall->setArg(0, Object.take());
11427 
11428   // Check the argument types.
11429   for (unsigned i = 0; i != NumArgsToCheck; i++) {
11430     Expr *Arg;
11431     if (i < Args.size()) {
11432       Arg = Args[i];
11433 
11434       // Pass the argument.
11435 
11436       ExprResult InputInit
11437         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11438                                                     Context,
11439                                                     Method->getParamDecl(i)),
11440                                     SourceLocation(), Arg);
11441 
11442       IsError |= InputInit.isInvalid();
11443       Arg = InputInit.takeAs<Expr>();
11444     } else {
11445       ExprResult DefArg
11446         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11447       if (DefArg.isInvalid()) {
11448         IsError = true;
11449         break;
11450       }
11451 
11452       Arg = DefArg.takeAs<Expr>();
11453     }
11454 
11455     TheCall->setArg(i + 1, Arg);
11456   }
11457 
11458   // If this is a variadic call, handle args passed through "...".
11459   if (Proto->isVariadic()) {
11460     // Promote the arguments (C99 6.5.2.2p7).
11461     for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
11462       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11463       IsError |= Arg.isInvalid();
11464       TheCall->setArg(i + 1, Arg.take());
11465     }
11466   }
11467 
11468   if (IsError) return true;
11469 
11470   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11471 
11472   if (CheckFunctionCall(Method, TheCall, Proto))
11473     return true;
11474 
11475   return MaybeBindToTemporary(TheCall);
11476 }
11477 
11478 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11479 ///  (if one exists), where @c Base is an expression of class type and
11480 /// @c Member is the name of the member we're trying to find.
11481 ExprResult
11482 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11483                                bool *NoArrowOperatorFound) {
11484   assert(Base->getType()->isRecordType() &&
11485          "left-hand side must have class type");
11486 
11487   if (checkPlaceholderForOverload(*this, Base))
11488     return ExprError();
11489 
11490   SourceLocation Loc = Base->getExprLoc();
11491 
11492   // C++ [over.ref]p1:
11493   //
11494   //   [...] An expression x->m is interpreted as (x.operator->())->m
11495   //   for a class object x of type T if T::operator->() exists and if
11496   //   the operator is selected as the best match function by the
11497   //   overload resolution mechanism (13.3).
11498   DeclarationName OpName =
11499     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11500   OverloadCandidateSet CandidateSet(Loc);
11501   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11502 
11503   if (RequireCompleteType(Loc, Base->getType(),
11504                           diag::err_typecheck_incomplete_tag, Base))
11505     return ExprError();
11506 
11507   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11508   LookupQualifiedName(R, BaseRecord->getDecl());
11509   R.suppressDiagnostics();
11510 
11511   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11512        Oper != OperEnd; ++Oper) {
11513     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11514                        None, CandidateSet, /*SuppressUserConversions=*/false);
11515   }
11516 
11517   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11518 
11519   // Perform overload resolution.
11520   OverloadCandidateSet::iterator Best;
11521   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11522   case OR_Success:
11523     // Overload resolution succeeded; we'll build the call below.
11524     break;
11525 
11526   case OR_No_Viable_Function:
11527     if (CandidateSet.empty()) {
11528       QualType BaseType = Base->getType();
11529       if (NoArrowOperatorFound) {
11530         // Report this specific error to the caller instead of emitting a
11531         // diagnostic, as requested.
11532         *NoArrowOperatorFound = true;
11533         return ExprError();
11534       }
11535       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11536         << BaseType << Base->getSourceRange();
11537       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
11538         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
11539           << FixItHint::CreateReplacement(OpLoc, ".");
11540       }
11541     } else
11542       Diag(OpLoc, diag::err_ovl_no_viable_oper)
11543         << "operator->" << Base->getSourceRange();
11544     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11545     return ExprError();
11546 
11547   case OR_Ambiguous:
11548     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11549       << "->" << Base->getType() << Base->getSourceRange();
11550     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11551     return ExprError();
11552 
11553   case OR_Deleted:
11554     Diag(OpLoc,  diag::err_ovl_deleted_oper)
11555       << Best->Function->isDeleted()
11556       << "->"
11557       << getDeletedOrUnavailableSuffix(Best->Function)
11558       << Base->getSourceRange();
11559     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11560     return ExprError();
11561   }
11562 
11563   CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11564 
11565   // Convert the object parameter.
11566   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11567   ExprResult BaseResult =
11568     PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11569                                         Best->FoundDecl, Method);
11570   if (BaseResult.isInvalid())
11571     return ExprError();
11572   Base = BaseResult.take();
11573 
11574   // Build the operator call.
11575   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11576                                             HadMultipleCandidates, OpLoc);
11577   if (FnExpr.isInvalid())
11578     return ExprError();
11579 
11580   QualType ResultTy = Method->getResultType();
11581   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11582   ResultTy = ResultTy.getNonLValueExprType(Context);
11583   CXXOperatorCallExpr *TheCall =
11584     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11585                                       Base, ResultTy, VK, OpLoc, false);
11586 
11587   if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11588                           Method))
11589           return ExprError();
11590 
11591   return MaybeBindToTemporary(TheCall);
11592 }
11593 
11594 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11595 /// a literal operator described by the provided lookup results.
11596 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11597                                           DeclarationNameInfo &SuffixInfo,
11598                                           ArrayRef<Expr*> Args,
11599                                           SourceLocation LitEndLoc,
11600                                        TemplateArgumentListInfo *TemplateArgs) {
11601   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11602 
11603   OverloadCandidateSet CandidateSet(UDSuffixLoc);
11604   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11605                         TemplateArgs);
11606 
11607   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11608 
11609   // Perform overload resolution. This will usually be trivial, but might need
11610   // to perform substitutions for a literal operator template.
11611   OverloadCandidateSet::iterator Best;
11612   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11613   case OR_Success:
11614   case OR_Deleted:
11615     break;
11616 
11617   case OR_No_Viable_Function:
11618     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11619       << R.getLookupName();
11620     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11621     return ExprError();
11622 
11623   case OR_Ambiguous:
11624     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11625     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11626     return ExprError();
11627   }
11628 
11629   FunctionDecl *FD = Best->Function;
11630   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11631                                         HadMultipleCandidates,
11632                                         SuffixInfo.getLoc(),
11633                                         SuffixInfo.getInfo());
11634   if (Fn.isInvalid())
11635     return true;
11636 
11637   // Check the argument types. This should almost always be a no-op, except
11638   // that array-to-pointer decay is applied to string literals.
11639   Expr *ConvArgs[2];
11640   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
11641     ExprResult InputInit = PerformCopyInitialization(
11642       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11643       SourceLocation(), Args[ArgIdx]);
11644     if (InputInit.isInvalid())
11645       return true;
11646     ConvArgs[ArgIdx] = InputInit.take();
11647   }
11648 
11649   QualType ResultTy = FD->getResultType();
11650   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11651   ResultTy = ResultTy.getNonLValueExprType(Context);
11652 
11653   UserDefinedLiteral *UDL =
11654     new (Context) UserDefinedLiteral(Context, Fn.take(),
11655                                      llvm::makeArrayRef(ConvArgs, Args.size()),
11656                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
11657 
11658   if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11659     return ExprError();
11660 
11661   if (CheckFunctionCall(FD, UDL, NULL))
11662     return ExprError();
11663 
11664   return MaybeBindToTemporary(UDL);
11665 }
11666 
11667 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11668 /// given LookupResult is non-empty, it is assumed to describe a member which
11669 /// will be invoked. Otherwise, the function will be found via argument
11670 /// dependent lookup.
11671 /// CallExpr is set to a valid expression and FRS_Success returned on success,
11672 /// otherwise CallExpr is set to ExprError() and some non-success value
11673 /// is returned.
11674 Sema::ForRangeStatus
11675 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11676                                 SourceLocation RangeLoc, VarDecl *Decl,
11677                                 BeginEndFunction BEF,
11678                                 const DeclarationNameInfo &NameInfo,
11679                                 LookupResult &MemberLookup,
11680                                 OverloadCandidateSet *CandidateSet,
11681                                 Expr *Range, ExprResult *CallExpr) {
11682   CandidateSet->clear();
11683   if (!MemberLookup.empty()) {
11684     ExprResult MemberRef =
11685         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11686                                  /*IsPtr=*/false, CXXScopeSpec(),
11687                                  /*TemplateKWLoc=*/SourceLocation(),
11688                                  /*FirstQualifierInScope=*/0,
11689                                  MemberLookup,
11690                                  /*TemplateArgs=*/0);
11691     if (MemberRef.isInvalid()) {
11692       *CallExpr = ExprError();
11693       Diag(Range->getLocStart(), diag::note_in_for_range)
11694           << RangeLoc << BEF << Range->getType();
11695       return FRS_DiagnosticIssued;
11696     }
11697     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
11698     if (CallExpr->isInvalid()) {
11699       *CallExpr = ExprError();
11700       Diag(Range->getLocStart(), diag::note_in_for_range)
11701           << RangeLoc << BEF << Range->getType();
11702       return FRS_DiagnosticIssued;
11703     }
11704   } else {
11705     UnresolvedSet<0> FoundNames;
11706     UnresolvedLookupExpr *Fn =
11707       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11708                                    NestedNameSpecifierLoc(), NameInfo,
11709                                    /*NeedsADL=*/true, /*Overloaded=*/false,
11710                                    FoundNames.begin(), FoundNames.end());
11711 
11712     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
11713                                                     CandidateSet, CallExpr);
11714     if (CandidateSet->empty() || CandidateSetError) {
11715       *CallExpr = ExprError();
11716       return FRS_NoViableFunction;
11717     }
11718     OverloadCandidateSet::iterator Best;
11719     OverloadingResult OverloadResult =
11720         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11721 
11722     if (OverloadResult == OR_No_Viable_Function) {
11723       *CallExpr = ExprError();
11724       return FRS_NoViableFunction;
11725     }
11726     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
11727                                          Loc, 0, CandidateSet, &Best,
11728                                          OverloadResult,
11729                                          /*AllowTypoCorrection=*/false);
11730     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11731       *CallExpr = ExprError();
11732       Diag(Range->getLocStart(), diag::note_in_for_range)
11733           << RangeLoc << BEF << Range->getType();
11734       return FRS_DiagnosticIssued;
11735     }
11736   }
11737   return FRS_Success;
11738 }
11739 
11740 
11741 /// FixOverloadedFunctionReference - E is an expression that refers to
11742 /// a C++ overloaded function (possibly with some parentheses and
11743 /// perhaps a '&' around it). We have resolved the overloaded function
11744 /// to the function declaration Fn, so patch up the expression E to
11745 /// refer (possibly indirectly) to Fn. Returns the new expr.
11746 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11747                                            FunctionDecl *Fn) {
11748   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11749     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11750                                                    Found, Fn);
11751     if (SubExpr == PE->getSubExpr())
11752       return PE;
11753 
11754     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11755   }
11756 
11757   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11758     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11759                                                    Found, Fn);
11760     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11761                                SubExpr->getType()) &&
11762            "Implicit cast type cannot be determined from overload");
11763     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11764     if (SubExpr == ICE->getSubExpr())
11765       return ICE;
11766 
11767     return ImplicitCastExpr::Create(Context, ICE->getType(),
11768                                     ICE->getCastKind(),
11769                                     SubExpr, 0,
11770                                     ICE->getValueKind());
11771   }
11772 
11773   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11774     assert(UnOp->getOpcode() == UO_AddrOf &&
11775            "Can only take the address of an overloaded function");
11776     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11777       if (Method->isStatic()) {
11778         // Do nothing: static member functions aren't any different
11779         // from non-member functions.
11780       } else {
11781         // Fix the sub expression, which really has to be an
11782         // UnresolvedLookupExpr holding an overloaded member function
11783         // or template.
11784         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11785                                                        Found, Fn);
11786         if (SubExpr == UnOp->getSubExpr())
11787           return UnOp;
11788 
11789         assert(isa<DeclRefExpr>(SubExpr)
11790                && "fixed to something other than a decl ref");
11791         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11792                && "fixed to a member ref with no nested name qualifier");
11793 
11794         // We have taken the address of a pointer to member
11795         // function. Perform the computation here so that we get the
11796         // appropriate pointer to member type.
11797         QualType ClassType
11798           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11799         QualType MemPtrType
11800           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11801 
11802         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11803                                            VK_RValue, OK_Ordinary,
11804                                            UnOp->getOperatorLoc());
11805       }
11806     }
11807     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11808                                                    Found, Fn);
11809     if (SubExpr == UnOp->getSubExpr())
11810       return UnOp;
11811 
11812     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11813                                      Context.getPointerType(SubExpr->getType()),
11814                                        VK_RValue, OK_Ordinary,
11815                                        UnOp->getOperatorLoc());
11816   }
11817 
11818   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11819     // FIXME: avoid copy.
11820     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11821     if (ULE->hasExplicitTemplateArgs()) {
11822       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11823       TemplateArgs = &TemplateArgsBuffer;
11824     }
11825 
11826     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11827                                            ULE->getQualifierLoc(),
11828                                            ULE->getTemplateKeywordLoc(),
11829                                            Fn,
11830                                            /*enclosing*/ false, // FIXME?
11831                                            ULE->getNameLoc(),
11832                                            Fn->getType(),
11833                                            VK_LValue,
11834                                            Found.getDecl(),
11835                                            TemplateArgs);
11836     MarkDeclRefReferenced(DRE);
11837     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11838     return DRE;
11839   }
11840 
11841   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11842     // FIXME: avoid copy.
11843     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11844     if (MemExpr->hasExplicitTemplateArgs()) {
11845       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11846       TemplateArgs = &TemplateArgsBuffer;
11847     }
11848 
11849     Expr *Base;
11850 
11851     // If we're filling in a static method where we used to have an
11852     // implicit member access, rewrite to a simple decl ref.
11853     if (MemExpr->isImplicitAccess()) {
11854       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11855         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11856                                                MemExpr->getQualifierLoc(),
11857                                                MemExpr->getTemplateKeywordLoc(),
11858                                                Fn,
11859                                                /*enclosing*/ false,
11860                                                MemExpr->getMemberLoc(),
11861                                                Fn->getType(),
11862                                                VK_LValue,
11863                                                Found.getDecl(),
11864                                                TemplateArgs);
11865         MarkDeclRefReferenced(DRE);
11866         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11867         return DRE;
11868       } else {
11869         SourceLocation Loc = MemExpr->getMemberLoc();
11870         if (MemExpr->getQualifier())
11871           Loc = MemExpr->getQualifierLoc().getBeginLoc();
11872         CheckCXXThisCapture(Loc);
11873         Base = new (Context) CXXThisExpr(Loc,
11874                                          MemExpr->getBaseType(),
11875                                          /*isImplicit=*/true);
11876       }
11877     } else
11878       Base = MemExpr->getBase();
11879 
11880     ExprValueKind valueKind;
11881     QualType type;
11882     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11883       valueKind = VK_LValue;
11884       type = Fn->getType();
11885     } else {
11886       valueKind = VK_RValue;
11887       type = Context.BoundMemberTy;
11888     }
11889 
11890     MemberExpr *ME = MemberExpr::Create(Context, Base,
11891                                         MemExpr->isArrow(),
11892                                         MemExpr->getQualifierLoc(),
11893                                         MemExpr->getTemplateKeywordLoc(),
11894                                         Fn,
11895                                         Found,
11896                                         MemExpr->getMemberNameInfo(),
11897                                         TemplateArgs,
11898                                         type, valueKind, OK_Ordinary);
11899     ME->setHadMultipleCandidates(true);
11900     MarkMemberReferenced(ME);
11901     return ME;
11902   }
11903 
11904   llvm_unreachable("Invalid reference to overloaded function");
11905 }
11906 
11907 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11908                                                 DeclAccessPair Found,
11909                                                 FunctionDecl *Fn) {
11910   return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11911 }
11912 
11913 } // end namespace clang
11914