SemaOverload.cpp revision e9f6f33f0cf98a3e39025a57a0079cd316ed98f8
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/Basic/TargetInfo.h"
25#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
31#include "llvm/ADT/DenseSet.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallString.h"
35#include <algorithm>
36
37namespace clang {
38using namespace sema;
39
40/// A convenience routine for creating a decayed reference to a function.
41static ExprResult
42CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
43                      bool HadMultipleCandidates,
44                      SourceLocation Loc = SourceLocation(),
45                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
46  if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
47    return ExprError();
48  // If FoundDecl is different from Fn (such as if one is a template
49  // and the other a specialization), make sure DiagnoseUseOfDecl is
50  // called on both.
51  // FIXME: This would be more comprehensively addressed by modifying
52  // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
53  // being used.
54  if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
55    return ExprError();
56  DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
57                                                 VK_LValue, Loc, LocInfo);
58  if (HadMultipleCandidates)
59    DRE->setHadMultipleCandidates(true);
60
61  S.MarkDeclRefReferenced(DRE);
62
63  ExprResult E = S.Owned(DRE);
64  E = S.DefaultFunctionArrayConversion(E.take());
65  if (E.isInvalid())
66    return ExprError();
67  return E;
68}
69
70static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
71                                 bool InOverloadResolution,
72                                 StandardConversionSequence &SCS,
73                                 bool CStyle,
74                                 bool AllowObjCWritebackConversion);
75
76static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
77                                                 QualType &ToType,
78                                                 bool InOverloadResolution,
79                                                 StandardConversionSequence &SCS,
80                                                 bool CStyle);
81static OverloadingResult
82IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
83                        UserDefinedConversionSequence& User,
84                        OverloadCandidateSet& Conversions,
85                        bool AllowExplicit);
86
87
88static ImplicitConversionSequence::CompareKind
89CompareStandardConversionSequences(Sema &S,
90                                   const StandardConversionSequence& SCS1,
91                                   const StandardConversionSequence& SCS2);
92
93static ImplicitConversionSequence::CompareKind
94CompareQualificationConversions(Sema &S,
95                                const StandardConversionSequence& SCS1,
96                                const StandardConversionSequence& SCS2);
97
98static ImplicitConversionSequence::CompareKind
99CompareDerivedToBaseConversions(Sema &S,
100                                const StandardConversionSequence& SCS1,
101                                const StandardConversionSequence& SCS2);
102
103
104
105/// GetConversionCategory - Retrieve the implicit conversion
106/// category corresponding to the given implicit conversion kind.
107ImplicitConversionCategory
108GetConversionCategory(ImplicitConversionKind Kind) {
109  static const ImplicitConversionCategory
110    Category[(int)ICK_Num_Conversion_Kinds] = {
111    ICC_Identity,
112    ICC_Lvalue_Transformation,
113    ICC_Lvalue_Transformation,
114    ICC_Lvalue_Transformation,
115    ICC_Identity,
116    ICC_Qualification_Adjustment,
117    ICC_Promotion,
118    ICC_Promotion,
119    ICC_Promotion,
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    ICC_Conversion
133  };
134  return Category[(int)Kind];
135}
136
137/// GetConversionRank - Retrieve the implicit conversion rank
138/// corresponding to the given implicit conversion kind.
139ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
140  static const ImplicitConversionRank
141    Rank[(int)ICK_Num_Conversion_Kinds] = {
142    ICR_Exact_Match,
143    ICR_Exact_Match,
144    ICR_Exact_Match,
145    ICR_Exact_Match,
146    ICR_Exact_Match,
147    ICR_Exact_Match,
148    ICR_Promotion,
149    ICR_Promotion,
150    ICR_Promotion,
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_Conversion,
162    ICR_Complex_Real_Conversion,
163    ICR_Conversion,
164    ICR_Conversion,
165    ICR_Writeback_Conversion
166  };
167  return Rank[(int)Kind];
168}
169
170/// GetImplicitConversionName - Return the name of this kind of
171/// implicit conversion.
172const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
173  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
174    "No conversion",
175    "Lvalue-to-rvalue",
176    "Array-to-pointer",
177    "Function-to-pointer",
178    "Noreturn adjustment",
179    "Qualification",
180    "Integral promotion",
181    "Floating point promotion",
182    "Complex promotion",
183    "Integral conversion",
184    "Floating conversion",
185    "Complex conversion",
186    "Floating-integral conversion",
187    "Pointer conversion",
188    "Pointer-to-member conversion",
189    "Boolean conversion",
190    "Compatible-types conversion",
191    "Derived-to-base conversion",
192    "Vector conversion",
193    "Vector splat",
194    "Complex-real conversion",
195    "Block Pointer conversion",
196    "Transparent Union Conversion"
197    "Writeback conversion"
198  };
199  return Name[Kind];
200}
201
202/// StandardConversionSequence - Set the standard conversion
203/// sequence to the identity conversion.
204void StandardConversionSequence::setAsIdentityConversion() {
205  First = ICK_Identity;
206  Second = ICK_Identity;
207  Third = ICK_Identity;
208  DeprecatedStringLiteralToCharPtr = false;
209  QualificationIncludesObjCLifetime = false;
210  ReferenceBinding = false;
211  DirectBinding = false;
212  IsLvalueReference = true;
213  BindsToFunctionLvalue = false;
214  BindsToRvalue = false;
215  BindsImplicitObjectArgumentWithoutRefQualifier = false;
216  ObjCLifetimeConversionBinding = false;
217  CopyConstructor = 0;
218}
219
220/// getRank - Retrieve the rank of this standard conversion sequence
221/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
222/// implicit conversions.
223ImplicitConversionRank StandardConversionSequence::getRank() const {
224  ImplicitConversionRank Rank = ICR_Exact_Match;
225  if  (GetConversionRank(First) > Rank)
226    Rank = GetConversionRank(First);
227  if  (GetConversionRank(Second) > Rank)
228    Rank = GetConversionRank(Second);
229  if  (GetConversionRank(Third) > Rank)
230    Rank = GetConversionRank(Third);
231  return Rank;
232}
233
234/// isPointerConversionToBool - Determines whether this conversion is
235/// a conversion of a pointer or pointer-to-member to bool. This is
236/// used as part of the ranking of standard conversion sequences
237/// (C++ 13.3.3.2p4).
238bool StandardConversionSequence::isPointerConversionToBool() const {
239  // Note that FromType has not necessarily been transformed by the
240  // array-to-pointer or function-to-pointer implicit conversions, so
241  // check for their presence as well as checking whether FromType is
242  // a pointer.
243  if (getToType(1)->isBooleanType() &&
244      (getFromType()->isPointerType() ||
245       getFromType()->isObjCObjectPointerType() ||
246       getFromType()->isBlockPointerType() ||
247       getFromType()->isNullPtrType() ||
248       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
249    return true;
250
251  return false;
252}
253
254/// isPointerConversionToVoidPointer - Determines whether this
255/// conversion is a conversion of a pointer to a void pointer. This is
256/// used as part of the ranking of standard conversion sequences (C++
257/// 13.3.3.2p4).
258bool
259StandardConversionSequence::
260isPointerConversionToVoidPointer(ASTContext& Context) const {
261  QualType FromType = getFromType();
262  QualType ToType = getToType(1);
263
264  // Note that FromType has not necessarily been transformed by the
265  // array-to-pointer implicit conversion, so check for its presence
266  // and redo the conversion to get a pointer.
267  if (First == ICK_Array_To_Pointer)
268    FromType = Context.getArrayDecayedType(FromType);
269
270  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
271    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
272      return ToPtrType->getPointeeType()->isVoidType();
273
274  return false;
275}
276
277/// Skip any implicit casts which could be either part of a narrowing conversion
278/// or after one in an implicit conversion.
279static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
280  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
281    switch (ICE->getCastKind()) {
282    case CK_NoOp:
283    case CK_IntegralCast:
284    case CK_IntegralToBoolean:
285    case CK_IntegralToFloating:
286    case CK_FloatingToIntegral:
287    case CK_FloatingToBoolean:
288    case CK_FloatingCast:
289      Converted = ICE->getSubExpr();
290      continue;
291
292    default:
293      return Converted;
294    }
295  }
296
297  return Converted;
298}
299
300/// Check if this standard conversion sequence represents a narrowing
301/// conversion, according to C++11 [dcl.init.list]p7.
302///
303/// \param Ctx  The AST context.
304/// \param Converted  The result of applying this standard conversion sequence.
305/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
306///        value of the expression prior to the narrowing conversion.
307/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
308///        type of the expression prior to the narrowing conversion.
309NarrowingKind
310StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
311                                             const Expr *Converted,
312                                             APValue &ConstantValue,
313                                             QualType &ConstantType) const {
314  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
315
316  // C++11 [dcl.init.list]p7:
317  //   A narrowing conversion is an implicit conversion ...
318  QualType FromType = getToType(0);
319  QualType ToType = getToType(1);
320  switch (Second) {
321  // -- from a floating-point type to an integer type, or
322  //
323  // -- from an integer type or unscoped enumeration type to a floating-point
324  //    type, except where the source is a constant expression and the actual
325  //    value after conversion will fit into the target type and will produce
326  //    the original value when converted back to the original type, or
327  case ICK_Floating_Integral:
328    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329      return NK_Type_Narrowing;
330    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331      llvm::APSInt IntConstantValue;
332      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
333      if (Initializer &&
334          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
335        // Convert the integer to the floating type.
336        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
337        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
338                                llvm::APFloat::rmNearestTiesToEven);
339        // And back.
340        llvm::APSInt ConvertedValue = IntConstantValue;
341        bool ignored;
342        Result.convertToInteger(ConvertedValue,
343                                llvm::APFloat::rmTowardZero, &ignored);
344        // If the resulting value is different, this was a narrowing conversion.
345        if (IntConstantValue != ConvertedValue) {
346          ConstantValue = APValue(IntConstantValue);
347          ConstantType = Initializer->getType();
348          return NK_Constant_Narrowing;
349        }
350      } else {
351        // Variables are always narrowings.
352        return NK_Variable_Narrowing;
353      }
354    }
355    return NK_Not_Narrowing;
356
357  // -- from long double to double or float, or from double to float, except
358  //    where the source is a constant expression and the actual value after
359  //    conversion is within the range of values that can be represented (even
360  //    if it cannot be represented exactly), or
361  case ICK_Floating_Conversion:
362    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
363        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
364      // FromType is larger than ToType.
365      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
366      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
367        // Constant!
368        assert(ConstantValue.isFloat());
369        llvm::APFloat FloatVal = ConstantValue.getFloat();
370        // Convert the source value into the target type.
371        bool ignored;
372        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
373          Ctx.getFloatTypeSemantics(ToType),
374          llvm::APFloat::rmNearestTiesToEven, &ignored);
375        // If there was no overflow, the source value is within the range of
376        // values that can be represented.
377        if (ConvertStatus & llvm::APFloat::opOverflow) {
378          ConstantType = Initializer->getType();
379          return NK_Constant_Narrowing;
380        }
381      } else {
382        return NK_Variable_Narrowing;
383      }
384    }
385    return NK_Not_Narrowing;
386
387  // -- from an integer type or unscoped enumeration type to an integer type
388  //    that cannot represent all the values of the original type, except where
389  //    the source is a constant expression and the actual value after
390  //    conversion will fit into the target type and will produce the original
391  //    value when converted back to the original type.
392  case ICK_Boolean_Conversion:  // Bools are integers too.
393    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
394      // Boolean conversions can be from pointers and pointers to members
395      // [conv.bool], and those aren't considered narrowing conversions.
396      return NK_Not_Narrowing;
397    }  // Otherwise, fall through to the integral case.
398  case ICK_Integral_Conversion: {
399    assert(FromType->isIntegralOrUnscopedEnumerationType());
400    assert(ToType->isIntegralOrUnscopedEnumerationType());
401    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
402    const unsigned FromWidth = Ctx.getIntWidth(FromType);
403    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
404    const unsigned ToWidth = Ctx.getIntWidth(ToType);
405
406    if (FromWidth > ToWidth ||
407        (FromWidth == ToWidth && FromSigned != ToSigned) ||
408        (FromSigned && !ToSigned)) {
409      // Not all values of FromType can be represented in ToType.
410      llvm::APSInt InitializerValue;
411      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
412      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
413        // Such conversions on variables are always narrowing.
414        return NK_Variable_Narrowing;
415      }
416      bool Narrowing = false;
417      if (FromWidth < ToWidth) {
418        // Negative -> unsigned is narrowing. Otherwise, more bits is never
419        // narrowing.
420        if (InitializerValue.isSigned() && InitializerValue.isNegative())
421          Narrowing = true;
422      } else {
423        // Add a bit to the InitializerValue so we don't have to worry about
424        // signed vs. unsigned comparisons.
425        InitializerValue = InitializerValue.extend(
426          InitializerValue.getBitWidth() + 1);
427        // Convert the initializer to and from the target width and signed-ness.
428        llvm::APSInt ConvertedValue = InitializerValue;
429        ConvertedValue = ConvertedValue.trunc(ToWidth);
430        ConvertedValue.setIsSigned(ToSigned);
431        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
432        ConvertedValue.setIsSigned(InitializerValue.isSigned());
433        // If the result is different, this was a narrowing conversion.
434        if (ConvertedValue != InitializerValue)
435          Narrowing = true;
436      }
437      if (Narrowing) {
438        ConstantType = Initializer->getType();
439        ConstantValue = APValue(InitializerValue);
440        return NK_Constant_Narrowing;
441      }
442    }
443    return NK_Not_Narrowing;
444  }
445
446  default:
447    // Other kinds of conversions are not narrowings.
448    return NK_Not_Narrowing;
449  }
450}
451
452/// DebugPrint - Print this standard conversion sequence to standard
453/// error. Useful for debugging overloading issues.
454void StandardConversionSequence::DebugPrint() const {
455  raw_ostream &OS = llvm::errs();
456  bool PrintedSomething = false;
457  if (First != ICK_Identity) {
458    OS << GetImplicitConversionName(First);
459    PrintedSomething = true;
460  }
461
462  if (Second != ICK_Identity) {
463    if (PrintedSomething) {
464      OS << " -> ";
465    }
466    OS << GetImplicitConversionName(Second);
467
468    if (CopyConstructor) {
469      OS << " (by copy constructor)";
470    } else if (DirectBinding) {
471      OS << " (direct reference binding)";
472    } else if (ReferenceBinding) {
473      OS << " (reference binding)";
474    }
475    PrintedSomething = true;
476  }
477
478  if (Third != ICK_Identity) {
479    if (PrintedSomething) {
480      OS << " -> ";
481    }
482    OS << GetImplicitConversionName(Third);
483    PrintedSomething = true;
484  }
485
486  if (!PrintedSomething) {
487    OS << "No conversions required";
488  }
489}
490
491/// DebugPrint - Print this user-defined conversion sequence to standard
492/// error. Useful for debugging overloading issues.
493void UserDefinedConversionSequence::DebugPrint() const {
494  raw_ostream &OS = llvm::errs();
495  if (Before.First || Before.Second || Before.Third) {
496    Before.DebugPrint();
497    OS << " -> ";
498  }
499  if (ConversionFunction)
500    OS << '\'' << *ConversionFunction << '\'';
501  else
502    OS << "aggregate initialization";
503  if (After.First || After.Second || After.Third) {
504    OS << " -> ";
505    After.DebugPrint();
506  }
507}
508
509/// DebugPrint - Print this implicit conversion sequence to standard
510/// error. Useful for debugging overloading issues.
511void ImplicitConversionSequence::DebugPrint() const {
512  raw_ostream &OS = llvm::errs();
513  if (isStdInitializerListElement())
514    OS << "Worst std::initializer_list element conversion: ";
515  switch (ConversionKind) {
516  case StandardConversion:
517    OS << "Standard conversion: ";
518    Standard.DebugPrint();
519    break;
520  case UserDefinedConversion:
521    OS << "User-defined conversion: ";
522    UserDefined.DebugPrint();
523    break;
524  case EllipsisConversion:
525    OS << "Ellipsis conversion";
526    break;
527  case AmbiguousConversion:
528    OS << "Ambiguous conversion";
529    break;
530  case BadConversion:
531    OS << "Bad conversion";
532    break;
533  }
534
535  OS << "\n";
536}
537
538void AmbiguousConversionSequence::construct() {
539  new (&conversions()) ConversionSet();
540}
541
542void AmbiguousConversionSequence::destruct() {
543  conversions().~ConversionSet();
544}
545
546void
547AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
548  FromTypePtr = O.FromTypePtr;
549  ToTypePtr = O.ToTypePtr;
550  new (&conversions()) ConversionSet(O.conversions());
551}
552
553namespace {
554  // Structure used by DeductionFailureInfo to store
555  // template argument information.
556  struct DFIArguments {
557    TemplateArgument FirstArg;
558    TemplateArgument SecondArg;
559  };
560  // Structure used by DeductionFailureInfo to store
561  // template parameter and template argument information.
562  struct DFIParamWithArguments : DFIArguments {
563    TemplateParameter Param;
564  };
565}
566
567/// \brief Convert from Sema's representation of template deduction information
568/// to the form used in overload-candidate information.
569DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
570                                              Sema::TemplateDeductionResult TDK,
571                                              TemplateDeductionInfo &Info) {
572  DeductionFailureInfo Result;
573  Result.Result = static_cast<unsigned>(TDK);
574  Result.HasDiagnostic = false;
575  Result.Data = 0;
576  switch (TDK) {
577  case Sema::TDK_Success:
578  case Sema::TDK_Invalid:
579  case Sema::TDK_InstantiationDepth:
580  case Sema::TDK_TooManyArguments:
581  case Sema::TDK_TooFewArguments:
582    break;
583
584  case Sema::TDK_Incomplete:
585  case Sema::TDK_InvalidExplicitArguments:
586    Result.Data = Info.Param.getOpaqueValue();
587    break;
588
589  case Sema::TDK_NonDeducedMismatch: {
590    // FIXME: Should allocate from normal heap so that we can free this later.
591    DFIArguments *Saved = new (Context) DFIArguments;
592    Saved->FirstArg = Info.FirstArg;
593    Saved->SecondArg = Info.SecondArg;
594    Result.Data = Saved;
595    break;
596  }
597
598  case Sema::TDK_Inconsistent:
599  case Sema::TDK_Underqualified: {
600    // FIXME: Should allocate from normal heap so that we can free this later.
601    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
602    Saved->Param = Info.Param;
603    Saved->FirstArg = Info.FirstArg;
604    Saved->SecondArg = Info.SecondArg;
605    Result.Data = Saved;
606    break;
607  }
608
609  case Sema::TDK_SubstitutionFailure:
610    Result.Data = Info.take();
611    if (Info.hasSFINAEDiagnostic()) {
612      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
613          SourceLocation(), PartialDiagnostic::NullDiagnostic());
614      Info.takeSFINAEDiagnostic(*Diag);
615      Result.HasDiagnostic = true;
616    }
617    break;
618
619  case Sema::TDK_FailedOverloadResolution:
620    Result.Data = Info.Expression;
621    break;
622
623  case Sema::TDK_MiscellaneousDeductionFailure:
624    break;
625  }
626
627  return Result;
628}
629
630void DeductionFailureInfo::Destroy() {
631  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
632  case Sema::TDK_Success:
633  case Sema::TDK_Invalid:
634  case Sema::TDK_InstantiationDepth:
635  case Sema::TDK_Incomplete:
636  case Sema::TDK_TooManyArguments:
637  case Sema::TDK_TooFewArguments:
638  case Sema::TDK_InvalidExplicitArguments:
639  case Sema::TDK_FailedOverloadResolution:
640    break;
641
642  case Sema::TDK_Inconsistent:
643  case Sema::TDK_Underqualified:
644  case Sema::TDK_NonDeducedMismatch:
645    // FIXME: Destroy the data?
646    Data = 0;
647    break;
648
649  case Sema::TDK_SubstitutionFailure:
650    // FIXME: Destroy the template argument list?
651    Data = 0;
652    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
653      Diag->~PartialDiagnosticAt();
654      HasDiagnostic = false;
655    }
656    break;
657
658  // Unhandled
659  case Sema::TDK_MiscellaneousDeductionFailure:
660    break;
661  }
662}
663
664PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
665  if (HasDiagnostic)
666    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
667  return 0;
668}
669
670TemplateParameter DeductionFailureInfo::getTemplateParameter() {
671  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
672  case Sema::TDK_Success:
673  case Sema::TDK_Invalid:
674  case Sema::TDK_InstantiationDepth:
675  case Sema::TDK_TooManyArguments:
676  case Sema::TDK_TooFewArguments:
677  case Sema::TDK_SubstitutionFailure:
678  case Sema::TDK_NonDeducedMismatch:
679  case Sema::TDK_FailedOverloadResolution:
680    return TemplateParameter();
681
682  case Sema::TDK_Incomplete:
683  case Sema::TDK_InvalidExplicitArguments:
684    return TemplateParameter::getFromOpaqueValue(Data);
685
686  case Sema::TDK_Inconsistent:
687  case Sema::TDK_Underqualified:
688    return static_cast<DFIParamWithArguments*>(Data)->Param;
689
690  // Unhandled
691  case Sema::TDK_MiscellaneousDeductionFailure:
692    break;
693  }
694
695  return TemplateParameter();
696}
697
698TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
699  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
700  case Sema::TDK_Success:
701  case Sema::TDK_Invalid:
702  case Sema::TDK_InstantiationDepth:
703  case Sema::TDK_TooManyArguments:
704  case Sema::TDK_TooFewArguments:
705  case Sema::TDK_Incomplete:
706  case Sema::TDK_InvalidExplicitArguments:
707  case Sema::TDK_Inconsistent:
708  case Sema::TDK_Underqualified:
709  case Sema::TDK_NonDeducedMismatch:
710  case Sema::TDK_FailedOverloadResolution:
711    return 0;
712
713  case Sema::TDK_SubstitutionFailure:
714    return static_cast<TemplateArgumentList*>(Data);
715
716  // Unhandled
717  case Sema::TDK_MiscellaneousDeductionFailure:
718    break;
719  }
720
721  return 0;
722}
723
724const TemplateArgument *DeductionFailureInfo::getFirstArg() {
725  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
726  case Sema::TDK_Success:
727  case Sema::TDK_Invalid:
728  case Sema::TDK_InstantiationDepth:
729  case Sema::TDK_Incomplete:
730  case Sema::TDK_TooManyArguments:
731  case Sema::TDK_TooFewArguments:
732  case Sema::TDK_InvalidExplicitArguments:
733  case Sema::TDK_SubstitutionFailure:
734  case Sema::TDK_FailedOverloadResolution:
735    return 0;
736
737  case Sema::TDK_Inconsistent:
738  case Sema::TDK_Underqualified:
739  case Sema::TDK_NonDeducedMismatch:
740    return &static_cast<DFIArguments*>(Data)->FirstArg;
741
742  // Unhandled
743  case Sema::TDK_MiscellaneousDeductionFailure:
744    break;
745  }
746
747  return 0;
748}
749
750const TemplateArgument *DeductionFailureInfo::getSecondArg() {
751  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
752  case Sema::TDK_Success:
753  case Sema::TDK_Invalid:
754  case Sema::TDK_InstantiationDepth:
755  case Sema::TDK_Incomplete:
756  case Sema::TDK_TooManyArguments:
757  case Sema::TDK_TooFewArguments:
758  case Sema::TDK_InvalidExplicitArguments:
759  case Sema::TDK_SubstitutionFailure:
760  case Sema::TDK_FailedOverloadResolution:
761    return 0;
762
763  case Sema::TDK_Inconsistent:
764  case Sema::TDK_Underqualified:
765  case Sema::TDK_NonDeducedMismatch:
766    return &static_cast<DFIArguments*>(Data)->SecondArg;
767
768  // Unhandled
769  case Sema::TDK_MiscellaneousDeductionFailure:
770    break;
771  }
772
773  return 0;
774}
775
776Expr *DeductionFailureInfo::getExpr() {
777  if (static_cast<Sema::TemplateDeductionResult>(Result) ==
778        Sema::TDK_FailedOverloadResolution)
779    return static_cast<Expr*>(Data);
780
781  return 0;
782}
783
784void OverloadCandidateSet::destroyCandidates() {
785  for (iterator i = begin(), e = end(); i != e; ++i) {
786    for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
787      i->Conversions[ii].~ImplicitConversionSequence();
788    if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
789      i->DeductionFailure.Destroy();
790  }
791}
792
793void OverloadCandidateSet::clear() {
794  destroyCandidates();
795  NumInlineSequences = 0;
796  Candidates.clear();
797  Functions.clear();
798}
799
800namespace {
801  class UnbridgedCastsSet {
802    struct Entry {
803      Expr **Addr;
804      Expr *Saved;
805    };
806    SmallVector<Entry, 2> Entries;
807
808  public:
809    void save(Sema &S, Expr *&E) {
810      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
811      Entry entry = { &E, E };
812      Entries.push_back(entry);
813      E = S.stripARCUnbridgedCast(E);
814    }
815
816    void restore() {
817      for (SmallVectorImpl<Entry>::iterator
818             i = Entries.begin(), e = Entries.end(); i != e; ++i)
819        *i->Addr = i->Saved;
820    }
821  };
822}
823
824/// checkPlaceholderForOverload - Do any interesting placeholder-like
825/// preprocessing on the given expression.
826///
827/// \param unbridgedCasts a collection to which to add unbridged casts;
828///   without this, they will be immediately diagnosed as errors
829///
830/// Return true on unrecoverable error.
831static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
832                                        UnbridgedCastsSet *unbridgedCasts = 0) {
833  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
834    // We can't handle overloaded expressions here because overload
835    // resolution might reasonably tweak them.
836    if (placeholder->getKind() == BuiltinType::Overload) return false;
837
838    // If the context potentially accepts unbridged ARC casts, strip
839    // the unbridged cast and add it to the collection for later restoration.
840    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
841        unbridgedCasts) {
842      unbridgedCasts->save(S, E);
843      return false;
844    }
845
846    // Go ahead and check everything else.
847    ExprResult result = S.CheckPlaceholderExpr(E);
848    if (result.isInvalid())
849      return true;
850
851    E = result.take();
852    return false;
853  }
854
855  // Nothing to do.
856  return false;
857}
858
859/// checkArgPlaceholdersForOverload - Check a set of call operands for
860/// placeholders.
861static bool checkArgPlaceholdersForOverload(Sema &S,
862                                            MultiExprArg Args,
863                                            UnbridgedCastsSet &unbridged) {
864  for (unsigned i = 0, e = Args.size(); i != e; ++i)
865    if (checkPlaceholderForOverload(S, Args[i], &unbridged))
866      return true;
867
868  return false;
869}
870
871// IsOverload - Determine whether the given New declaration is an
872// overload of the declarations in Old. This routine returns false if
873// New and Old cannot be overloaded, e.g., if New has the same
874// signature as some function in Old (C++ 1.3.10) or if the Old
875// declarations aren't functions (or function templates) at all. When
876// it does return false, MatchedDecl will point to the decl that New
877// cannot be overloaded with.  This decl may be a UsingShadowDecl on
878// top of the underlying declaration.
879//
880// Example: Given the following input:
881//
882//   void f(int, float); // #1
883//   void f(int, int); // #2
884//   int f(int, int); // #3
885//
886// When we process #1, there is no previous declaration of "f",
887// so IsOverload will not be used.
888//
889// When we process #2, Old contains only the FunctionDecl for #1.  By
890// comparing the parameter types, we see that #1 and #2 are overloaded
891// (since they have different signatures), so this routine returns
892// false; MatchedDecl is unchanged.
893//
894// When we process #3, Old is an overload set containing #1 and #2. We
895// compare the signatures of #3 to #1 (they're overloaded, so we do
896// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
897// identical (return types of functions are not part of the
898// signature), IsOverload returns false and MatchedDecl will be set to
899// point to the FunctionDecl for #2.
900//
901// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
902// into a class by a using declaration.  The rules for whether to hide
903// shadow declarations ignore some properties which otherwise figure
904// into a function template's signature.
905Sema::OverloadKind
906Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
907                    NamedDecl *&Match, bool NewIsUsingDecl) {
908  for (LookupResult::iterator I = Old.begin(), E = Old.end();
909         I != E; ++I) {
910    NamedDecl *OldD = *I;
911
912    bool OldIsUsingDecl = false;
913    if (isa<UsingShadowDecl>(OldD)) {
914      OldIsUsingDecl = true;
915
916      // We can always introduce two using declarations into the same
917      // context, even if they have identical signatures.
918      if (NewIsUsingDecl) continue;
919
920      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
921    }
922
923    // If either declaration was introduced by a using declaration,
924    // we'll need to use slightly different rules for matching.
925    // Essentially, these rules are the normal rules, except that
926    // function templates hide function templates with different
927    // return types or template parameter lists.
928    bool UseMemberUsingDeclRules =
929      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
930      !New->getFriendObjectKind();
931
932    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
933      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
934        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
935          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
936          continue;
937        }
938
939        Match = *I;
940        return Ovl_Match;
941      }
942    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
943      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
944        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
945          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
946          continue;
947        }
948
949        if (!shouldLinkPossiblyHiddenDecl(*I, New))
950          continue;
951
952        Match = *I;
953        return Ovl_Match;
954      }
955    } else if (isa<UsingDecl>(OldD)) {
956      // We can overload with these, which can show up when doing
957      // redeclaration checks for UsingDecls.
958      assert(Old.getLookupKind() == LookupUsingDeclName);
959    } else if (isa<TagDecl>(OldD)) {
960      // We can always overload with tags by hiding them.
961    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
962      // Optimistically assume that an unresolved using decl will
963      // overload; if it doesn't, we'll have to diagnose during
964      // template instantiation.
965    } else {
966      // (C++ 13p1):
967      //   Only function declarations can be overloaded; object and type
968      //   declarations cannot be overloaded.
969      Match = *I;
970      return Ovl_NonFunction;
971    }
972  }
973
974  return Ovl_Overload;
975}
976
977bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
978                      bool UseUsingDeclRules) {
979  // C++ [basic.start.main]p2: This function shall not be overloaded.
980  if (New->isMain())
981    return false;
982
983  // MSVCRT user defined entry points cannot be overloaded.
984  if (New->isMSVCRTEntryPoint())
985    return false;
986
987  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
988  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
989
990  // C++ [temp.fct]p2:
991  //   A function template can be overloaded with other function templates
992  //   and with normal (non-template) functions.
993  if ((OldTemplate == 0) != (NewTemplate == 0))
994    return true;
995
996  // Is the function New an overload of the function Old?
997  QualType OldQType = Context.getCanonicalType(Old->getType());
998  QualType NewQType = Context.getCanonicalType(New->getType());
999
1000  // Compare the signatures (C++ 1.3.10) of the two functions to
1001  // determine whether they are overloads. If we find any mismatch
1002  // in the signature, they are overloads.
1003
1004  // If either of these functions is a K&R-style function (no
1005  // prototype), then we consider them to have matching signatures.
1006  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1007      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1008    return false;
1009
1010  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1011  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
1012
1013  // The signature of a function includes the types of its
1014  // parameters (C++ 1.3.10), which includes the presence or absence
1015  // of the ellipsis; see C++ DR 357).
1016  if (OldQType != NewQType &&
1017      (OldType->getNumArgs() != NewType->getNumArgs() ||
1018       OldType->isVariadic() != NewType->isVariadic() ||
1019       !FunctionArgTypesAreEqual(OldType, NewType)))
1020    return true;
1021
1022  // C++ [temp.over.link]p4:
1023  //   The signature of a function template consists of its function
1024  //   signature, its return type and its template parameter list. The names
1025  //   of the template parameters are significant only for establishing the
1026  //   relationship between the template parameters and the rest of the
1027  //   signature.
1028  //
1029  // We check the return type and template parameter lists for function
1030  // templates first; the remaining checks follow.
1031  //
1032  // However, we don't consider either of these when deciding whether
1033  // a member introduced by a shadow declaration is hidden.
1034  if (!UseUsingDeclRules && NewTemplate &&
1035      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1036                                       OldTemplate->getTemplateParameters(),
1037                                       false, TPL_TemplateMatch) ||
1038       OldType->getResultType() != NewType->getResultType()))
1039    return true;
1040
1041  // If the function is a class member, its signature includes the
1042  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1043  //
1044  // As part of this, also check whether one of the member functions
1045  // is static, in which case they are not overloads (C++
1046  // 13.1p2). While not part of the definition of the signature,
1047  // this check is important to determine whether these functions
1048  // can be overloaded.
1049  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1050  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1051  if (OldMethod && NewMethod &&
1052      !OldMethod->isStatic() && !NewMethod->isStatic()) {
1053    if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1054      if (!UseUsingDeclRules &&
1055          (OldMethod->getRefQualifier() == RQ_None ||
1056           NewMethod->getRefQualifier() == RQ_None)) {
1057        // C++0x [over.load]p2:
1058        //   - Member function declarations with the same name and the same
1059        //     parameter-type-list as well as member function template
1060        //     declarations with the same name, the same parameter-type-list, and
1061        //     the same template parameter lists cannot be overloaded if any of
1062        //     them, but not all, have a ref-qualifier (8.3.5).
1063        Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1064          << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1065        Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1066      }
1067      return true;
1068    }
1069
1070    // We may not have applied the implicit const for a constexpr member
1071    // function yet (because we haven't yet resolved whether this is a static
1072    // or non-static member function). Add it now, on the assumption that this
1073    // is a redeclaration of OldMethod.
1074    unsigned NewQuals = NewMethod->getTypeQualifiers();
1075    if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
1076        !isa<CXXConstructorDecl>(NewMethod))
1077      NewQuals |= Qualifiers::Const;
1078    if (OldMethod->getTypeQualifiers() != NewQuals)
1079      return true;
1080  }
1081
1082  // The signatures match; this is not an overload.
1083  return false;
1084}
1085
1086/// \brief Checks availability of the function depending on the current
1087/// function context. Inside an unavailable function, unavailability is ignored.
1088///
1089/// \returns true if \arg FD is unavailable and current context is inside
1090/// an available function, false otherwise.
1091bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1092  return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1093}
1094
1095/// \brief Tries a user-defined conversion from From to ToType.
1096///
1097/// Produces an implicit conversion sequence for when a standard conversion
1098/// is not an option. See TryImplicitConversion for more information.
1099static ImplicitConversionSequence
1100TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1101                         bool SuppressUserConversions,
1102                         bool AllowExplicit,
1103                         bool InOverloadResolution,
1104                         bool CStyle,
1105                         bool AllowObjCWritebackConversion) {
1106  ImplicitConversionSequence ICS;
1107
1108  if (SuppressUserConversions) {
1109    // We're not in the case above, so there is no conversion that
1110    // we can perform.
1111    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1112    return ICS;
1113  }
1114
1115  // Attempt user-defined conversion.
1116  OverloadCandidateSet Conversions(From->getExprLoc());
1117  OverloadingResult UserDefResult
1118    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1119                              AllowExplicit);
1120
1121  if (UserDefResult == OR_Success) {
1122    ICS.setUserDefined();
1123    // C++ [over.ics.user]p4:
1124    //   A conversion of an expression of class type to the same class
1125    //   type is given Exact Match rank, and a conversion of an
1126    //   expression of class type to a base class of that type is
1127    //   given Conversion rank, in spite of the fact that a copy
1128    //   constructor (i.e., a user-defined conversion function) is
1129    //   called for those cases.
1130    if (CXXConstructorDecl *Constructor
1131          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1132      QualType FromCanon
1133        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1134      QualType ToCanon
1135        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1136      if (Constructor->isCopyConstructor() &&
1137          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1138        // Turn this into a "standard" conversion sequence, so that it
1139        // gets ranked with standard conversion sequences.
1140        ICS.setStandard();
1141        ICS.Standard.setAsIdentityConversion();
1142        ICS.Standard.setFromType(From->getType());
1143        ICS.Standard.setAllToTypes(ToType);
1144        ICS.Standard.CopyConstructor = Constructor;
1145        if (ToCanon != FromCanon)
1146          ICS.Standard.Second = ICK_Derived_To_Base;
1147      }
1148    }
1149
1150    // C++ [over.best.ics]p4:
1151    //   However, when considering the argument of a user-defined
1152    //   conversion function that is a candidate by 13.3.1.3 when
1153    //   invoked for the copying of the temporary in the second step
1154    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1155    //   13.3.1.6 in all cases, only standard conversion sequences and
1156    //   ellipsis conversion sequences are allowed.
1157    if (SuppressUserConversions && ICS.isUserDefined()) {
1158      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1159    }
1160  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1161    ICS.setAmbiguous();
1162    ICS.Ambiguous.setFromType(From->getType());
1163    ICS.Ambiguous.setToType(ToType);
1164    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1165         Cand != Conversions.end(); ++Cand)
1166      if (Cand->Viable)
1167        ICS.Ambiguous.addConversion(Cand->Function);
1168  } else {
1169    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1170  }
1171
1172  return ICS;
1173}
1174
1175/// TryImplicitConversion - Attempt to perform an implicit conversion
1176/// from the given expression (Expr) to the given type (ToType). This
1177/// function returns an implicit conversion sequence that can be used
1178/// to perform the initialization. Given
1179///
1180///   void f(float f);
1181///   void g(int i) { f(i); }
1182///
1183/// this routine would produce an implicit conversion sequence to
1184/// describe the initialization of f from i, which will be a standard
1185/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1186/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1187//
1188/// Note that this routine only determines how the conversion can be
1189/// performed; it does not actually perform the conversion. As such,
1190/// it will not produce any diagnostics if no conversion is available,
1191/// but will instead return an implicit conversion sequence of kind
1192/// "BadConversion".
1193///
1194/// If @p SuppressUserConversions, then user-defined conversions are
1195/// not permitted.
1196/// If @p AllowExplicit, then explicit user-defined conversions are
1197/// permitted.
1198///
1199/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1200/// writeback conversion, which allows __autoreleasing id* parameters to
1201/// be initialized with __strong id* or __weak id* arguments.
1202static ImplicitConversionSequence
1203TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1204                      bool SuppressUserConversions,
1205                      bool AllowExplicit,
1206                      bool InOverloadResolution,
1207                      bool CStyle,
1208                      bool AllowObjCWritebackConversion) {
1209  ImplicitConversionSequence ICS;
1210  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1211                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1212    ICS.setStandard();
1213    return ICS;
1214  }
1215
1216  if (!S.getLangOpts().CPlusPlus) {
1217    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1218    return ICS;
1219  }
1220
1221  // C++ [over.ics.user]p4:
1222  //   A conversion of an expression of class type to the same class
1223  //   type is given Exact Match rank, and a conversion of an
1224  //   expression of class type to a base class of that type is
1225  //   given Conversion rank, in spite of the fact that a copy/move
1226  //   constructor (i.e., a user-defined conversion function) is
1227  //   called for those cases.
1228  QualType FromType = From->getType();
1229  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1230      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1231       S.IsDerivedFrom(FromType, ToType))) {
1232    ICS.setStandard();
1233    ICS.Standard.setAsIdentityConversion();
1234    ICS.Standard.setFromType(FromType);
1235    ICS.Standard.setAllToTypes(ToType);
1236
1237    // We don't actually check at this point whether there is a valid
1238    // copy/move constructor, since overloading just assumes that it
1239    // exists. When we actually perform initialization, we'll find the
1240    // appropriate constructor to copy the returned object, if needed.
1241    ICS.Standard.CopyConstructor = 0;
1242
1243    // Determine whether this is considered a derived-to-base conversion.
1244    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1245      ICS.Standard.Second = ICK_Derived_To_Base;
1246
1247    return ICS;
1248  }
1249
1250  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1251                                  AllowExplicit, InOverloadResolution, CStyle,
1252                                  AllowObjCWritebackConversion);
1253}
1254
1255ImplicitConversionSequence
1256Sema::TryImplicitConversion(Expr *From, QualType ToType,
1257                            bool SuppressUserConversions,
1258                            bool AllowExplicit,
1259                            bool InOverloadResolution,
1260                            bool CStyle,
1261                            bool AllowObjCWritebackConversion) {
1262  return clang::TryImplicitConversion(*this, From, ToType,
1263                                      SuppressUserConversions, AllowExplicit,
1264                                      InOverloadResolution, CStyle,
1265                                      AllowObjCWritebackConversion);
1266}
1267
1268/// PerformImplicitConversion - Perform an implicit conversion of the
1269/// expression From to the type ToType. Returns the
1270/// converted expression. Flavor is the kind of conversion we're
1271/// performing, used in the error message. If @p AllowExplicit,
1272/// explicit user-defined conversions are permitted.
1273ExprResult
1274Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1275                                AssignmentAction Action, bool AllowExplicit) {
1276  ImplicitConversionSequence ICS;
1277  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1278}
1279
1280ExprResult
1281Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1282                                AssignmentAction Action, bool AllowExplicit,
1283                                ImplicitConversionSequence& ICS) {
1284  if (checkPlaceholderForOverload(*this, From))
1285    return ExprError();
1286
1287  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1288  bool AllowObjCWritebackConversion
1289    = getLangOpts().ObjCAutoRefCount &&
1290      (Action == AA_Passing || Action == AA_Sending);
1291
1292  ICS = clang::TryImplicitConversion(*this, From, ToType,
1293                                     /*SuppressUserConversions=*/false,
1294                                     AllowExplicit,
1295                                     /*InOverloadResolution=*/false,
1296                                     /*CStyle=*/false,
1297                                     AllowObjCWritebackConversion);
1298  return PerformImplicitConversion(From, ToType, ICS, Action);
1299}
1300
1301/// \brief Determine whether the conversion from FromType to ToType is a valid
1302/// conversion that strips "noreturn" off the nested function type.
1303bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1304                                QualType &ResultTy) {
1305  if (Context.hasSameUnqualifiedType(FromType, ToType))
1306    return false;
1307
1308  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1309  // where F adds one of the following at most once:
1310  //   - a pointer
1311  //   - a member pointer
1312  //   - a block pointer
1313  CanQualType CanTo = Context.getCanonicalType(ToType);
1314  CanQualType CanFrom = Context.getCanonicalType(FromType);
1315  Type::TypeClass TyClass = CanTo->getTypeClass();
1316  if (TyClass != CanFrom->getTypeClass()) return false;
1317  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1318    if (TyClass == Type::Pointer) {
1319      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1320      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1321    } else if (TyClass == Type::BlockPointer) {
1322      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1323      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1324    } else if (TyClass == Type::MemberPointer) {
1325      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1326      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1327    } else {
1328      return false;
1329    }
1330
1331    TyClass = CanTo->getTypeClass();
1332    if (TyClass != CanFrom->getTypeClass()) return false;
1333    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1334      return false;
1335  }
1336
1337  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1338  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1339  if (!EInfo.getNoReturn()) return false;
1340
1341  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1342  assert(QualType(FromFn, 0).isCanonical());
1343  if (QualType(FromFn, 0) != CanTo) return false;
1344
1345  ResultTy = ToType;
1346  return true;
1347}
1348
1349/// \brief Determine whether the conversion from FromType to ToType is a valid
1350/// vector conversion.
1351///
1352/// \param ICK Will be set to the vector conversion kind, if this is a vector
1353/// conversion.
1354static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1355                               QualType ToType, ImplicitConversionKind &ICK) {
1356  // We need at least one of these types to be a vector type to have a vector
1357  // conversion.
1358  if (!ToType->isVectorType() && !FromType->isVectorType())
1359    return false;
1360
1361  // Identical types require no conversions.
1362  if (Context.hasSameUnqualifiedType(FromType, ToType))
1363    return false;
1364
1365  // There are no conversions between extended vector types, only identity.
1366  if (ToType->isExtVectorType()) {
1367    // There are no conversions between extended vector types other than the
1368    // identity conversion.
1369    if (FromType->isExtVectorType())
1370      return false;
1371
1372    // Vector splat from any arithmetic type to a vector.
1373    if (FromType->isArithmeticType()) {
1374      ICK = ICK_Vector_Splat;
1375      return true;
1376    }
1377  }
1378
1379  // We can perform the conversion between vector types in the following cases:
1380  // 1)vector types are equivalent AltiVec and GCC vector types
1381  // 2)lax vector conversions are permitted and the vector types are of the
1382  //   same size
1383  if (ToType->isVectorType() && FromType->isVectorType()) {
1384    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1385        (Context.getLangOpts().LaxVectorConversions &&
1386         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1387      ICK = ICK_Vector_Conversion;
1388      return true;
1389    }
1390  }
1391
1392  return false;
1393}
1394
1395static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1396                                bool InOverloadResolution,
1397                                StandardConversionSequence &SCS,
1398                                bool CStyle);
1399
1400/// IsStandardConversion - Determines whether there is a standard
1401/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1402/// expression From to the type ToType. Standard conversion sequences
1403/// only consider non-class types; for conversions that involve class
1404/// types, use TryImplicitConversion. If a conversion exists, SCS will
1405/// contain the standard conversion sequence required to perform this
1406/// conversion and this routine will return true. Otherwise, this
1407/// routine will return false and the value of SCS is unspecified.
1408static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1409                                 bool InOverloadResolution,
1410                                 StandardConversionSequence &SCS,
1411                                 bool CStyle,
1412                                 bool AllowObjCWritebackConversion) {
1413  QualType FromType = From->getType();
1414
1415  // Standard conversions (C++ [conv])
1416  SCS.setAsIdentityConversion();
1417  SCS.DeprecatedStringLiteralToCharPtr = false;
1418  SCS.IncompatibleObjC = false;
1419  SCS.setFromType(FromType);
1420  SCS.CopyConstructor = 0;
1421
1422  // There are no standard conversions for class types in C++, so
1423  // abort early. When overloading in C, however, we do permit
1424  if (FromType->isRecordType() || ToType->isRecordType()) {
1425    if (S.getLangOpts().CPlusPlus)
1426      return false;
1427
1428    // When we're overloading in C, we allow, as standard conversions,
1429  }
1430
1431  // The first conversion can be an lvalue-to-rvalue conversion,
1432  // array-to-pointer conversion, or function-to-pointer conversion
1433  // (C++ 4p1).
1434
1435  if (FromType == S.Context.OverloadTy) {
1436    DeclAccessPair AccessPair;
1437    if (FunctionDecl *Fn
1438          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1439                                                 AccessPair)) {
1440      // We were able to resolve the address of the overloaded function,
1441      // so we can convert to the type of that function.
1442      FromType = Fn->getType();
1443
1444      // we can sometimes resolve &foo<int> regardless of ToType, so check
1445      // if the type matches (identity) or we are converting to bool
1446      if (!S.Context.hasSameUnqualifiedType(
1447                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1448        QualType resultTy;
1449        // if the function type matches except for [[noreturn]], it's ok
1450        if (!S.IsNoReturnConversion(FromType,
1451              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1452          // otherwise, only a boolean conversion is standard
1453          if (!ToType->isBooleanType())
1454            return false;
1455      }
1456
1457      // Check if the "from" expression is taking the address of an overloaded
1458      // function and recompute the FromType accordingly. Take advantage of the
1459      // fact that non-static member functions *must* have such an address-of
1460      // expression.
1461      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1462      if (Method && !Method->isStatic()) {
1463        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1464               "Non-unary operator on non-static member address");
1465        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1466               == UO_AddrOf &&
1467               "Non-address-of operator on non-static member address");
1468        const Type *ClassType
1469          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1470        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1471      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1472        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1473               UO_AddrOf &&
1474               "Non-address-of operator for overloaded function expression");
1475        FromType = S.Context.getPointerType(FromType);
1476      }
1477
1478      // Check that we've computed the proper type after overload resolution.
1479      assert(S.Context.hasSameType(
1480        FromType,
1481        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1482    } else {
1483      return false;
1484    }
1485  }
1486  // Lvalue-to-rvalue conversion (C++11 4.1):
1487  //   A glvalue (3.10) of a non-function, non-array type T can
1488  //   be converted to a prvalue.
1489  bool argIsLValue = From->isGLValue();
1490  if (argIsLValue &&
1491      !FromType->isFunctionType() && !FromType->isArrayType() &&
1492      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1493    SCS.First = ICK_Lvalue_To_Rvalue;
1494
1495    // C11 6.3.2.1p2:
1496    //   ... if the lvalue has atomic type, the value has the non-atomic version
1497    //   of the type of the lvalue ...
1498    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1499      FromType = Atomic->getValueType();
1500
1501    // If T is a non-class type, the type of the rvalue is the
1502    // cv-unqualified version of T. Otherwise, the type of the rvalue
1503    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1504    // just strip the qualifiers because they don't matter.
1505    FromType = FromType.getUnqualifiedType();
1506  } else if (FromType->isArrayType()) {
1507    // Array-to-pointer conversion (C++ 4.2)
1508    SCS.First = ICK_Array_To_Pointer;
1509
1510    // An lvalue or rvalue of type "array of N T" or "array of unknown
1511    // bound of T" can be converted to an rvalue of type "pointer to
1512    // T" (C++ 4.2p1).
1513    FromType = S.Context.getArrayDecayedType(FromType);
1514
1515    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1516      // This conversion is deprecated. (C++ D.4).
1517      SCS.DeprecatedStringLiteralToCharPtr = true;
1518
1519      // For the purpose of ranking in overload resolution
1520      // (13.3.3.1.1), this conversion is considered an
1521      // array-to-pointer conversion followed by a qualification
1522      // conversion (4.4). (C++ 4.2p2)
1523      SCS.Second = ICK_Identity;
1524      SCS.Third = ICK_Qualification;
1525      SCS.QualificationIncludesObjCLifetime = false;
1526      SCS.setAllToTypes(FromType);
1527      return true;
1528    }
1529  } else if (FromType->isFunctionType() && argIsLValue) {
1530    // Function-to-pointer conversion (C++ 4.3).
1531    SCS.First = ICK_Function_To_Pointer;
1532
1533    // An lvalue of function type T can be converted to an rvalue of
1534    // type "pointer to T." The result is a pointer to the
1535    // function. (C++ 4.3p1).
1536    FromType = S.Context.getPointerType(FromType);
1537  } else {
1538    // We don't require any conversions for the first step.
1539    SCS.First = ICK_Identity;
1540  }
1541  SCS.setToType(0, FromType);
1542
1543  // The second conversion can be an integral promotion, floating
1544  // point promotion, integral conversion, floating point conversion,
1545  // floating-integral conversion, pointer conversion,
1546  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1547  // For overloading in C, this can also be a "compatible-type"
1548  // conversion.
1549  bool IncompatibleObjC = false;
1550  ImplicitConversionKind SecondICK = ICK_Identity;
1551  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1552    // The unqualified versions of the types are the same: there's no
1553    // conversion to do.
1554    SCS.Second = ICK_Identity;
1555  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1556    // Integral promotion (C++ 4.5).
1557    SCS.Second = ICK_Integral_Promotion;
1558    FromType = ToType.getUnqualifiedType();
1559  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1560    // Floating point promotion (C++ 4.6).
1561    SCS.Second = ICK_Floating_Promotion;
1562    FromType = ToType.getUnqualifiedType();
1563  } else if (S.IsComplexPromotion(FromType, ToType)) {
1564    // Complex promotion (Clang extension)
1565    SCS.Second = ICK_Complex_Promotion;
1566    FromType = ToType.getUnqualifiedType();
1567  } else if (ToType->isBooleanType() &&
1568             (FromType->isArithmeticType() ||
1569              FromType->isAnyPointerType() ||
1570              FromType->isBlockPointerType() ||
1571              FromType->isMemberPointerType() ||
1572              FromType->isNullPtrType())) {
1573    // Boolean conversions (C++ 4.12).
1574    SCS.Second = ICK_Boolean_Conversion;
1575    FromType = S.Context.BoolTy;
1576  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1577             ToType->isIntegralType(S.Context)) {
1578    // Integral conversions (C++ 4.7).
1579    SCS.Second = ICK_Integral_Conversion;
1580    FromType = ToType.getUnqualifiedType();
1581  } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1582    // Complex conversions (C99 6.3.1.6)
1583    SCS.Second = ICK_Complex_Conversion;
1584    FromType = ToType.getUnqualifiedType();
1585  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1586             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1587    // Complex-real conversions (C99 6.3.1.7)
1588    SCS.Second = ICK_Complex_Real;
1589    FromType = ToType.getUnqualifiedType();
1590  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1591    // Floating point conversions (C++ 4.8).
1592    SCS.Second = ICK_Floating_Conversion;
1593    FromType = ToType.getUnqualifiedType();
1594  } else if ((FromType->isRealFloatingType() &&
1595              ToType->isIntegralType(S.Context)) ||
1596             (FromType->isIntegralOrUnscopedEnumerationType() &&
1597              ToType->isRealFloatingType())) {
1598    // Floating-integral conversions (C++ 4.9).
1599    SCS.Second = ICK_Floating_Integral;
1600    FromType = ToType.getUnqualifiedType();
1601  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1602    SCS.Second = ICK_Block_Pointer_Conversion;
1603  } else if (AllowObjCWritebackConversion &&
1604             S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1605    SCS.Second = ICK_Writeback_Conversion;
1606  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1607                                   FromType, IncompatibleObjC)) {
1608    // Pointer conversions (C++ 4.10).
1609    SCS.Second = ICK_Pointer_Conversion;
1610    SCS.IncompatibleObjC = IncompatibleObjC;
1611    FromType = FromType.getUnqualifiedType();
1612  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1613                                         InOverloadResolution, FromType)) {
1614    // Pointer to member conversions (4.11).
1615    SCS.Second = ICK_Pointer_Member;
1616  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1617    SCS.Second = SecondICK;
1618    FromType = ToType.getUnqualifiedType();
1619  } else if (!S.getLangOpts().CPlusPlus &&
1620             S.Context.typesAreCompatible(ToType, FromType)) {
1621    // Compatible conversions (Clang extension for C function overloading)
1622    SCS.Second = ICK_Compatible_Conversion;
1623    FromType = ToType.getUnqualifiedType();
1624  } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1625    // Treat a conversion that strips "noreturn" as an identity conversion.
1626    SCS.Second = ICK_NoReturn_Adjustment;
1627  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1628                                             InOverloadResolution,
1629                                             SCS, CStyle)) {
1630    SCS.Second = ICK_TransparentUnionConversion;
1631    FromType = ToType;
1632  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1633                                 CStyle)) {
1634    // tryAtomicConversion has updated the standard conversion sequence
1635    // appropriately.
1636    return true;
1637  } else if (ToType->isEventT() &&
1638             From->isIntegerConstantExpr(S.getASTContext()) &&
1639             (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1640    SCS.Second = ICK_Zero_Event_Conversion;
1641    FromType = ToType;
1642  } else {
1643    // No second conversion required.
1644    SCS.Second = ICK_Identity;
1645  }
1646  SCS.setToType(1, FromType);
1647
1648  QualType CanonFrom;
1649  QualType CanonTo;
1650  // The third conversion can be a qualification conversion (C++ 4p1).
1651  bool ObjCLifetimeConversion;
1652  if (S.IsQualificationConversion(FromType, ToType, CStyle,
1653                                  ObjCLifetimeConversion)) {
1654    SCS.Third = ICK_Qualification;
1655    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1656    FromType = ToType;
1657    CanonFrom = S.Context.getCanonicalType(FromType);
1658    CanonTo = S.Context.getCanonicalType(ToType);
1659  } else {
1660    // No conversion required
1661    SCS.Third = ICK_Identity;
1662
1663    // C++ [over.best.ics]p6:
1664    //   [...] Any difference in top-level cv-qualification is
1665    //   subsumed by the initialization itself and does not constitute
1666    //   a conversion. [...]
1667    CanonFrom = S.Context.getCanonicalType(FromType);
1668    CanonTo = S.Context.getCanonicalType(ToType);
1669    if (CanonFrom.getLocalUnqualifiedType()
1670                                       == CanonTo.getLocalUnqualifiedType() &&
1671        CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1672      FromType = ToType;
1673      CanonFrom = CanonTo;
1674    }
1675  }
1676  SCS.setToType(2, FromType);
1677
1678  // If we have not converted the argument type to the parameter type,
1679  // this is a bad conversion sequence.
1680  if (CanonFrom != CanonTo)
1681    return false;
1682
1683  return true;
1684}
1685
1686static bool
1687IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1688                                     QualType &ToType,
1689                                     bool InOverloadResolution,
1690                                     StandardConversionSequence &SCS,
1691                                     bool CStyle) {
1692
1693  const RecordType *UT = ToType->getAsUnionType();
1694  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1695    return false;
1696  // The field to initialize within the transparent union.
1697  RecordDecl *UD = UT->getDecl();
1698  // It's compatible if the expression matches any of the fields.
1699  for (RecordDecl::field_iterator it = UD->field_begin(),
1700       itend = UD->field_end();
1701       it != itend; ++it) {
1702    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1703                             CStyle, /*ObjCWritebackConversion=*/false)) {
1704      ToType = it->getType();
1705      return true;
1706    }
1707  }
1708  return false;
1709}
1710
1711/// IsIntegralPromotion - Determines whether the conversion from the
1712/// expression From (whose potentially-adjusted type is FromType) to
1713/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1714/// sets PromotedType to the promoted type.
1715bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1716  const BuiltinType *To = ToType->getAs<BuiltinType>();
1717  // All integers are built-in.
1718  if (!To) {
1719    return false;
1720  }
1721
1722  // An rvalue of type char, signed char, unsigned char, short int, or
1723  // unsigned short int can be converted to an rvalue of type int if
1724  // int can represent all the values of the source type; otherwise,
1725  // the source rvalue can be converted to an rvalue of type unsigned
1726  // int (C++ 4.5p1).
1727  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1728      !FromType->isEnumeralType()) {
1729    if (// We can promote any signed, promotable integer type to an int
1730        (FromType->isSignedIntegerType() ||
1731         // We can promote any unsigned integer type whose size is
1732         // less than int to an int.
1733         (!FromType->isSignedIntegerType() &&
1734          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1735      return To->getKind() == BuiltinType::Int;
1736    }
1737
1738    return To->getKind() == BuiltinType::UInt;
1739  }
1740
1741  // C++11 [conv.prom]p3:
1742  //   A prvalue of an unscoped enumeration type whose underlying type is not
1743  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1744  //   following types that can represent all the values of the enumeration
1745  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1746  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1747  //   long long int. If none of the types in that list can represent all the
1748  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1749  //   type can be converted to an rvalue a prvalue of the extended integer type
1750  //   with lowest integer conversion rank (4.13) greater than the rank of long
1751  //   long in which all the values of the enumeration can be represented. If
1752  //   there are two such extended types, the signed one is chosen.
1753  // C++11 [conv.prom]p4:
1754  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1755  //   can be converted to a prvalue of its underlying type. Moreover, if
1756  //   integral promotion can be applied to its underlying type, a prvalue of an
1757  //   unscoped enumeration type whose underlying type is fixed can also be
1758  //   converted to a prvalue of the promoted underlying type.
1759  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1760    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1761    // provided for a scoped enumeration.
1762    if (FromEnumType->getDecl()->isScoped())
1763      return false;
1764
1765    // We can perform an integral promotion to the underlying type of the enum,
1766    // even if that's not the promoted type.
1767    if (FromEnumType->getDecl()->isFixed()) {
1768      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1769      return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1770             IsIntegralPromotion(From, Underlying, ToType);
1771    }
1772
1773    // We have already pre-calculated the promotion type, so this is trivial.
1774    if (ToType->isIntegerType() &&
1775        !RequireCompleteType(From->getLocStart(), FromType, 0))
1776      return Context.hasSameUnqualifiedType(ToType,
1777                                FromEnumType->getDecl()->getPromotionType());
1778  }
1779
1780  // C++0x [conv.prom]p2:
1781  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1782  //   to an rvalue a prvalue of the first of the following types that can
1783  //   represent all the values of its underlying type: int, unsigned int,
1784  //   long int, unsigned long int, long long int, or unsigned long long int.
1785  //   If none of the types in that list can represent all the values of its
1786  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1787  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1788  //   type.
1789  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1790      ToType->isIntegerType()) {
1791    // Determine whether the type we're converting from is signed or
1792    // unsigned.
1793    bool FromIsSigned = FromType->isSignedIntegerType();
1794    uint64_t FromSize = Context.getTypeSize(FromType);
1795
1796    // The types we'll try to promote to, in the appropriate
1797    // order. Try each of these types.
1798    QualType PromoteTypes[6] = {
1799      Context.IntTy, Context.UnsignedIntTy,
1800      Context.LongTy, Context.UnsignedLongTy ,
1801      Context.LongLongTy, Context.UnsignedLongLongTy
1802    };
1803    for (int Idx = 0; Idx < 6; ++Idx) {
1804      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1805      if (FromSize < ToSize ||
1806          (FromSize == ToSize &&
1807           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1808        // We found the type that we can promote to. If this is the
1809        // type we wanted, we have a promotion. Otherwise, no
1810        // promotion.
1811        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1812      }
1813    }
1814  }
1815
1816  // An rvalue for an integral bit-field (9.6) can be converted to an
1817  // rvalue of type int if int can represent all the values of the
1818  // bit-field; otherwise, it can be converted to unsigned int if
1819  // unsigned int can represent all the values of the bit-field. If
1820  // the bit-field is larger yet, no integral promotion applies to
1821  // it. If the bit-field has an enumerated type, it is treated as any
1822  // other value of that type for promotion purposes (C++ 4.5p3).
1823  // FIXME: We should delay checking of bit-fields until we actually perform the
1824  // conversion.
1825  using llvm::APSInt;
1826  if (From)
1827    if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1828      APSInt BitWidth;
1829      if (FromType->isIntegralType(Context) &&
1830          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1831        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1832        ToSize = Context.getTypeSize(ToType);
1833
1834        // Are we promoting to an int from a bitfield that fits in an int?
1835        if (BitWidth < ToSize ||
1836            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1837          return To->getKind() == BuiltinType::Int;
1838        }
1839
1840        // Are we promoting to an unsigned int from an unsigned bitfield
1841        // that fits into an unsigned int?
1842        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1843          return To->getKind() == BuiltinType::UInt;
1844        }
1845
1846        return false;
1847      }
1848    }
1849
1850  // An rvalue of type bool can be converted to an rvalue of type int,
1851  // with false becoming zero and true becoming one (C++ 4.5p4).
1852  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1853    return true;
1854  }
1855
1856  return false;
1857}
1858
1859/// IsFloatingPointPromotion - Determines whether the conversion from
1860/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1861/// returns true and sets PromotedType to the promoted type.
1862bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1863  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1864    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1865      /// An rvalue of type float can be converted to an rvalue of type
1866      /// double. (C++ 4.6p1).
1867      if (FromBuiltin->getKind() == BuiltinType::Float &&
1868          ToBuiltin->getKind() == BuiltinType::Double)
1869        return true;
1870
1871      // C99 6.3.1.5p1:
1872      //   When a float is promoted to double or long double, or a
1873      //   double is promoted to long double [...].
1874      if (!getLangOpts().CPlusPlus &&
1875          (FromBuiltin->getKind() == BuiltinType::Float ||
1876           FromBuiltin->getKind() == BuiltinType::Double) &&
1877          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1878        return true;
1879
1880      // Half can be promoted to float.
1881      if (!getLangOpts().NativeHalfType &&
1882           FromBuiltin->getKind() == BuiltinType::Half &&
1883          ToBuiltin->getKind() == BuiltinType::Float)
1884        return true;
1885    }
1886
1887  return false;
1888}
1889
1890/// \brief Determine if a conversion is a complex promotion.
1891///
1892/// A complex promotion is defined as a complex -> complex conversion
1893/// where the conversion between the underlying real types is a
1894/// floating-point or integral promotion.
1895bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1896  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1897  if (!FromComplex)
1898    return false;
1899
1900  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1901  if (!ToComplex)
1902    return false;
1903
1904  return IsFloatingPointPromotion(FromComplex->getElementType(),
1905                                  ToComplex->getElementType()) ||
1906    IsIntegralPromotion(0, FromComplex->getElementType(),
1907                        ToComplex->getElementType());
1908}
1909
1910/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1911/// the pointer type FromPtr to a pointer to type ToPointee, with the
1912/// same type qualifiers as FromPtr has on its pointee type. ToType,
1913/// if non-empty, will be a pointer to ToType that may or may not have
1914/// the right set of qualifiers on its pointee.
1915///
1916static QualType
1917BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1918                                   QualType ToPointee, QualType ToType,
1919                                   ASTContext &Context,
1920                                   bool StripObjCLifetime = false) {
1921  assert((FromPtr->getTypeClass() == Type::Pointer ||
1922          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1923         "Invalid similarly-qualified pointer type");
1924
1925  /// Conversions to 'id' subsume cv-qualifier conversions.
1926  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1927    return ToType.getUnqualifiedType();
1928
1929  QualType CanonFromPointee
1930    = Context.getCanonicalType(FromPtr->getPointeeType());
1931  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1932  Qualifiers Quals = CanonFromPointee.getQualifiers();
1933
1934  if (StripObjCLifetime)
1935    Quals.removeObjCLifetime();
1936
1937  // Exact qualifier match -> return the pointer type we're converting to.
1938  if (CanonToPointee.getLocalQualifiers() == Quals) {
1939    // ToType is exactly what we need. Return it.
1940    if (!ToType.isNull())
1941      return ToType.getUnqualifiedType();
1942
1943    // Build a pointer to ToPointee. It has the right qualifiers
1944    // already.
1945    if (isa<ObjCObjectPointerType>(ToType))
1946      return Context.getObjCObjectPointerType(ToPointee);
1947    return Context.getPointerType(ToPointee);
1948  }
1949
1950  // Just build a canonical type that has the right qualifiers.
1951  QualType QualifiedCanonToPointee
1952    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1953
1954  if (isa<ObjCObjectPointerType>(ToType))
1955    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1956  return Context.getPointerType(QualifiedCanonToPointee);
1957}
1958
1959static bool isNullPointerConstantForConversion(Expr *Expr,
1960                                               bool InOverloadResolution,
1961                                               ASTContext &Context) {
1962  // Handle value-dependent integral null pointer constants correctly.
1963  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1964  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1965      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1966    return !InOverloadResolution;
1967
1968  return Expr->isNullPointerConstant(Context,
1969                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1970                                        : Expr::NPC_ValueDependentIsNull);
1971}
1972
1973/// IsPointerConversion - Determines whether the conversion of the
1974/// expression From, which has the (possibly adjusted) type FromType,
1975/// can be converted to the type ToType via a pointer conversion (C++
1976/// 4.10). If so, returns true and places the converted type (that
1977/// might differ from ToType in its cv-qualifiers at some level) into
1978/// ConvertedType.
1979///
1980/// This routine also supports conversions to and from block pointers
1981/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1982/// pointers to interfaces. FIXME: Once we've determined the
1983/// appropriate overloading rules for Objective-C, we may want to
1984/// split the Objective-C checks into a different routine; however,
1985/// GCC seems to consider all of these conversions to be pointer
1986/// conversions, so for now they live here. IncompatibleObjC will be
1987/// set if the conversion is an allowed Objective-C conversion that
1988/// should result in a warning.
1989bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1990                               bool InOverloadResolution,
1991                               QualType& ConvertedType,
1992                               bool &IncompatibleObjC) {
1993  IncompatibleObjC = false;
1994  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1995                              IncompatibleObjC))
1996    return true;
1997
1998  // Conversion from a null pointer constant to any Objective-C pointer type.
1999  if (ToType->isObjCObjectPointerType() &&
2000      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2001    ConvertedType = ToType;
2002    return true;
2003  }
2004
2005  // Blocks: Block pointers can be converted to void*.
2006  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2007      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2008    ConvertedType = ToType;
2009    return true;
2010  }
2011  // Blocks: A null pointer constant can be converted to a block
2012  // pointer type.
2013  if (ToType->isBlockPointerType() &&
2014      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2015    ConvertedType = ToType;
2016    return true;
2017  }
2018
2019  // If the left-hand-side is nullptr_t, the right side can be a null
2020  // pointer constant.
2021  if (ToType->isNullPtrType() &&
2022      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2023    ConvertedType = ToType;
2024    return true;
2025  }
2026
2027  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2028  if (!ToTypePtr)
2029    return false;
2030
2031  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2032  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2033    ConvertedType = ToType;
2034    return true;
2035  }
2036
2037  // Beyond this point, both types need to be pointers
2038  // , including objective-c pointers.
2039  QualType ToPointeeType = ToTypePtr->getPointeeType();
2040  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2041      !getLangOpts().ObjCAutoRefCount) {
2042    ConvertedType = BuildSimilarlyQualifiedPointerType(
2043                                      FromType->getAs<ObjCObjectPointerType>(),
2044                                                       ToPointeeType,
2045                                                       ToType, Context);
2046    return true;
2047  }
2048  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2049  if (!FromTypePtr)
2050    return false;
2051
2052  QualType FromPointeeType = FromTypePtr->getPointeeType();
2053
2054  // If the unqualified pointee types are the same, this can't be a
2055  // pointer conversion, so don't do all of the work below.
2056  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2057    return false;
2058
2059  // An rvalue of type "pointer to cv T," where T is an object type,
2060  // can be converted to an rvalue of type "pointer to cv void" (C++
2061  // 4.10p2).
2062  if (FromPointeeType->isIncompleteOrObjectType() &&
2063      ToPointeeType->isVoidType()) {
2064    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2065                                                       ToPointeeType,
2066                                                       ToType, Context,
2067                                                   /*StripObjCLifetime=*/true);
2068    return true;
2069  }
2070
2071  // MSVC allows implicit function to void* type conversion.
2072  if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2073      ToPointeeType->isVoidType()) {
2074    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2075                                                       ToPointeeType,
2076                                                       ToType, Context);
2077    return true;
2078  }
2079
2080  // When we're overloading in C, we allow a special kind of pointer
2081  // conversion for compatible-but-not-identical pointee types.
2082  if (!getLangOpts().CPlusPlus &&
2083      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2084    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2085                                                       ToPointeeType,
2086                                                       ToType, Context);
2087    return true;
2088  }
2089
2090  // C++ [conv.ptr]p3:
2091  //
2092  //   An rvalue of type "pointer to cv D," where D is a class type,
2093  //   can be converted to an rvalue of type "pointer to cv B," where
2094  //   B is a base class (clause 10) of D. If B is an inaccessible
2095  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2096  //   necessitates this conversion is ill-formed. The result of the
2097  //   conversion is a pointer to the base class sub-object of the
2098  //   derived class object. The null pointer value is converted to
2099  //   the null pointer value of the destination type.
2100  //
2101  // Note that we do not check for ambiguity or inaccessibility
2102  // here. That is handled by CheckPointerConversion.
2103  if (getLangOpts().CPlusPlus &&
2104      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2105      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2106      !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2107      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2108    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2109                                                       ToPointeeType,
2110                                                       ToType, Context);
2111    return true;
2112  }
2113
2114  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2115      Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2116    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2117                                                       ToPointeeType,
2118                                                       ToType, Context);
2119    return true;
2120  }
2121
2122  return false;
2123}
2124
2125/// \brief Adopt the given qualifiers for the given type.
2126static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2127  Qualifiers TQs = T.getQualifiers();
2128
2129  // Check whether qualifiers already match.
2130  if (TQs == Qs)
2131    return T;
2132
2133  if (Qs.compatiblyIncludes(TQs))
2134    return Context.getQualifiedType(T, Qs);
2135
2136  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2137}
2138
2139/// isObjCPointerConversion - Determines whether this is an
2140/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2141/// with the same arguments and return values.
2142bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2143                                   QualType& ConvertedType,
2144                                   bool &IncompatibleObjC) {
2145  if (!getLangOpts().ObjC1)
2146    return false;
2147
2148  // The set of qualifiers on the type we're converting from.
2149  Qualifiers FromQualifiers = FromType.getQualifiers();
2150
2151  // First, we handle all conversions on ObjC object pointer types.
2152  const ObjCObjectPointerType* ToObjCPtr =
2153    ToType->getAs<ObjCObjectPointerType>();
2154  const ObjCObjectPointerType *FromObjCPtr =
2155    FromType->getAs<ObjCObjectPointerType>();
2156
2157  if (ToObjCPtr && FromObjCPtr) {
2158    // If the pointee types are the same (ignoring qualifications),
2159    // then this is not a pointer conversion.
2160    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2161                                       FromObjCPtr->getPointeeType()))
2162      return false;
2163
2164    // Check for compatible
2165    // Objective C++: We're able to convert between "id" or "Class" and a
2166    // pointer to any interface (in both directions).
2167    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2168      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2169      return true;
2170    }
2171    // Conversions with Objective-C's id<...>.
2172    if ((FromObjCPtr->isObjCQualifiedIdType() ||
2173         ToObjCPtr->isObjCQualifiedIdType()) &&
2174        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2175                                                  /*compare=*/false)) {
2176      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2177      return true;
2178    }
2179    // Objective C++: We're able to convert from a pointer to an
2180    // interface to a pointer to a different interface.
2181    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2182      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2183      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2184      if (getLangOpts().CPlusPlus && LHS && RHS &&
2185          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2186                                                FromObjCPtr->getPointeeType()))
2187        return false;
2188      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2189                                                   ToObjCPtr->getPointeeType(),
2190                                                         ToType, Context);
2191      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2192      return true;
2193    }
2194
2195    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2196      // Okay: this is some kind of implicit downcast of Objective-C
2197      // interfaces, which is permitted. However, we're going to
2198      // complain about it.
2199      IncompatibleObjC = true;
2200      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2201                                                   ToObjCPtr->getPointeeType(),
2202                                                         ToType, Context);
2203      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2204      return true;
2205    }
2206  }
2207  // Beyond this point, both types need to be C pointers or block pointers.
2208  QualType ToPointeeType;
2209  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2210    ToPointeeType = ToCPtr->getPointeeType();
2211  else if (const BlockPointerType *ToBlockPtr =
2212            ToType->getAs<BlockPointerType>()) {
2213    // Objective C++: We're able to convert from a pointer to any object
2214    // to a block pointer type.
2215    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2216      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2217      return true;
2218    }
2219    ToPointeeType = ToBlockPtr->getPointeeType();
2220  }
2221  else if (FromType->getAs<BlockPointerType>() &&
2222           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2223    // Objective C++: We're able to convert from a block pointer type to a
2224    // pointer to any object.
2225    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2226    return true;
2227  }
2228  else
2229    return false;
2230
2231  QualType FromPointeeType;
2232  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2233    FromPointeeType = FromCPtr->getPointeeType();
2234  else if (const BlockPointerType *FromBlockPtr =
2235           FromType->getAs<BlockPointerType>())
2236    FromPointeeType = FromBlockPtr->getPointeeType();
2237  else
2238    return false;
2239
2240  // If we have pointers to pointers, recursively check whether this
2241  // is an Objective-C conversion.
2242  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2243      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2244                              IncompatibleObjC)) {
2245    // We always complain about this conversion.
2246    IncompatibleObjC = true;
2247    ConvertedType = Context.getPointerType(ConvertedType);
2248    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2249    return true;
2250  }
2251  // Allow conversion of pointee being objective-c pointer to another one;
2252  // as in I* to id.
2253  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2254      ToPointeeType->getAs<ObjCObjectPointerType>() &&
2255      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2256                              IncompatibleObjC)) {
2257
2258    ConvertedType = Context.getPointerType(ConvertedType);
2259    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2260    return true;
2261  }
2262
2263  // If we have pointers to functions or blocks, check whether the only
2264  // differences in the argument and result types are in Objective-C
2265  // pointer conversions. If so, we permit the conversion (but
2266  // complain about it).
2267  const FunctionProtoType *FromFunctionType
2268    = FromPointeeType->getAs<FunctionProtoType>();
2269  const FunctionProtoType *ToFunctionType
2270    = ToPointeeType->getAs<FunctionProtoType>();
2271  if (FromFunctionType && ToFunctionType) {
2272    // If the function types are exactly the same, this isn't an
2273    // Objective-C pointer conversion.
2274    if (Context.getCanonicalType(FromPointeeType)
2275          == Context.getCanonicalType(ToPointeeType))
2276      return false;
2277
2278    // Perform the quick checks that will tell us whether these
2279    // function types are obviously different.
2280    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2281        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2282        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2283      return false;
2284
2285    bool HasObjCConversion = false;
2286    if (Context.getCanonicalType(FromFunctionType->getResultType())
2287          == Context.getCanonicalType(ToFunctionType->getResultType())) {
2288      // Okay, the types match exactly. Nothing to do.
2289    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2290                                       ToFunctionType->getResultType(),
2291                                       ConvertedType, IncompatibleObjC)) {
2292      // Okay, we have an Objective-C pointer conversion.
2293      HasObjCConversion = true;
2294    } else {
2295      // Function types are too different. Abort.
2296      return false;
2297    }
2298
2299    // Check argument types.
2300    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2301         ArgIdx != NumArgs; ++ArgIdx) {
2302      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2303      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2304      if (Context.getCanonicalType(FromArgType)
2305            == Context.getCanonicalType(ToArgType)) {
2306        // Okay, the types match exactly. Nothing to do.
2307      } else if (isObjCPointerConversion(FromArgType, ToArgType,
2308                                         ConvertedType, IncompatibleObjC)) {
2309        // Okay, we have an Objective-C pointer conversion.
2310        HasObjCConversion = true;
2311      } else {
2312        // Argument types are too different. Abort.
2313        return false;
2314      }
2315    }
2316
2317    if (HasObjCConversion) {
2318      // We had an Objective-C conversion. Allow this pointer
2319      // conversion, but complain about it.
2320      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2321      IncompatibleObjC = true;
2322      return true;
2323    }
2324  }
2325
2326  return false;
2327}
2328
2329/// \brief Determine whether this is an Objective-C writeback conversion,
2330/// used for parameter passing when performing automatic reference counting.
2331///
2332/// \param FromType The type we're converting form.
2333///
2334/// \param ToType The type we're converting to.
2335///
2336/// \param ConvertedType The type that will be produced after applying
2337/// this conversion.
2338bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2339                                     QualType &ConvertedType) {
2340  if (!getLangOpts().ObjCAutoRefCount ||
2341      Context.hasSameUnqualifiedType(FromType, ToType))
2342    return false;
2343
2344  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2345  QualType ToPointee;
2346  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2347    ToPointee = ToPointer->getPointeeType();
2348  else
2349    return false;
2350
2351  Qualifiers ToQuals = ToPointee.getQualifiers();
2352  if (!ToPointee->isObjCLifetimeType() ||
2353      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2354      !ToQuals.withoutObjCLifetime().empty())
2355    return false;
2356
2357  // Argument must be a pointer to __strong to __weak.
2358  QualType FromPointee;
2359  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2360    FromPointee = FromPointer->getPointeeType();
2361  else
2362    return false;
2363
2364  Qualifiers FromQuals = FromPointee.getQualifiers();
2365  if (!FromPointee->isObjCLifetimeType() ||
2366      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2367       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2368    return false;
2369
2370  // Make sure that we have compatible qualifiers.
2371  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2372  if (!ToQuals.compatiblyIncludes(FromQuals))
2373    return false;
2374
2375  // Remove qualifiers from the pointee type we're converting from; they
2376  // aren't used in the compatibility check belong, and we'll be adding back
2377  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2378  FromPointee = FromPointee.getUnqualifiedType();
2379
2380  // The unqualified form of the pointee types must be compatible.
2381  ToPointee = ToPointee.getUnqualifiedType();
2382  bool IncompatibleObjC;
2383  if (Context.typesAreCompatible(FromPointee, ToPointee))
2384    FromPointee = ToPointee;
2385  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2386                                    IncompatibleObjC))
2387    return false;
2388
2389  /// \brief Construct the type we're converting to, which is a pointer to
2390  /// __autoreleasing pointee.
2391  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2392  ConvertedType = Context.getPointerType(FromPointee);
2393  return true;
2394}
2395
2396bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2397                                    QualType& ConvertedType) {
2398  QualType ToPointeeType;
2399  if (const BlockPointerType *ToBlockPtr =
2400        ToType->getAs<BlockPointerType>())
2401    ToPointeeType = ToBlockPtr->getPointeeType();
2402  else
2403    return false;
2404
2405  QualType FromPointeeType;
2406  if (const BlockPointerType *FromBlockPtr =
2407      FromType->getAs<BlockPointerType>())
2408    FromPointeeType = FromBlockPtr->getPointeeType();
2409  else
2410    return false;
2411  // We have pointer to blocks, check whether the only
2412  // differences in the argument and result types are in Objective-C
2413  // pointer conversions. If so, we permit the conversion.
2414
2415  const FunctionProtoType *FromFunctionType
2416    = FromPointeeType->getAs<FunctionProtoType>();
2417  const FunctionProtoType *ToFunctionType
2418    = ToPointeeType->getAs<FunctionProtoType>();
2419
2420  if (!FromFunctionType || !ToFunctionType)
2421    return false;
2422
2423  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2424    return true;
2425
2426  // Perform the quick checks that will tell us whether these
2427  // function types are obviously different.
2428  if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2429      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2430    return false;
2431
2432  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2433  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2434  if (FromEInfo != ToEInfo)
2435    return false;
2436
2437  bool IncompatibleObjC = false;
2438  if (Context.hasSameType(FromFunctionType->getResultType(),
2439                          ToFunctionType->getResultType())) {
2440    // Okay, the types match exactly. Nothing to do.
2441  } else {
2442    QualType RHS = FromFunctionType->getResultType();
2443    QualType LHS = ToFunctionType->getResultType();
2444    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2445        !RHS.hasQualifiers() && LHS.hasQualifiers())
2446       LHS = LHS.getUnqualifiedType();
2447
2448     if (Context.hasSameType(RHS,LHS)) {
2449       // OK exact match.
2450     } else if (isObjCPointerConversion(RHS, LHS,
2451                                        ConvertedType, IncompatibleObjC)) {
2452     if (IncompatibleObjC)
2453       return false;
2454     // Okay, we have an Objective-C pointer conversion.
2455     }
2456     else
2457       return false;
2458   }
2459
2460   // Check argument types.
2461   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2462        ArgIdx != NumArgs; ++ArgIdx) {
2463     IncompatibleObjC = false;
2464     QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2465     QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2466     if (Context.hasSameType(FromArgType, ToArgType)) {
2467       // Okay, the types match exactly. Nothing to do.
2468     } else if (isObjCPointerConversion(ToArgType, FromArgType,
2469                                        ConvertedType, IncompatibleObjC)) {
2470       if (IncompatibleObjC)
2471         return false;
2472       // Okay, we have an Objective-C pointer conversion.
2473     } else
2474       // Argument types are too different. Abort.
2475       return false;
2476   }
2477   if (LangOpts.ObjCAutoRefCount &&
2478       !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2479                                                    ToFunctionType))
2480     return false;
2481
2482   ConvertedType = ToType;
2483   return true;
2484}
2485
2486enum {
2487  ft_default,
2488  ft_different_class,
2489  ft_parameter_arity,
2490  ft_parameter_mismatch,
2491  ft_return_type,
2492  ft_qualifer_mismatch
2493};
2494
2495/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2496/// function types.  Catches different number of parameter, mismatch in
2497/// parameter types, and different return types.
2498void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2499                                      QualType FromType, QualType ToType) {
2500  // If either type is not valid, include no extra info.
2501  if (FromType.isNull() || ToType.isNull()) {
2502    PDiag << ft_default;
2503    return;
2504  }
2505
2506  // Get the function type from the pointers.
2507  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2508    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2509                            *ToMember = ToType->getAs<MemberPointerType>();
2510    if (FromMember->getClass() != ToMember->getClass()) {
2511      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2512            << QualType(FromMember->getClass(), 0);
2513      return;
2514    }
2515    FromType = FromMember->getPointeeType();
2516    ToType = ToMember->getPointeeType();
2517  }
2518
2519  if (FromType->isPointerType())
2520    FromType = FromType->getPointeeType();
2521  if (ToType->isPointerType())
2522    ToType = ToType->getPointeeType();
2523
2524  // Remove references.
2525  FromType = FromType.getNonReferenceType();
2526  ToType = ToType.getNonReferenceType();
2527
2528  // Don't print extra info for non-specialized template functions.
2529  if (FromType->isInstantiationDependentType() &&
2530      !FromType->getAs<TemplateSpecializationType>()) {
2531    PDiag << ft_default;
2532    return;
2533  }
2534
2535  // No extra info for same types.
2536  if (Context.hasSameType(FromType, ToType)) {
2537    PDiag << ft_default;
2538    return;
2539  }
2540
2541  const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2542                          *ToFunction = ToType->getAs<FunctionProtoType>();
2543
2544  // Both types need to be function types.
2545  if (!FromFunction || !ToFunction) {
2546    PDiag << ft_default;
2547    return;
2548  }
2549
2550  if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2551    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2552          << FromFunction->getNumArgs();
2553    return;
2554  }
2555
2556  // Handle different parameter types.
2557  unsigned ArgPos;
2558  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2559    PDiag << ft_parameter_mismatch << ArgPos + 1
2560          << ToFunction->getArgType(ArgPos)
2561          << FromFunction->getArgType(ArgPos);
2562    return;
2563  }
2564
2565  // Handle different return type.
2566  if (!Context.hasSameType(FromFunction->getResultType(),
2567                           ToFunction->getResultType())) {
2568    PDiag << ft_return_type << ToFunction->getResultType()
2569          << FromFunction->getResultType();
2570    return;
2571  }
2572
2573  unsigned FromQuals = FromFunction->getTypeQuals(),
2574           ToQuals = ToFunction->getTypeQuals();
2575  if (FromQuals != ToQuals) {
2576    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2577    return;
2578  }
2579
2580  // Unable to find a difference, so add no extra info.
2581  PDiag << ft_default;
2582}
2583
2584/// FunctionArgTypesAreEqual - This routine checks two function proto types
2585/// for equality of their argument types. Caller has already checked that
2586/// they have same number of arguments.  If the parameters are different,
2587/// ArgPos will have the parameter index of the first different parameter.
2588bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2589                                    const FunctionProtoType *NewType,
2590                                    unsigned *ArgPos) {
2591  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2592       N = NewType->arg_type_begin(),
2593       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2594    if (!Context.hasSameType(O->getUnqualifiedType(),
2595                             N->getUnqualifiedType())) {
2596      if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2597      return false;
2598    }
2599  }
2600  return true;
2601}
2602
2603/// CheckPointerConversion - Check the pointer conversion from the
2604/// expression From to the type ToType. This routine checks for
2605/// ambiguous or inaccessible derived-to-base pointer
2606/// conversions for which IsPointerConversion has already returned
2607/// true. It returns true and produces a diagnostic if there was an
2608/// error, or returns false otherwise.
2609bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2610                                  CastKind &Kind,
2611                                  CXXCastPath& BasePath,
2612                                  bool IgnoreBaseAccess) {
2613  QualType FromType = From->getType();
2614  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2615
2616  Kind = CK_BitCast;
2617
2618  if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2619      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2620      Expr::NPCK_ZeroExpression) {
2621    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2622      DiagRuntimeBehavior(From->getExprLoc(), From,
2623                          PDiag(diag::warn_impcast_bool_to_null_pointer)
2624                            << ToType << From->getSourceRange());
2625    else if (!isUnevaluatedContext())
2626      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2627        << ToType << From->getSourceRange();
2628  }
2629  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2630    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2631      QualType FromPointeeType = FromPtrType->getPointeeType(),
2632               ToPointeeType   = ToPtrType->getPointeeType();
2633
2634      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2635          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2636        // We must have a derived-to-base conversion. Check an
2637        // ambiguous or inaccessible conversion.
2638        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2639                                         From->getExprLoc(),
2640                                         From->getSourceRange(), &BasePath,
2641                                         IgnoreBaseAccess))
2642          return true;
2643
2644        // The conversion was successful.
2645        Kind = CK_DerivedToBase;
2646      }
2647    }
2648  } else if (const ObjCObjectPointerType *ToPtrType =
2649               ToType->getAs<ObjCObjectPointerType>()) {
2650    if (const ObjCObjectPointerType *FromPtrType =
2651          FromType->getAs<ObjCObjectPointerType>()) {
2652      // Objective-C++ conversions are always okay.
2653      // FIXME: We should have a different class of conversions for the
2654      // Objective-C++ implicit conversions.
2655      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2656        return false;
2657    } else if (FromType->isBlockPointerType()) {
2658      Kind = CK_BlockPointerToObjCPointerCast;
2659    } else {
2660      Kind = CK_CPointerToObjCPointerCast;
2661    }
2662  } else if (ToType->isBlockPointerType()) {
2663    if (!FromType->isBlockPointerType())
2664      Kind = CK_AnyPointerToBlockPointerCast;
2665  }
2666
2667  // We shouldn't fall into this case unless it's valid for other
2668  // reasons.
2669  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2670    Kind = CK_NullToPointer;
2671
2672  return false;
2673}
2674
2675/// IsMemberPointerConversion - Determines whether the conversion of the
2676/// expression From, which has the (possibly adjusted) type FromType, can be
2677/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2678/// If so, returns true and places the converted type (that might differ from
2679/// ToType in its cv-qualifiers at some level) into ConvertedType.
2680bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2681                                     QualType ToType,
2682                                     bool InOverloadResolution,
2683                                     QualType &ConvertedType) {
2684  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2685  if (!ToTypePtr)
2686    return false;
2687
2688  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2689  if (From->isNullPointerConstant(Context,
2690                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2691                                        : Expr::NPC_ValueDependentIsNull)) {
2692    ConvertedType = ToType;
2693    return true;
2694  }
2695
2696  // Otherwise, both types have to be member pointers.
2697  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2698  if (!FromTypePtr)
2699    return false;
2700
2701  // A pointer to member of B can be converted to a pointer to member of D,
2702  // where D is derived from B (C++ 4.11p2).
2703  QualType FromClass(FromTypePtr->getClass(), 0);
2704  QualType ToClass(ToTypePtr->getClass(), 0);
2705
2706  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2707      !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2708      IsDerivedFrom(ToClass, FromClass)) {
2709    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2710                                                 ToClass.getTypePtr());
2711    return true;
2712  }
2713
2714  return false;
2715}
2716
2717/// CheckMemberPointerConversion - Check the member pointer conversion from the
2718/// expression From to the type ToType. This routine checks for ambiguous or
2719/// virtual or inaccessible base-to-derived member pointer conversions
2720/// for which IsMemberPointerConversion has already returned true. It returns
2721/// true and produces a diagnostic if there was an error, or returns false
2722/// otherwise.
2723bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2724                                        CastKind &Kind,
2725                                        CXXCastPath &BasePath,
2726                                        bool IgnoreBaseAccess) {
2727  QualType FromType = From->getType();
2728  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2729  if (!FromPtrType) {
2730    // This must be a null pointer to member pointer conversion
2731    assert(From->isNullPointerConstant(Context,
2732                                       Expr::NPC_ValueDependentIsNull) &&
2733           "Expr must be null pointer constant!");
2734    Kind = CK_NullToMemberPointer;
2735    return false;
2736  }
2737
2738  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2739  assert(ToPtrType && "No member pointer cast has a target type "
2740                      "that is not a member pointer.");
2741
2742  QualType FromClass = QualType(FromPtrType->getClass(), 0);
2743  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2744
2745  // FIXME: What about dependent types?
2746  assert(FromClass->isRecordType() && "Pointer into non-class.");
2747  assert(ToClass->isRecordType() && "Pointer into non-class.");
2748
2749  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2750                     /*DetectVirtual=*/true);
2751  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2752  assert(DerivationOkay &&
2753         "Should not have been called if derivation isn't OK.");
2754  (void)DerivationOkay;
2755
2756  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2757                                  getUnqualifiedType())) {
2758    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2759    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2760      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2761    return true;
2762  }
2763
2764  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2765    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2766      << FromClass << ToClass << QualType(VBase, 0)
2767      << From->getSourceRange();
2768    return true;
2769  }
2770
2771  if (!IgnoreBaseAccess)
2772    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2773                         Paths.front(),
2774                         diag::err_downcast_from_inaccessible_base);
2775
2776  // Must be a base to derived member conversion.
2777  BuildBasePathArray(Paths, BasePath);
2778  Kind = CK_BaseToDerivedMemberPointer;
2779  return false;
2780}
2781
2782/// IsQualificationConversion - Determines whether the conversion from
2783/// an rvalue of type FromType to ToType is a qualification conversion
2784/// (C++ 4.4).
2785///
2786/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2787/// when the qualification conversion involves a change in the Objective-C
2788/// object lifetime.
2789bool
2790Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2791                                bool CStyle, bool &ObjCLifetimeConversion) {
2792  FromType = Context.getCanonicalType(FromType);
2793  ToType = Context.getCanonicalType(ToType);
2794  ObjCLifetimeConversion = false;
2795
2796  // If FromType and ToType are the same type, this is not a
2797  // qualification conversion.
2798  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2799    return false;
2800
2801  // (C++ 4.4p4):
2802  //   A conversion can add cv-qualifiers at levels other than the first
2803  //   in multi-level pointers, subject to the following rules: [...]
2804  bool PreviousToQualsIncludeConst = true;
2805  bool UnwrappedAnyPointer = false;
2806  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2807    // Within each iteration of the loop, we check the qualifiers to
2808    // determine if this still looks like a qualification
2809    // conversion. Then, if all is well, we unwrap one more level of
2810    // pointers or pointers-to-members and do it all again
2811    // until there are no more pointers or pointers-to-members left to
2812    // unwrap.
2813    UnwrappedAnyPointer = true;
2814
2815    Qualifiers FromQuals = FromType.getQualifiers();
2816    Qualifiers ToQuals = ToType.getQualifiers();
2817
2818    // Objective-C ARC:
2819    //   Check Objective-C lifetime conversions.
2820    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2821        UnwrappedAnyPointer) {
2822      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2823        ObjCLifetimeConversion = true;
2824        FromQuals.removeObjCLifetime();
2825        ToQuals.removeObjCLifetime();
2826      } else {
2827        // Qualification conversions cannot cast between different
2828        // Objective-C lifetime qualifiers.
2829        return false;
2830      }
2831    }
2832
2833    // Allow addition/removal of GC attributes but not changing GC attributes.
2834    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2835        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2836      FromQuals.removeObjCGCAttr();
2837      ToQuals.removeObjCGCAttr();
2838    }
2839
2840    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2841    //      2,j, and similarly for volatile.
2842    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2843      return false;
2844
2845    //   -- if the cv 1,j and cv 2,j are different, then const is in
2846    //      every cv for 0 < k < j.
2847    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2848        && !PreviousToQualsIncludeConst)
2849      return false;
2850
2851    // Keep track of whether all prior cv-qualifiers in the "to" type
2852    // include const.
2853    PreviousToQualsIncludeConst
2854      = PreviousToQualsIncludeConst && ToQuals.hasConst();
2855  }
2856
2857  // We are left with FromType and ToType being the pointee types
2858  // after unwrapping the original FromType and ToType the same number
2859  // of types. If we unwrapped any pointers, and if FromType and
2860  // ToType have the same unqualified type (since we checked
2861  // qualifiers above), then this is a qualification conversion.
2862  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2863}
2864
2865/// \brief - Determine whether this is a conversion from a scalar type to an
2866/// atomic type.
2867///
2868/// If successful, updates \c SCS's second and third steps in the conversion
2869/// sequence to finish the conversion.
2870static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2871                                bool InOverloadResolution,
2872                                StandardConversionSequence &SCS,
2873                                bool CStyle) {
2874  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2875  if (!ToAtomic)
2876    return false;
2877
2878  StandardConversionSequence InnerSCS;
2879  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2880                            InOverloadResolution, InnerSCS,
2881                            CStyle, /*AllowObjCWritebackConversion=*/false))
2882    return false;
2883
2884  SCS.Second = InnerSCS.Second;
2885  SCS.setToType(1, InnerSCS.getToType(1));
2886  SCS.Third = InnerSCS.Third;
2887  SCS.QualificationIncludesObjCLifetime
2888    = InnerSCS.QualificationIncludesObjCLifetime;
2889  SCS.setToType(2, InnerSCS.getToType(2));
2890  return true;
2891}
2892
2893static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2894                                              CXXConstructorDecl *Constructor,
2895                                              QualType Type) {
2896  const FunctionProtoType *CtorType =
2897      Constructor->getType()->getAs<FunctionProtoType>();
2898  if (CtorType->getNumArgs() > 0) {
2899    QualType FirstArg = CtorType->getArgType(0);
2900    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2901      return true;
2902  }
2903  return false;
2904}
2905
2906static OverloadingResult
2907IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2908                                       CXXRecordDecl *To,
2909                                       UserDefinedConversionSequence &User,
2910                                       OverloadCandidateSet &CandidateSet,
2911                                       bool AllowExplicit) {
2912  DeclContext::lookup_result R = S.LookupConstructors(To);
2913  for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2914       Con != ConEnd; ++Con) {
2915    NamedDecl *D = *Con;
2916    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2917
2918    // Find the constructor (which may be a template).
2919    CXXConstructorDecl *Constructor = 0;
2920    FunctionTemplateDecl *ConstructorTmpl
2921      = dyn_cast<FunctionTemplateDecl>(D);
2922    if (ConstructorTmpl)
2923      Constructor
2924        = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2925    else
2926      Constructor = cast<CXXConstructorDecl>(D);
2927
2928    bool Usable = !Constructor->isInvalidDecl() &&
2929                  S.isInitListConstructor(Constructor) &&
2930                  (AllowExplicit || !Constructor->isExplicit());
2931    if (Usable) {
2932      // If the first argument is (a reference to) the target type,
2933      // suppress conversions.
2934      bool SuppressUserConversions =
2935          isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2936      if (ConstructorTmpl)
2937        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2938                                       /*ExplicitArgs*/ 0,
2939                                       From, CandidateSet,
2940                                       SuppressUserConversions);
2941      else
2942        S.AddOverloadCandidate(Constructor, FoundDecl,
2943                               From, CandidateSet,
2944                               SuppressUserConversions);
2945    }
2946  }
2947
2948  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2949
2950  OverloadCandidateSet::iterator Best;
2951  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2952  case OR_Success: {
2953    // Record the standard conversion we used and the conversion function.
2954    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2955    QualType ThisType = Constructor->getThisType(S.Context);
2956    // Initializer lists don't have conversions as such.
2957    User.Before.setAsIdentityConversion();
2958    User.HadMultipleCandidates = HadMultipleCandidates;
2959    User.ConversionFunction = Constructor;
2960    User.FoundConversionFunction = Best->FoundDecl;
2961    User.After.setAsIdentityConversion();
2962    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2963    User.After.setAllToTypes(ToType);
2964    return OR_Success;
2965  }
2966
2967  case OR_No_Viable_Function:
2968    return OR_No_Viable_Function;
2969  case OR_Deleted:
2970    return OR_Deleted;
2971  case OR_Ambiguous:
2972    return OR_Ambiguous;
2973  }
2974
2975  llvm_unreachable("Invalid OverloadResult!");
2976}
2977
2978/// Determines whether there is a user-defined conversion sequence
2979/// (C++ [over.ics.user]) that converts expression From to the type
2980/// ToType. If such a conversion exists, User will contain the
2981/// user-defined conversion sequence that performs such a conversion
2982/// and this routine will return true. Otherwise, this routine returns
2983/// false and User is unspecified.
2984///
2985/// \param AllowExplicit  true if the conversion should consider C++0x
2986/// "explicit" conversion functions as well as non-explicit conversion
2987/// functions (C++0x [class.conv.fct]p2).
2988static OverloadingResult
2989IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2990                        UserDefinedConversionSequence &User,
2991                        OverloadCandidateSet &CandidateSet,
2992                        bool AllowExplicit) {
2993  // Whether we will only visit constructors.
2994  bool ConstructorsOnly = false;
2995
2996  // If the type we are conversion to is a class type, enumerate its
2997  // constructors.
2998  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2999    // C++ [over.match.ctor]p1:
3000    //   When objects of class type are direct-initialized (8.5), or
3001    //   copy-initialized from an expression of the same or a
3002    //   derived class type (8.5), overload resolution selects the
3003    //   constructor. [...] For copy-initialization, the candidate
3004    //   functions are all the converting constructors (12.3.1) of
3005    //   that class. The argument list is the expression-list within
3006    //   the parentheses of the initializer.
3007    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3008        (From->getType()->getAs<RecordType>() &&
3009         S.IsDerivedFrom(From->getType(), ToType)))
3010      ConstructorsOnly = true;
3011
3012    S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3013    // RequireCompleteType may have returned true due to some invalid decl
3014    // during template instantiation, but ToType may be complete enough now
3015    // to try to recover.
3016    if (ToType->isIncompleteType()) {
3017      // We're not going to find any constructors.
3018    } else if (CXXRecordDecl *ToRecordDecl
3019                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3020
3021      Expr **Args = &From;
3022      unsigned NumArgs = 1;
3023      bool ListInitializing = false;
3024      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3025        // But first, see if there is an init-list-constructor that will work.
3026        OverloadingResult Result = IsInitializerListConstructorConversion(
3027            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3028        if (Result != OR_No_Viable_Function)
3029          return Result;
3030        // Never mind.
3031        CandidateSet.clear();
3032
3033        // If we're list-initializing, we pass the individual elements as
3034        // arguments, not the entire list.
3035        Args = InitList->getInits();
3036        NumArgs = InitList->getNumInits();
3037        ListInitializing = true;
3038      }
3039
3040      DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3041      for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3042           Con != ConEnd; ++Con) {
3043        NamedDecl *D = *Con;
3044        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3045
3046        // Find the constructor (which may be a template).
3047        CXXConstructorDecl *Constructor = 0;
3048        FunctionTemplateDecl *ConstructorTmpl
3049          = dyn_cast<FunctionTemplateDecl>(D);
3050        if (ConstructorTmpl)
3051          Constructor
3052            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3053        else
3054          Constructor = cast<CXXConstructorDecl>(D);
3055
3056        bool Usable = !Constructor->isInvalidDecl();
3057        if (ListInitializing)
3058          Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3059        else
3060          Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3061        if (Usable) {
3062          bool SuppressUserConversions = !ConstructorsOnly;
3063          if (SuppressUserConversions && ListInitializing) {
3064            SuppressUserConversions = false;
3065            if (NumArgs == 1) {
3066              // If the first argument is (a reference to) the target type,
3067              // suppress conversions.
3068              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3069                                                S.Context, Constructor, ToType);
3070            }
3071          }
3072          if (ConstructorTmpl)
3073            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3074                                           /*ExplicitArgs*/ 0,
3075                                           llvm::makeArrayRef(Args, NumArgs),
3076                                           CandidateSet, SuppressUserConversions);
3077          else
3078            // Allow one user-defined conversion when user specifies a
3079            // From->ToType conversion via an static cast (c-style, etc).
3080            S.AddOverloadCandidate(Constructor, FoundDecl,
3081                                   llvm::makeArrayRef(Args, NumArgs),
3082                                   CandidateSet, SuppressUserConversions);
3083        }
3084      }
3085    }
3086  }
3087
3088  // Enumerate conversion functions, if we're allowed to.
3089  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3090  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3091    // No conversion functions from incomplete types.
3092  } else if (const RecordType *FromRecordType
3093                                   = From->getType()->getAs<RecordType>()) {
3094    if (CXXRecordDecl *FromRecordDecl
3095         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3096      // Add all of the conversion functions as candidates.
3097      std::pair<CXXRecordDecl::conversion_iterator,
3098                CXXRecordDecl::conversion_iterator>
3099        Conversions = FromRecordDecl->getVisibleConversionFunctions();
3100      for (CXXRecordDecl::conversion_iterator
3101             I = Conversions.first, E = Conversions.second; I != E; ++I) {
3102        DeclAccessPair FoundDecl = I.getPair();
3103        NamedDecl *D = FoundDecl.getDecl();
3104        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3105        if (isa<UsingShadowDecl>(D))
3106          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3107
3108        CXXConversionDecl *Conv;
3109        FunctionTemplateDecl *ConvTemplate;
3110        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3111          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3112        else
3113          Conv = cast<CXXConversionDecl>(D);
3114
3115        if (AllowExplicit || !Conv->isExplicit()) {
3116          if (ConvTemplate)
3117            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3118                                             ActingContext, From, ToType,
3119                                             CandidateSet);
3120          else
3121            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3122                                     From, ToType, CandidateSet);
3123        }
3124      }
3125    }
3126  }
3127
3128  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3129
3130  OverloadCandidateSet::iterator Best;
3131  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3132  case OR_Success:
3133    // Record the standard conversion we used and the conversion function.
3134    if (CXXConstructorDecl *Constructor
3135          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3136      // C++ [over.ics.user]p1:
3137      //   If the user-defined conversion is specified by a
3138      //   constructor (12.3.1), the initial standard conversion
3139      //   sequence converts the source type to the type required by
3140      //   the argument of the constructor.
3141      //
3142      QualType ThisType = Constructor->getThisType(S.Context);
3143      if (isa<InitListExpr>(From)) {
3144        // Initializer lists don't have conversions as such.
3145        User.Before.setAsIdentityConversion();
3146      } else {
3147        if (Best->Conversions[0].isEllipsis())
3148          User.EllipsisConversion = true;
3149        else {
3150          User.Before = Best->Conversions[0].Standard;
3151          User.EllipsisConversion = false;
3152        }
3153      }
3154      User.HadMultipleCandidates = HadMultipleCandidates;
3155      User.ConversionFunction = Constructor;
3156      User.FoundConversionFunction = Best->FoundDecl;
3157      User.After.setAsIdentityConversion();
3158      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3159      User.After.setAllToTypes(ToType);
3160      return OR_Success;
3161    }
3162    if (CXXConversionDecl *Conversion
3163                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3164      // C++ [over.ics.user]p1:
3165      //
3166      //   [...] If the user-defined conversion is specified by a
3167      //   conversion function (12.3.2), the initial standard
3168      //   conversion sequence converts the source type to the
3169      //   implicit object parameter of the conversion function.
3170      User.Before = Best->Conversions[0].Standard;
3171      User.HadMultipleCandidates = HadMultipleCandidates;
3172      User.ConversionFunction = Conversion;
3173      User.FoundConversionFunction = Best->FoundDecl;
3174      User.EllipsisConversion = false;
3175
3176      // C++ [over.ics.user]p2:
3177      //   The second standard conversion sequence converts the
3178      //   result of the user-defined conversion to the target type
3179      //   for the sequence. Since an implicit conversion sequence
3180      //   is an initialization, the special rules for
3181      //   initialization by user-defined conversion apply when
3182      //   selecting the best user-defined conversion for a
3183      //   user-defined conversion sequence (see 13.3.3 and
3184      //   13.3.3.1).
3185      User.After = Best->FinalConversion;
3186      return OR_Success;
3187    }
3188    llvm_unreachable("Not a constructor or conversion function?");
3189
3190  case OR_No_Viable_Function:
3191    return OR_No_Viable_Function;
3192  case OR_Deleted:
3193    // No conversion here! We're done.
3194    return OR_Deleted;
3195
3196  case OR_Ambiguous:
3197    return OR_Ambiguous;
3198  }
3199
3200  llvm_unreachable("Invalid OverloadResult!");
3201}
3202
3203bool
3204Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3205  ImplicitConversionSequence ICS;
3206  OverloadCandidateSet CandidateSet(From->getExprLoc());
3207  OverloadingResult OvResult =
3208    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3209                            CandidateSet, false);
3210  if (OvResult == OR_Ambiguous)
3211    Diag(From->getLocStart(),
3212         diag::err_typecheck_ambiguous_condition)
3213          << From->getType() << ToType << From->getSourceRange();
3214  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3215    if (!RequireCompleteType(From->getLocStart(), ToType,
3216                          diag::err_typecheck_nonviable_condition_incomplete,
3217                             From->getType(), From->getSourceRange()))
3218      Diag(From->getLocStart(),
3219           diag::err_typecheck_nonviable_condition)
3220           << From->getType() << From->getSourceRange() << ToType;
3221  }
3222  else
3223    return false;
3224  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3225  return true;
3226}
3227
3228/// \brief Compare the user-defined conversion functions or constructors
3229/// of two user-defined conversion sequences to determine whether any ordering
3230/// is possible.
3231static ImplicitConversionSequence::CompareKind
3232compareConversionFunctions(Sema &S,
3233                           FunctionDecl *Function1,
3234                           FunctionDecl *Function2) {
3235  if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3236    return ImplicitConversionSequence::Indistinguishable;
3237
3238  // Objective-C++:
3239  //   If both conversion functions are implicitly-declared conversions from
3240  //   a lambda closure type to a function pointer and a block pointer,
3241  //   respectively, always prefer the conversion to a function pointer,
3242  //   because the function pointer is more lightweight and is more likely
3243  //   to keep code working.
3244  CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3245  if (!Conv1)
3246    return ImplicitConversionSequence::Indistinguishable;
3247
3248  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3249  if (!Conv2)
3250    return ImplicitConversionSequence::Indistinguishable;
3251
3252  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3253    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3254    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3255    if (Block1 != Block2)
3256      return Block1? ImplicitConversionSequence::Worse
3257                   : ImplicitConversionSequence::Better;
3258  }
3259
3260  return ImplicitConversionSequence::Indistinguishable;
3261}
3262
3263/// CompareImplicitConversionSequences - Compare two implicit
3264/// conversion sequences to determine whether one is better than the
3265/// other or if they are indistinguishable (C++ 13.3.3.2).
3266static ImplicitConversionSequence::CompareKind
3267CompareImplicitConversionSequences(Sema &S,
3268                                   const ImplicitConversionSequence& ICS1,
3269                                   const ImplicitConversionSequence& ICS2)
3270{
3271  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3272  // conversion sequences (as defined in 13.3.3.1)
3273  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3274  //      conversion sequence than a user-defined conversion sequence or
3275  //      an ellipsis conversion sequence, and
3276  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3277  //      conversion sequence than an ellipsis conversion sequence
3278  //      (13.3.3.1.3).
3279  //
3280  // C++0x [over.best.ics]p10:
3281  //   For the purpose of ranking implicit conversion sequences as
3282  //   described in 13.3.3.2, the ambiguous conversion sequence is
3283  //   treated as a user-defined sequence that is indistinguishable
3284  //   from any other user-defined conversion sequence.
3285  if (ICS1.getKindRank() < ICS2.getKindRank())
3286    return ImplicitConversionSequence::Better;
3287  if (ICS2.getKindRank() < ICS1.getKindRank())
3288    return ImplicitConversionSequence::Worse;
3289
3290  // The following checks require both conversion sequences to be of
3291  // the same kind.
3292  if (ICS1.getKind() != ICS2.getKind())
3293    return ImplicitConversionSequence::Indistinguishable;
3294
3295  ImplicitConversionSequence::CompareKind Result =
3296      ImplicitConversionSequence::Indistinguishable;
3297
3298  // Two implicit conversion sequences of the same form are
3299  // indistinguishable conversion sequences unless one of the
3300  // following rules apply: (C++ 13.3.3.2p3):
3301  if (ICS1.isStandard())
3302    Result = CompareStandardConversionSequences(S,
3303                                                ICS1.Standard, ICS2.Standard);
3304  else if (ICS1.isUserDefined()) {
3305    // User-defined conversion sequence U1 is a better conversion
3306    // sequence than another user-defined conversion sequence U2 if
3307    // they contain the same user-defined conversion function or
3308    // constructor and if the second standard conversion sequence of
3309    // U1 is better than the second standard conversion sequence of
3310    // U2 (C++ 13.3.3.2p3).
3311    if (ICS1.UserDefined.ConversionFunction ==
3312          ICS2.UserDefined.ConversionFunction)
3313      Result = CompareStandardConversionSequences(S,
3314                                                  ICS1.UserDefined.After,
3315                                                  ICS2.UserDefined.After);
3316    else
3317      Result = compareConversionFunctions(S,
3318                                          ICS1.UserDefined.ConversionFunction,
3319                                          ICS2.UserDefined.ConversionFunction);
3320  }
3321
3322  // List-initialization sequence L1 is a better conversion sequence than
3323  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3324  // for some X and L2 does not.
3325  if (Result == ImplicitConversionSequence::Indistinguishable &&
3326      !ICS1.isBad()) {
3327    if (ICS1.isStdInitializerListElement() &&
3328        !ICS2.isStdInitializerListElement())
3329      return ImplicitConversionSequence::Better;
3330    if (!ICS1.isStdInitializerListElement() &&
3331        ICS2.isStdInitializerListElement())
3332      return ImplicitConversionSequence::Worse;
3333  }
3334
3335  return Result;
3336}
3337
3338static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3339  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3340    Qualifiers Quals;
3341    T1 = Context.getUnqualifiedArrayType(T1, Quals);
3342    T2 = Context.getUnqualifiedArrayType(T2, Quals);
3343  }
3344
3345  return Context.hasSameUnqualifiedType(T1, T2);
3346}
3347
3348// Per 13.3.3.2p3, compare the given standard conversion sequences to
3349// determine if one is a proper subset of the other.
3350static ImplicitConversionSequence::CompareKind
3351compareStandardConversionSubsets(ASTContext &Context,
3352                                 const StandardConversionSequence& SCS1,
3353                                 const StandardConversionSequence& SCS2) {
3354  ImplicitConversionSequence::CompareKind Result
3355    = ImplicitConversionSequence::Indistinguishable;
3356
3357  // the identity conversion sequence is considered to be a subsequence of
3358  // any non-identity conversion sequence
3359  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3360    return ImplicitConversionSequence::Better;
3361  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3362    return ImplicitConversionSequence::Worse;
3363
3364  if (SCS1.Second != SCS2.Second) {
3365    if (SCS1.Second == ICK_Identity)
3366      Result = ImplicitConversionSequence::Better;
3367    else if (SCS2.Second == ICK_Identity)
3368      Result = ImplicitConversionSequence::Worse;
3369    else
3370      return ImplicitConversionSequence::Indistinguishable;
3371  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3372    return ImplicitConversionSequence::Indistinguishable;
3373
3374  if (SCS1.Third == SCS2.Third) {
3375    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3376                             : ImplicitConversionSequence::Indistinguishable;
3377  }
3378
3379  if (SCS1.Third == ICK_Identity)
3380    return Result == ImplicitConversionSequence::Worse
3381             ? ImplicitConversionSequence::Indistinguishable
3382             : ImplicitConversionSequence::Better;
3383
3384  if (SCS2.Third == ICK_Identity)
3385    return Result == ImplicitConversionSequence::Better
3386             ? ImplicitConversionSequence::Indistinguishable
3387             : ImplicitConversionSequence::Worse;
3388
3389  return ImplicitConversionSequence::Indistinguishable;
3390}
3391
3392/// \brief Determine whether one of the given reference bindings is better
3393/// than the other based on what kind of bindings they are.
3394static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3395                                       const StandardConversionSequence &SCS2) {
3396  // C++0x [over.ics.rank]p3b4:
3397  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3398  //      implicit object parameter of a non-static member function declared
3399  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3400  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3401  //      lvalue reference to a function lvalue and S2 binds an rvalue
3402  //      reference*.
3403  //
3404  // FIXME: Rvalue references. We're going rogue with the above edits,
3405  // because the semantics in the current C++0x working paper (N3225 at the
3406  // time of this writing) break the standard definition of std::forward
3407  // and std::reference_wrapper when dealing with references to functions.
3408  // Proposed wording changes submitted to CWG for consideration.
3409  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3410      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3411    return false;
3412
3413  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3414          SCS2.IsLvalueReference) ||
3415         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3416          !SCS2.IsLvalueReference);
3417}
3418
3419/// CompareStandardConversionSequences - Compare two standard
3420/// conversion sequences to determine whether one is better than the
3421/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3422static ImplicitConversionSequence::CompareKind
3423CompareStandardConversionSequences(Sema &S,
3424                                   const StandardConversionSequence& SCS1,
3425                                   const StandardConversionSequence& SCS2)
3426{
3427  // Standard conversion sequence S1 is a better conversion sequence
3428  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3429
3430  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3431  //     sequences in the canonical form defined by 13.3.3.1.1,
3432  //     excluding any Lvalue Transformation; the identity conversion
3433  //     sequence is considered to be a subsequence of any
3434  //     non-identity conversion sequence) or, if not that,
3435  if (ImplicitConversionSequence::CompareKind CK
3436        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3437    return CK;
3438
3439  //  -- the rank of S1 is better than the rank of S2 (by the rules
3440  //     defined below), or, if not that,
3441  ImplicitConversionRank Rank1 = SCS1.getRank();
3442  ImplicitConversionRank Rank2 = SCS2.getRank();
3443  if (Rank1 < Rank2)
3444    return ImplicitConversionSequence::Better;
3445  else if (Rank2 < Rank1)
3446    return ImplicitConversionSequence::Worse;
3447
3448  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3449  // are indistinguishable unless one of the following rules
3450  // applies:
3451
3452  //   A conversion that is not a conversion of a pointer, or
3453  //   pointer to member, to bool is better than another conversion
3454  //   that is such a conversion.
3455  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3456    return SCS2.isPointerConversionToBool()
3457             ? ImplicitConversionSequence::Better
3458             : ImplicitConversionSequence::Worse;
3459
3460  // C++ [over.ics.rank]p4b2:
3461  //
3462  //   If class B is derived directly or indirectly from class A,
3463  //   conversion of B* to A* is better than conversion of B* to
3464  //   void*, and conversion of A* to void* is better than conversion
3465  //   of B* to void*.
3466  bool SCS1ConvertsToVoid
3467    = SCS1.isPointerConversionToVoidPointer(S.Context);
3468  bool SCS2ConvertsToVoid
3469    = SCS2.isPointerConversionToVoidPointer(S.Context);
3470  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3471    // Exactly one of the conversion sequences is a conversion to
3472    // a void pointer; it's the worse conversion.
3473    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3474                              : ImplicitConversionSequence::Worse;
3475  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3476    // Neither conversion sequence converts to a void pointer; compare
3477    // their derived-to-base conversions.
3478    if (ImplicitConversionSequence::CompareKind DerivedCK
3479          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3480      return DerivedCK;
3481  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3482             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3483    // Both conversion sequences are conversions to void
3484    // pointers. Compare the source types to determine if there's an
3485    // inheritance relationship in their sources.
3486    QualType FromType1 = SCS1.getFromType();
3487    QualType FromType2 = SCS2.getFromType();
3488
3489    // Adjust the types we're converting from via the array-to-pointer
3490    // conversion, if we need to.
3491    if (SCS1.First == ICK_Array_To_Pointer)
3492      FromType1 = S.Context.getArrayDecayedType(FromType1);
3493    if (SCS2.First == ICK_Array_To_Pointer)
3494      FromType2 = S.Context.getArrayDecayedType(FromType2);
3495
3496    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3497    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3498
3499    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3500      return ImplicitConversionSequence::Better;
3501    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3502      return ImplicitConversionSequence::Worse;
3503
3504    // Objective-C++: If one interface is more specific than the
3505    // other, it is the better one.
3506    const ObjCObjectPointerType* FromObjCPtr1
3507      = FromType1->getAs<ObjCObjectPointerType>();
3508    const ObjCObjectPointerType* FromObjCPtr2
3509      = FromType2->getAs<ObjCObjectPointerType>();
3510    if (FromObjCPtr1 && FromObjCPtr2) {
3511      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3512                                                          FromObjCPtr2);
3513      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3514                                                           FromObjCPtr1);
3515      if (AssignLeft != AssignRight) {
3516        return AssignLeft? ImplicitConversionSequence::Better
3517                         : ImplicitConversionSequence::Worse;
3518      }
3519    }
3520  }
3521
3522  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3523  // bullet 3).
3524  if (ImplicitConversionSequence::CompareKind QualCK
3525        = CompareQualificationConversions(S, SCS1, SCS2))
3526    return QualCK;
3527
3528  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3529    // Check for a better reference binding based on the kind of bindings.
3530    if (isBetterReferenceBindingKind(SCS1, SCS2))
3531      return ImplicitConversionSequence::Better;
3532    else if (isBetterReferenceBindingKind(SCS2, SCS1))
3533      return ImplicitConversionSequence::Worse;
3534
3535    // C++ [over.ics.rank]p3b4:
3536    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3537    //      which the references refer are the same type except for
3538    //      top-level cv-qualifiers, and the type to which the reference
3539    //      initialized by S2 refers is more cv-qualified than the type
3540    //      to which the reference initialized by S1 refers.
3541    QualType T1 = SCS1.getToType(2);
3542    QualType T2 = SCS2.getToType(2);
3543    T1 = S.Context.getCanonicalType(T1);
3544    T2 = S.Context.getCanonicalType(T2);
3545    Qualifiers T1Quals, T2Quals;
3546    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3547    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3548    if (UnqualT1 == UnqualT2) {
3549      // Objective-C++ ARC: If the references refer to objects with different
3550      // lifetimes, prefer bindings that don't change lifetime.
3551      if (SCS1.ObjCLifetimeConversionBinding !=
3552                                          SCS2.ObjCLifetimeConversionBinding) {
3553        return SCS1.ObjCLifetimeConversionBinding
3554                                           ? ImplicitConversionSequence::Worse
3555                                           : ImplicitConversionSequence::Better;
3556      }
3557
3558      // If the type is an array type, promote the element qualifiers to the
3559      // type for comparison.
3560      if (isa<ArrayType>(T1) && T1Quals)
3561        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3562      if (isa<ArrayType>(T2) && T2Quals)
3563        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3564      if (T2.isMoreQualifiedThan(T1))
3565        return ImplicitConversionSequence::Better;
3566      else if (T1.isMoreQualifiedThan(T2))
3567        return ImplicitConversionSequence::Worse;
3568    }
3569  }
3570
3571  // In Microsoft mode, prefer an integral conversion to a
3572  // floating-to-integral conversion if the integral conversion
3573  // is between types of the same size.
3574  // For example:
3575  // void f(float);
3576  // void f(int);
3577  // int main {
3578  //    long a;
3579  //    f(a);
3580  // }
3581  // Here, MSVC will call f(int) instead of generating a compile error
3582  // as clang will do in standard mode.
3583  if (S.getLangOpts().MicrosoftMode &&
3584      SCS1.Second == ICK_Integral_Conversion &&
3585      SCS2.Second == ICK_Floating_Integral &&
3586      S.Context.getTypeSize(SCS1.getFromType()) ==
3587      S.Context.getTypeSize(SCS1.getToType(2)))
3588    return ImplicitConversionSequence::Better;
3589
3590  return ImplicitConversionSequence::Indistinguishable;
3591}
3592
3593/// CompareQualificationConversions - Compares two standard conversion
3594/// sequences to determine whether they can be ranked based on their
3595/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3596ImplicitConversionSequence::CompareKind
3597CompareQualificationConversions(Sema &S,
3598                                const StandardConversionSequence& SCS1,
3599                                const StandardConversionSequence& SCS2) {
3600  // C++ 13.3.3.2p3:
3601  //  -- S1 and S2 differ only in their qualification conversion and
3602  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3603  //     cv-qualification signature of type T1 is a proper subset of
3604  //     the cv-qualification signature of type T2, and S1 is not the
3605  //     deprecated string literal array-to-pointer conversion (4.2).
3606  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3607      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3608    return ImplicitConversionSequence::Indistinguishable;
3609
3610  // FIXME: the example in the standard doesn't use a qualification
3611  // conversion (!)
3612  QualType T1 = SCS1.getToType(2);
3613  QualType T2 = SCS2.getToType(2);
3614  T1 = S.Context.getCanonicalType(T1);
3615  T2 = S.Context.getCanonicalType(T2);
3616  Qualifiers T1Quals, T2Quals;
3617  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3618  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3619
3620  // If the types are the same, we won't learn anything by unwrapped
3621  // them.
3622  if (UnqualT1 == UnqualT2)
3623    return ImplicitConversionSequence::Indistinguishable;
3624
3625  // If the type is an array type, promote the element qualifiers to the type
3626  // for comparison.
3627  if (isa<ArrayType>(T1) && T1Quals)
3628    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3629  if (isa<ArrayType>(T2) && T2Quals)
3630    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3631
3632  ImplicitConversionSequence::CompareKind Result
3633    = ImplicitConversionSequence::Indistinguishable;
3634
3635  // Objective-C++ ARC:
3636  //   Prefer qualification conversions not involving a change in lifetime
3637  //   to qualification conversions that do not change lifetime.
3638  if (SCS1.QualificationIncludesObjCLifetime !=
3639                                      SCS2.QualificationIncludesObjCLifetime) {
3640    Result = SCS1.QualificationIncludesObjCLifetime
3641               ? ImplicitConversionSequence::Worse
3642               : ImplicitConversionSequence::Better;
3643  }
3644
3645  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3646    // Within each iteration of the loop, we check the qualifiers to
3647    // determine if this still looks like a qualification
3648    // conversion. Then, if all is well, we unwrap one more level of
3649    // pointers or pointers-to-members and do it all again
3650    // until there are no more pointers or pointers-to-members left
3651    // to unwrap. This essentially mimics what
3652    // IsQualificationConversion does, but here we're checking for a
3653    // strict subset of qualifiers.
3654    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3655      // The qualifiers are the same, so this doesn't tell us anything
3656      // about how the sequences rank.
3657      ;
3658    else if (T2.isMoreQualifiedThan(T1)) {
3659      // T1 has fewer qualifiers, so it could be the better sequence.
3660      if (Result == ImplicitConversionSequence::Worse)
3661        // Neither has qualifiers that are a subset of the other's
3662        // qualifiers.
3663        return ImplicitConversionSequence::Indistinguishable;
3664
3665      Result = ImplicitConversionSequence::Better;
3666    } else if (T1.isMoreQualifiedThan(T2)) {
3667      // T2 has fewer qualifiers, so it could be the better sequence.
3668      if (Result == ImplicitConversionSequence::Better)
3669        // Neither has qualifiers that are a subset of the other's
3670        // qualifiers.
3671        return ImplicitConversionSequence::Indistinguishable;
3672
3673      Result = ImplicitConversionSequence::Worse;
3674    } else {
3675      // Qualifiers are disjoint.
3676      return ImplicitConversionSequence::Indistinguishable;
3677    }
3678
3679    // If the types after this point are equivalent, we're done.
3680    if (S.Context.hasSameUnqualifiedType(T1, T2))
3681      break;
3682  }
3683
3684  // Check that the winning standard conversion sequence isn't using
3685  // the deprecated string literal array to pointer conversion.
3686  switch (Result) {
3687  case ImplicitConversionSequence::Better:
3688    if (SCS1.DeprecatedStringLiteralToCharPtr)
3689      Result = ImplicitConversionSequence::Indistinguishable;
3690    break;
3691
3692  case ImplicitConversionSequence::Indistinguishable:
3693    break;
3694
3695  case ImplicitConversionSequence::Worse:
3696    if (SCS2.DeprecatedStringLiteralToCharPtr)
3697      Result = ImplicitConversionSequence::Indistinguishable;
3698    break;
3699  }
3700
3701  return Result;
3702}
3703
3704/// CompareDerivedToBaseConversions - Compares two standard conversion
3705/// sequences to determine whether they can be ranked based on their
3706/// various kinds of derived-to-base conversions (C++
3707/// [over.ics.rank]p4b3).  As part of these checks, we also look at
3708/// conversions between Objective-C interface types.
3709ImplicitConversionSequence::CompareKind
3710CompareDerivedToBaseConversions(Sema &S,
3711                                const StandardConversionSequence& SCS1,
3712                                const StandardConversionSequence& SCS2) {
3713  QualType FromType1 = SCS1.getFromType();
3714  QualType ToType1 = SCS1.getToType(1);
3715  QualType FromType2 = SCS2.getFromType();
3716  QualType ToType2 = SCS2.getToType(1);
3717
3718  // Adjust the types we're converting from via the array-to-pointer
3719  // conversion, if we need to.
3720  if (SCS1.First == ICK_Array_To_Pointer)
3721    FromType1 = S.Context.getArrayDecayedType(FromType1);
3722  if (SCS2.First == ICK_Array_To_Pointer)
3723    FromType2 = S.Context.getArrayDecayedType(FromType2);
3724
3725  // Canonicalize all of the types.
3726  FromType1 = S.Context.getCanonicalType(FromType1);
3727  ToType1 = S.Context.getCanonicalType(ToType1);
3728  FromType2 = S.Context.getCanonicalType(FromType2);
3729  ToType2 = S.Context.getCanonicalType(ToType2);
3730
3731  // C++ [over.ics.rank]p4b3:
3732  //
3733  //   If class B is derived directly or indirectly from class A and
3734  //   class C is derived directly or indirectly from B,
3735  //
3736  // Compare based on pointer conversions.
3737  if (SCS1.Second == ICK_Pointer_Conversion &&
3738      SCS2.Second == ICK_Pointer_Conversion &&
3739      /*FIXME: Remove if Objective-C id conversions get their own rank*/
3740      FromType1->isPointerType() && FromType2->isPointerType() &&
3741      ToType1->isPointerType() && ToType2->isPointerType()) {
3742    QualType FromPointee1
3743      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3744    QualType ToPointee1
3745      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3746    QualType FromPointee2
3747      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3748    QualType ToPointee2
3749      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3750
3751    //   -- conversion of C* to B* is better than conversion of C* to A*,
3752    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3753      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3754        return ImplicitConversionSequence::Better;
3755      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3756        return ImplicitConversionSequence::Worse;
3757    }
3758
3759    //   -- conversion of B* to A* is better than conversion of C* to A*,
3760    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3761      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3762        return ImplicitConversionSequence::Better;
3763      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3764        return ImplicitConversionSequence::Worse;
3765    }
3766  } else if (SCS1.Second == ICK_Pointer_Conversion &&
3767             SCS2.Second == ICK_Pointer_Conversion) {
3768    const ObjCObjectPointerType *FromPtr1
3769      = FromType1->getAs<ObjCObjectPointerType>();
3770    const ObjCObjectPointerType *FromPtr2
3771      = FromType2->getAs<ObjCObjectPointerType>();
3772    const ObjCObjectPointerType *ToPtr1
3773      = ToType1->getAs<ObjCObjectPointerType>();
3774    const ObjCObjectPointerType *ToPtr2
3775      = ToType2->getAs<ObjCObjectPointerType>();
3776
3777    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3778      // Apply the same conversion ranking rules for Objective-C pointer types
3779      // that we do for C++ pointers to class types. However, we employ the
3780      // Objective-C pseudo-subtyping relationship used for assignment of
3781      // Objective-C pointer types.
3782      bool FromAssignLeft
3783        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3784      bool FromAssignRight
3785        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3786      bool ToAssignLeft
3787        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3788      bool ToAssignRight
3789        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3790
3791      // A conversion to an a non-id object pointer type or qualified 'id'
3792      // type is better than a conversion to 'id'.
3793      if (ToPtr1->isObjCIdType() &&
3794          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3795        return ImplicitConversionSequence::Worse;
3796      if (ToPtr2->isObjCIdType() &&
3797          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3798        return ImplicitConversionSequence::Better;
3799
3800      // A conversion to a non-id object pointer type is better than a
3801      // conversion to a qualified 'id' type
3802      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3803        return ImplicitConversionSequence::Worse;
3804      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3805        return ImplicitConversionSequence::Better;
3806
3807      // A conversion to an a non-Class object pointer type or qualified 'Class'
3808      // type is better than a conversion to 'Class'.
3809      if (ToPtr1->isObjCClassType() &&
3810          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3811        return ImplicitConversionSequence::Worse;
3812      if (ToPtr2->isObjCClassType() &&
3813          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3814        return ImplicitConversionSequence::Better;
3815
3816      // A conversion to a non-Class object pointer type is better than a
3817      // conversion to a qualified 'Class' type.
3818      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3819        return ImplicitConversionSequence::Worse;
3820      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3821        return ImplicitConversionSequence::Better;
3822
3823      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3824      if (S.Context.hasSameType(FromType1, FromType2) &&
3825          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3826          (ToAssignLeft != ToAssignRight))
3827        return ToAssignLeft? ImplicitConversionSequence::Worse
3828                           : ImplicitConversionSequence::Better;
3829
3830      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3831      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3832          (FromAssignLeft != FromAssignRight))
3833        return FromAssignLeft? ImplicitConversionSequence::Better
3834        : ImplicitConversionSequence::Worse;
3835    }
3836  }
3837
3838  // Ranking of member-pointer types.
3839  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3840      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3841      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3842    const MemberPointerType * FromMemPointer1 =
3843                                        FromType1->getAs<MemberPointerType>();
3844    const MemberPointerType * ToMemPointer1 =
3845                                          ToType1->getAs<MemberPointerType>();
3846    const MemberPointerType * FromMemPointer2 =
3847                                          FromType2->getAs<MemberPointerType>();
3848    const MemberPointerType * ToMemPointer2 =
3849                                          ToType2->getAs<MemberPointerType>();
3850    const Type *FromPointeeType1 = FromMemPointer1->getClass();
3851    const Type *ToPointeeType1 = ToMemPointer1->getClass();
3852    const Type *FromPointeeType2 = FromMemPointer2->getClass();
3853    const Type *ToPointeeType2 = ToMemPointer2->getClass();
3854    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3855    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3856    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3857    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3858    // conversion of A::* to B::* is better than conversion of A::* to C::*,
3859    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3860      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3861        return ImplicitConversionSequence::Worse;
3862      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3863        return ImplicitConversionSequence::Better;
3864    }
3865    // conversion of B::* to C::* is better than conversion of A::* to C::*
3866    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3867      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3868        return ImplicitConversionSequence::Better;
3869      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3870        return ImplicitConversionSequence::Worse;
3871    }
3872  }
3873
3874  if (SCS1.Second == ICK_Derived_To_Base) {
3875    //   -- conversion of C to B is better than conversion of C to A,
3876    //   -- binding of an expression of type C to a reference of type
3877    //      B& is better than binding an expression of type C to a
3878    //      reference of type A&,
3879    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3880        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3881      if (S.IsDerivedFrom(ToType1, ToType2))
3882        return ImplicitConversionSequence::Better;
3883      else if (S.IsDerivedFrom(ToType2, ToType1))
3884        return ImplicitConversionSequence::Worse;
3885    }
3886
3887    //   -- conversion of B to A is better than conversion of C to A.
3888    //   -- binding of an expression of type B to a reference of type
3889    //      A& is better than binding an expression of type C to a
3890    //      reference of type A&,
3891    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3892        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3893      if (S.IsDerivedFrom(FromType2, FromType1))
3894        return ImplicitConversionSequence::Better;
3895      else if (S.IsDerivedFrom(FromType1, FromType2))
3896        return ImplicitConversionSequence::Worse;
3897    }
3898  }
3899
3900  return ImplicitConversionSequence::Indistinguishable;
3901}
3902
3903/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3904/// C++ class.
3905static bool isTypeValid(QualType T) {
3906  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3907    return !Record->isInvalidDecl();
3908
3909  return true;
3910}
3911
3912/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3913/// determine whether they are reference-related,
3914/// reference-compatible, reference-compatible with added
3915/// qualification, or incompatible, for use in C++ initialization by
3916/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3917/// type, and the first type (T1) is the pointee type of the reference
3918/// type being initialized.
3919Sema::ReferenceCompareResult
3920Sema::CompareReferenceRelationship(SourceLocation Loc,
3921                                   QualType OrigT1, QualType OrigT2,
3922                                   bool &DerivedToBase,
3923                                   bool &ObjCConversion,
3924                                   bool &ObjCLifetimeConversion) {
3925  assert(!OrigT1->isReferenceType() &&
3926    "T1 must be the pointee type of the reference type");
3927  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3928
3929  QualType T1 = Context.getCanonicalType(OrigT1);
3930  QualType T2 = Context.getCanonicalType(OrigT2);
3931  Qualifiers T1Quals, T2Quals;
3932  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3933  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3934
3935  // C++ [dcl.init.ref]p4:
3936  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3937  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3938  //   T1 is a base class of T2.
3939  DerivedToBase = false;
3940  ObjCConversion = false;
3941  ObjCLifetimeConversion = false;
3942  if (UnqualT1 == UnqualT2) {
3943    // Nothing to do.
3944  } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3945             isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3946             IsDerivedFrom(UnqualT2, UnqualT1))
3947    DerivedToBase = true;
3948  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3949           UnqualT2->isObjCObjectOrInterfaceType() &&
3950           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3951    ObjCConversion = true;
3952  else
3953    return Ref_Incompatible;
3954
3955  // At this point, we know that T1 and T2 are reference-related (at
3956  // least).
3957
3958  // If the type is an array type, promote the element qualifiers to the type
3959  // for comparison.
3960  if (isa<ArrayType>(T1) && T1Quals)
3961    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3962  if (isa<ArrayType>(T2) && T2Quals)
3963    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3964
3965  // C++ [dcl.init.ref]p4:
3966  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3967  //   reference-related to T2 and cv1 is the same cv-qualification
3968  //   as, or greater cv-qualification than, cv2. For purposes of
3969  //   overload resolution, cases for which cv1 is greater
3970  //   cv-qualification than cv2 are identified as
3971  //   reference-compatible with added qualification (see 13.3.3.2).
3972  //
3973  // Note that we also require equivalence of Objective-C GC and address-space
3974  // qualifiers when performing these computations, so that e.g., an int in
3975  // address space 1 is not reference-compatible with an int in address
3976  // space 2.
3977  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3978      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3979    T1Quals.removeObjCLifetime();
3980    T2Quals.removeObjCLifetime();
3981    ObjCLifetimeConversion = true;
3982  }
3983
3984  if (T1Quals == T2Quals)
3985    return Ref_Compatible;
3986  else if (T1Quals.compatiblyIncludes(T2Quals))
3987    return Ref_Compatible_With_Added_Qualification;
3988  else
3989    return Ref_Related;
3990}
3991
3992/// \brief Look for a user-defined conversion to an value reference-compatible
3993///        with DeclType. Return true if something definite is found.
3994static bool
3995FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3996                         QualType DeclType, SourceLocation DeclLoc,
3997                         Expr *Init, QualType T2, bool AllowRvalues,
3998                         bool AllowExplicit) {
3999  assert(T2->isRecordType() && "Can only find conversions of record types.");
4000  CXXRecordDecl *T2RecordDecl
4001    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4002
4003  OverloadCandidateSet CandidateSet(DeclLoc);
4004  std::pair<CXXRecordDecl::conversion_iterator,
4005            CXXRecordDecl::conversion_iterator>
4006    Conversions = T2RecordDecl->getVisibleConversionFunctions();
4007  for (CXXRecordDecl::conversion_iterator
4008         I = Conversions.first, E = Conversions.second; I != E; ++I) {
4009    NamedDecl *D = *I;
4010    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4011    if (isa<UsingShadowDecl>(D))
4012      D = cast<UsingShadowDecl>(D)->getTargetDecl();
4013
4014    FunctionTemplateDecl *ConvTemplate
4015      = dyn_cast<FunctionTemplateDecl>(D);
4016    CXXConversionDecl *Conv;
4017    if (ConvTemplate)
4018      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4019    else
4020      Conv = cast<CXXConversionDecl>(D);
4021
4022    // If this is an explicit conversion, and we're not allowed to consider
4023    // explicit conversions, skip it.
4024    if (!AllowExplicit && Conv->isExplicit())
4025      continue;
4026
4027    if (AllowRvalues) {
4028      bool DerivedToBase = false;
4029      bool ObjCConversion = false;
4030      bool ObjCLifetimeConversion = false;
4031
4032      // If we are initializing an rvalue reference, don't permit conversion
4033      // functions that return lvalues.
4034      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4035        const ReferenceType *RefType
4036          = Conv->getConversionType()->getAs<LValueReferenceType>();
4037        if (RefType && !RefType->getPointeeType()->isFunctionType())
4038          continue;
4039      }
4040
4041      if (!ConvTemplate &&
4042          S.CompareReferenceRelationship(
4043            DeclLoc,
4044            Conv->getConversionType().getNonReferenceType()
4045              .getUnqualifiedType(),
4046            DeclType.getNonReferenceType().getUnqualifiedType(),
4047            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4048          Sema::Ref_Incompatible)
4049        continue;
4050    } else {
4051      // If the conversion function doesn't return a reference type,
4052      // it can't be considered for this conversion. An rvalue reference
4053      // is only acceptable if its referencee is a function type.
4054
4055      const ReferenceType *RefType =
4056        Conv->getConversionType()->getAs<ReferenceType>();
4057      if (!RefType ||
4058          (!RefType->isLValueReferenceType() &&
4059           !RefType->getPointeeType()->isFunctionType()))
4060        continue;
4061    }
4062
4063    if (ConvTemplate)
4064      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4065                                       Init, DeclType, CandidateSet);
4066    else
4067      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4068                               DeclType, CandidateSet);
4069  }
4070
4071  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4072
4073  OverloadCandidateSet::iterator Best;
4074  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4075  case OR_Success:
4076    // C++ [over.ics.ref]p1:
4077    //
4078    //   [...] If the parameter binds directly to the result of
4079    //   applying a conversion function to the argument
4080    //   expression, the implicit conversion sequence is a
4081    //   user-defined conversion sequence (13.3.3.1.2), with the
4082    //   second standard conversion sequence either an identity
4083    //   conversion or, if the conversion function returns an
4084    //   entity of a type that is a derived class of the parameter
4085    //   type, a derived-to-base Conversion.
4086    if (!Best->FinalConversion.DirectBinding)
4087      return false;
4088
4089    ICS.setUserDefined();
4090    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4091    ICS.UserDefined.After = Best->FinalConversion;
4092    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4093    ICS.UserDefined.ConversionFunction = Best->Function;
4094    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4095    ICS.UserDefined.EllipsisConversion = false;
4096    assert(ICS.UserDefined.After.ReferenceBinding &&
4097           ICS.UserDefined.After.DirectBinding &&
4098           "Expected a direct reference binding!");
4099    return true;
4100
4101  case OR_Ambiguous:
4102    ICS.setAmbiguous();
4103    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4104         Cand != CandidateSet.end(); ++Cand)
4105      if (Cand->Viable)
4106        ICS.Ambiguous.addConversion(Cand->Function);
4107    return true;
4108
4109  case OR_No_Viable_Function:
4110  case OR_Deleted:
4111    // There was no suitable conversion, or we found a deleted
4112    // conversion; continue with other checks.
4113    return false;
4114  }
4115
4116  llvm_unreachable("Invalid OverloadResult!");
4117}
4118
4119/// \brief Compute an implicit conversion sequence for reference
4120/// initialization.
4121static ImplicitConversionSequence
4122TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4123                 SourceLocation DeclLoc,
4124                 bool SuppressUserConversions,
4125                 bool AllowExplicit) {
4126  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4127
4128  // Most paths end in a failed conversion.
4129  ImplicitConversionSequence ICS;
4130  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4131
4132  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4133  QualType T2 = Init->getType();
4134
4135  // If the initializer is the address of an overloaded function, try
4136  // to resolve the overloaded function. If all goes well, T2 is the
4137  // type of the resulting function.
4138  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4139    DeclAccessPair Found;
4140    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4141                                                                false, Found))
4142      T2 = Fn->getType();
4143  }
4144
4145  // Compute some basic properties of the types and the initializer.
4146  bool isRValRef = DeclType->isRValueReferenceType();
4147  bool DerivedToBase = false;
4148  bool ObjCConversion = false;
4149  bool ObjCLifetimeConversion = false;
4150  Expr::Classification InitCategory = Init->Classify(S.Context);
4151  Sema::ReferenceCompareResult RefRelationship
4152    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4153                                     ObjCConversion, ObjCLifetimeConversion);
4154
4155
4156  // C++0x [dcl.init.ref]p5:
4157  //   A reference to type "cv1 T1" is initialized by an expression
4158  //   of type "cv2 T2" as follows:
4159
4160  //     -- If reference is an lvalue reference and the initializer expression
4161  if (!isRValRef) {
4162    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4163    //        reference-compatible with "cv2 T2," or
4164    //
4165    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4166    if (InitCategory.isLValue() &&
4167        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4168      // C++ [over.ics.ref]p1:
4169      //   When a parameter of reference type binds directly (8.5.3)
4170      //   to an argument expression, the implicit conversion sequence
4171      //   is the identity conversion, unless the argument expression
4172      //   has a type that is a derived class of the parameter type,
4173      //   in which case the implicit conversion sequence is a
4174      //   derived-to-base Conversion (13.3.3.1).
4175      ICS.setStandard();
4176      ICS.Standard.First = ICK_Identity;
4177      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4178                         : ObjCConversion? ICK_Compatible_Conversion
4179                         : ICK_Identity;
4180      ICS.Standard.Third = ICK_Identity;
4181      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4182      ICS.Standard.setToType(0, T2);
4183      ICS.Standard.setToType(1, T1);
4184      ICS.Standard.setToType(2, T1);
4185      ICS.Standard.ReferenceBinding = true;
4186      ICS.Standard.DirectBinding = true;
4187      ICS.Standard.IsLvalueReference = !isRValRef;
4188      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4189      ICS.Standard.BindsToRvalue = false;
4190      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4191      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4192      ICS.Standard.CopyConstructor = 0;
4193
4194      // Nothing more to do: the inaccessibility/ambiguity check for
4195      // derived-to-base conversions is suppressed when we're
4196      // computing the implicit conversion sequence (C++
4197      // [over.best.ics]p2).
4198      return ICS;
4199    }
4200
4201    //       -- has a class type (i.e., T2 is a class type), where T1 is
4202    //          not reference-related to T2, and can be implicitly
4203    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4204    //          is reference-compatible with "cv3 T3" 92) (this
4205    //          conversion is selected by enumerating the applicable
4206    //          conversion functions (13.3.1.6) and choosing the best
4207    //          one through overload resolution (13.3)),
4208    if (!SuppressUserConversions && T2->isRecordType() &&
4209        !S.RequireCompleteType(DeclLoc, T2, 0) &&
4210        RefRelationship == Sema::Ref_Incompatible) {
4211      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4212                                   Init, T2, /*AllowRvalues=*/false,
4213                                   AllowExplicit))
4214        return ICS;
4215    }
4216  }
4217
4218  //     -- Otherwise, the reference shall be an lvalue reference to a
4219  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4220  //        shall be an rvalue reference.
4221  //
4222  // We actually handle one oddity of C++ [over.ics.ref] at this
4223  // point, which is that, due to p2 (which short-circuits reference
4224  // binding by only attempting a simple conversion for non-direct
4225  // bindings) and p3's strange wording, we allow a const volatile
4226  // reference to bind to an rvalue. Hence the check for the presence
4227  // of "const" rather than checking for "const" being the only
4228  // qualifier.
4229  // This is also the point where rvalue references and lvalue inits no longer
4230  // go together.
4231  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4232    return ICS;
4233
4234  //       -- If the initializer expression
4235  //
4236  //            -- is an xvalue, class prvalue, array prvalue or function
4237  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4238  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4239      (InitCategory.isXValue() ||
4240      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4241      (InitCategory.isLValue() && T2->isFunctionType()))) {
4242    ICS.setStandard();
4243    ICS.Standard.First = ICK_Identity;
4244    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4245                      : ObjCConversion? ICK_Compatible_Conversion
4246                      : ICK_Identity;
4247    ICS.Standard.Third = ICK_Identity;
4248    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4249    ICS.Standard.setToType(0, T2);
4250    ICS.Standard.setToType(1, T1);
4251    ICS.Standard.setToType(2, T1);
4252    ICS.Standard.ReferenceBinding = true;
4253    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4254    // binding unless we're binding to a class prvalue.
4255    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4256    // allow the use of rvalue references in C++98/03 for the benefit of
4257    // standard library implementors; therefore, we need the xvalue check here.
4258    ICS.Standard.DirectBinding =
4259      S.getLangOpts().CPlusPlus11 ||
4260      (InitCategory.isPRValue() && !T2->isRecordType());
4261    ICS.Standard.IsLvalueReference = !isRValRef;
4262    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4263    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4264    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4265    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4266    ICS.Standard.CopyConstructor = 0;
4267    return ICS;
4268  }
4269
4270  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4271  //               reference-related to T2, and can be implicitly converted to
4272  //               an xvalue, class prvalue, or function lvalue of type
4273  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4274  //               "cv3 T3",
4275  //
4276  //          then the reference is bound to the value of the initializer
4277  //          expression in the first case and to the result of the conversion
4278  //          in the second case (or, in either case, to an appropriate base
4279  //          class subobject).
4280  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4281      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4282      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4283                               Init, T2, /*AllowRvalues=*/true,
4284                               AllowExplicit)) {
4285    // In the second case, if the reference is an rvalue reference
4286    // and the second standard conversion sequence of the
4287    // user-defined conversion sequence includes an lvalue-to-rvalue
4288    // conversion, the program is ill-formed.
4289    if (ICS.isUserDefined() && isRValRef &&
4290        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4291      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4292
4293    return ICS;
4294  }
4295
4296  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4297  //          initialized from the initializer expression using the
4298  //          rules for a non-reference copy initialization (8.5). The
4299  //          reference is then bound to the temporary. If T1 is
4300  //          reference-related to T2, cv1 must be the same
4301  //          cv-qualification as, or greater cv-qualification than,
4302  //          cv2; otherwise, the program is ill-formed.
4303  if (RefRelationship == Sema::Ref_Related) {
4304    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4305    // we would be reference-compatible or reference-compatible with
4306    // added qualification. But that wasn't the case, so the reference
4307    // initialization fails.
4308    //
4309    // Note that we only want to check address spaces and cvr-qualifiers here.
4310    // ObjC GC and lifetime qualifiers aren't important.
4311    Qualifiers T1Quals = T1.getQualifiers();
4312    Qualifiers T2Quals = T2.getQualifiers();
4313    T1Quals.removeObjCGCAttr();
4314    T1Quals.removeObjCLifetime();
4315    T2Quals.removeObjCGCAttr();
4316    T2Quals.removeObjCLifetime();
4317    if (!T1Quals.compatiblyIncludes(T2Quals))
4318      return ICS;
4319  }
4320
4321  // If at least one of the types is a class type, the types are not
4322  // related, and we aren't allowed any user conversions, the
4323  // reference binding fails. This case is important for breaking
4324  // recursion, since TryImplicitConversion below will attempt to
4325  // create a temporary through the use of a copy constructor.
4326  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4327      (T1->isRecordType() || T2->isRecordType()))
4328    return ICS;
4329
4330  // If T1 is reference-related to T2 and the reference is an rvalue
4331  // reference, the initializer expression shall not be an lvalue.
4332  if (RefRelationship >= Sema::Ref_Related &&
4333      isRValRef && Init->Classify(S.Context).isLValue())
4334    return ICS;
4335
4336  // C++ [over.ics.ref]p2:
4337  //   When a parameter of reference type is not bound directly to
4338  //   an argument expression, the conversion sequence is the one
4339  //   required to convert the argument expression to the
4340  //   underlying type of the reference according to
4341  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4342  //   to copy-initializing a temporary of the underlying type with
4343  //   the argument expression. Any difference in top-level
4344  //   cv-qualification is subsumed by the initialization itself
4345  //   and does not constitute a conversion.
4346  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4347                              /*AllowExplicit=*/false,
4348                              /*InOverloadResolution=*/false,
4349                              /*CStyle=*/false,
4350                              /*AllowObjCWritebackConversion=*/false);
4351
4352  // Of course, that's still a reference binding.
4353  if (ICS.isStandard()) {
4354    ICS.Standard.ReferenceBinding = true;
4355    ICS.Standard.IsLvalueReference = !isRValRef;
4356    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4357    ICS.Standard.BindsToRvalue = true;
4358    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4359    ICS.Standard.ObjCLifetimeConversionBinding = false;
4360  } else if (ICS.isUserDefined()) {
4361    // Don't allow rvalue references to bind to lvalues.
4362    if (DeclType->isRValueReferenceType()) {
4363      if (const ReferenceType *RefType
4364            = ICS.UserDefined.ConversionFunction->getResultType()
4365                ->getAs<LValueReferenceType>()) {
4366        if (!RefType->getPointeeType()->isFunctionType()) {
4367          ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4368                     DeclType);
4369          return ICS;
4370        }
4371      }
4372    }
4373
4374    ICS.UserDefined.After.ReferenceBinding = true;
4375    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4376    ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4377    ICS.UserDefined.After.BindsToRvalue = true;
4378    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4379    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4380  }
4381
4382  return ICS;
4383}
4384
4385static ImplicitConversionSequence
4386TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4387                      bool SuppressUserConversions,
4388                      bool InOverloadResolution,
4389                      bool AllowObjCWritebackConversion,
4390                      bool AllowExplicit = false);
4391
4392/// TryListConversion - Try to copy-initialize a value of type ToType from the
4393/// initializer list From.
4394static ImplicitConversionSequence
4395TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4396                  bool SuppressUserConversions,
4397                  bool InOverloadResolution,
4398                  bool AllowObjCWritebackConversion) {
4399  // C++11 [over.ics.list]p1:
4400  //   When an argument is an initializer list, it is not an expression and
4401  //   special rules apply for converting it to a parameter type.
4402
4403  ImplicitConversionSequence Result;
4404  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4405
4406  // We need a complete type for what follows. Incomplete types can never be
4407  // initialized from init lists.
4408  if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4409    return Result;
4410
4411  // C++11 [over.ics.list]p2:
4412  //   If the parameter type is std::initializer_list<X> or "array of X" and
4413  //   all the elements can be implicitly converted to X, the implicit
4414  //   conversion sequence is the worst conversion necessary to convert an
4415  //   element of the list to X.
4416  bool toStdInitializerList = false;
4417  QualType X;
4418  if (ToType->isArrayType())
4419    X = S.Context.getAsArrayType(ToType)->getElementType();
4420  else
4421    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4422  if (!X.isNull()) {
4423    for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4424      Expr *Init = From->getInit(i);
4425      ImplicitConversionSequence ICS =
4426          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4427                                InOverloadResolution,
4428                                AllowObjCWritebackConversion);
4429      // If a single element isn't convertible, fail.
4430      if (ICS.isBad()) {
4431        Result = ICS;
4432        break;
4433      }
4434      // Otherwise, look for the worst conversion.
4435      if (Result.isBad() ||
4436          CompareImplicitConversionSequences(S, ICS, Result) ==
4437              ImplicitConversionSequence::Worse)
4438        Result = ICS;
4439    }
4440
4441    // For an empty list, we won't have computed any conversion sequence.
4442    // Introduce the identity conversion sequence.
4443    if (From->getNumInits() == 0) {
4444      Result.setStandard();
4445      Result.Standard.setAsIdentityConversion();
4446      Result.Standard.setFromType(ToType);
4447      Result.Standard.setAllToTypes(ToType);
4448    }
4449
4450    Result.setStdInitializerListElement(toStdInitializerList);
4451    return Result;
4452  }
4453
4454  // C++11 [over.ics.list]p3:
4455  //   Otherwise, if the parameter is a non-aggregate class X and overload
4456  //   resolution chooses a single best constructor [...] the implicit
4457  //   conversion sequence is a user-defined conversion sequence. If multiple
4458  //   constructors are viable but none is better than the others, the
4459  //   implicit conversion sequence is a user-defined conversion sequence.
4460  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4461    // This function can deal with initializer lists.
4462    return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4463                                    /*AllowExplicit=*/false,
4464                                    InOverloadResolution, /*CStyle=*/false,
4465                                    AllowObjCWritebackConversion);
4466  }
4467
4468  // C++11 [over.ics.list]p4:
4469  //   Otherwise, if the parameter has an aggregate type which can be
4470  //   initialized from the initializer list [...] the implicit conversion
4471  //   sequence is a user-defined conversion sequence.
4472  if (ToType->isAggregateType()) {
4473    // Type is an aggregate, argument is an init list. At this point it comes
4474    // down to checking whether the initialization works.
4475    // FIXME: Find out whether this parameter is consumed or not.
4476    InitializedEntity Entity =
4477        InitializedEntity::InitializeParameter(S.Context, ToType,
4478                                               /*Consumed=*/false);
4479    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4480      Result.setUserDefined();
4481      Result.UserDefined.Before.setAsIdentityConversion();
4482      // Initializer lists don't have a type.
4483      Result.UserDefined.Before.setFromType(QualType());
4484      Result.UserDefined.Before.setAllToTypes(QualType());
4485
4486      Result.UserDefined.After.setAsIdentityConversion();
4487      Result.UserDefined.After.setFromType(ToType);
4488      Result.UserDefined.After.setAllToTypes(ToType);
4489      Result.UserDefined.ConversionFunction = 0;
4490    }
4491    return Result;
4492  }
4493
4494  // C++11 [over.ics.list]p5:
4495  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4496  if (ToType->isReferenceType()) {
4497    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4498    // mention initializer lists in any way. So we go by what list-
4499    // initialization would do and try to extrapolate from that.
4500
4501    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4502
4503    // If the initializer list has a single element that is reference-related
4504    // to the parameter type, we initialize the reference from that.
4505    if (From->getNumInits() == 1) {
4506      Expr *Init = From->getInit(0);
4507
4508      QualType T2 = Init->getType();
4509
4510      // If the initializer is the address of an overloaded function, try
4511      // to resolve the overloaded function. If all goes well, T2 is the
4512      // type of the resulting function.
4513      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4514        DeclAccessPair Found;
4515        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4516                                   Init, ToType, false, Found))
4517          T2 = Fn->getType();
4518      }
4519
4520      // Compute some basic properties of the types and the initializer.
4521      bool dummy1 = false;
4522      bool dummy2 = false;
4523      bool dummy3 = false;
4524      Sema::ReferenceCompareResult RefRelationship
4525        = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4526                                         dummy2, dummy3);
4527
4528      if (RefRelationship >= Sema::Ref_Related) {
4529        return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4530                                SuppressUserConversions,
4531                                /*AllowExplicit=*/false);
4532      }
4533    }
4534
4535    // Otherwise, we bind the reference to a temporary created from the
4536    // initializer list.
4537    Result = TryListConversion(S, From, T1, SuppressUserConversions,
4538                               InOverloadResolution,
4539                               AllowObjCWritebackConversion);
4540    if (Result.isFailure())
4541      return Result;
4542    assert(!Result.isEllipsis() &&
4543           "Sub-initialization cannot result in ellipsis conversion.");
4544
4545    // Can we even bind to a temporary?
4546    if (ToType->isRValueReferenceType() ||
4547        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4548      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4549                                            Result.UserDefined.After;
4550      SCS.ReferenceBinding = true;
4551      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4552      SCS.BindsToRvalue = true;
4553      SCS.BindsToFunctionLvalue = false;
4554      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4555      SCS.ObjCLifetimeConversionBinding = false;
4556    } else
4557      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4558                    From, ToType);
4559    return Result;
4560  }
4561
4562  // C++11 [over.ics.list]p6:
4563  //   Otherwise, if the parameter type is not a class:
4564  if (!ToType->isRecordType()) {
4565    //    - if the initializer list has one element, the implicit conversion
4566    //      sequence is the one required to convert the element to the
4567    //      parameter type.
4568    unsigned NumInits = From->getNumInits();
4569    if (NumInits == 1)
4570      Result = TryCopyInitialization(S, From->getInit(0), ToType,
4571                                     SuppressUserConversions,
4572                                     InOverloadResolution,
4573                                     AllowObjCWritebackConversion);
4574    //    - if the initializer list has no elements, the implicit conversion
4575    //      sequence is the identity conversion.
4576    else if (NumInits == 0) {
4577      Result.setStandard();
4578      Result.Standard.setAsIdentityConversion();
4579      Result.Standard.setFromType(ToType);
4580      Result.Standard.setAllToTypes(ToType);
4581    }
4582    return Result;
4583  }
4584
4585  // C++11 [over.ics.list]p7:
4586  //   In all cases other than those enumerated above, no conversion is possible
4587  return Result;
4588}
4589
4590/// TryCopyInitialization - Try to copy-initialize a value of type
4591/// ToType from the expression From. Return the implicit conversion
4592/// sequence required to pass this argument, which may be a bad
4593/// conversion sequence (meaning that the argument cannot be passed to
4594/// a parameter of this type). If @p SuppressUserConversions, then we
4595/// do not permit any user-defined conversion sequences.
4596static ImplicitConversionSequence
4597TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4598                      bool SuppressUserConversions,
4599                      bool InOverloadResolution,
4600                      bool AllowObjCWritebackConversion,
4601                      bool AllowExplicit) {
4602  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4603    return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4604                             InOverloadResolution,AllowObjCWritebackConversion);
4605
4606  if (ToType->isReferenceType())
4607    return TryReferenceInit(S, From, ToType,
4608                            /*FIXME:*/From->getLocStart(),
4609                            SuppressUserConversions,
4610                            AllowExplicit);
4611
4612  return TryImplicitConversion(S, From, ToType,
4613                               SuppressUserConversions,
4614                               /*AllowExplicit=*/false,
4615                               InOverloadResolution,
4616                               /*CStyle=*/false,
4617                               AllowObjCWritebackConversion);
4618}
4619
4620static bool TryCopyInitialization(const CanQualType FromQTy,
4621                                  const CanQualType ToQTy,
4622                                  Sema &S,
4623                                  SourceLocation Loc,
4624                                  ExprValueKind FromVK) {
4625  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4626  ImplicitConversionSequence ICS =
4627    TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4628
4629  return !ICS.isBad();
4630}
4631
4632/// TryObjectArgumentInitialization - Try to initialize the object
4633/// parameter of the given member function (@c Method) from the
4634/// expression @p From.
4635static ImplicitConversionSequence
4636TryObjectArgumentInitialization(Sema &S, QualType FromType,
4637                                Expr::Classification FromClassification,
4638                                CXXMethodDecl *Method,
4639                                CXXRecordDecl *ActingContext) {
4640  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4641  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4642  //                 const volatile object.
4643  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4644    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4645  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4646
4647  // Set up the conversion sequence as a "bad" conversion, to allow us
4648  // to exit early.
4649  ImplicitConversionSequence ICS;
4650
4651  // We need to have an object of class type.
4652  if (const PointerType *PT = FromType->getAs<PointerType>()) {
4653    FromType = PT->getPointeeType();
4654
4655    // When we had a pointer, it's implicitly dereferenced, so we
4656    // better have an lvalue.
4657    assert(FromClassification.isLValue());
4658  }
4659
4660  assert(FromType->isRecordType());
4661
4662  // C++0x [over.match.funcs]p4:
4663  //   For non-static member functions, the type of the implicit object
4664  //   parameter is
4665  //
4666  //     - "lvalue reference to cv X" for functions declared without a
4667  //        ref-qualifier or with the & ref-qualifier
4668  //     - "rvalue reference to cv X" for functions declared with the &&
4669  //        ref-qualifier
4670  //
4671  // where X is the class of which the function is a member and cv is the
4672  // cv-qualification on the member function declaration.
4673  //
4674  // However, when finding an implicit conversion sequence for the argument, we
4675  // are not allowed to create temporaries or perform user-defined conversions
4676  // (C++ [over.match.funcs]p5). We perform a simplified version of
4677  // reference binding here, that allows class rvalues to bind to
4678  // non-constant references.
4679
4680  // First check the qualifiers.
4681  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4682  if (ImplicitParamType.getCVRQualifiers()
4683                                    != FromTypeCanon.getLocalCVRQualifiers() &&
4684      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4685    ICS.setBad(BadConversionSequence::bad_qualifiers,
4686               FromType, ImplicitParamType);
4687    return ICS;
4688  }
4689
4690  // Check that we have either the same type or a derived type. It
4691  // affects the conversion rank.
4692  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4693  ImplicitConversionKind SecondKind;
4694  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4695    SecondKind = ICK_Identity;
4696  } else if (S.IsDerivedFrom(FromType, ClassType))
4697    SecondKind = ICK_Derived_To_Base;
4698  else {
4699    ICS.setBad(BadConversionSequence::unrelated_class,
4700               FromType, ImplicitParamType);
4701    return ICS;
4702  }
4703
4704  // Check the ref-qualifier.
4705  switch (Method->getRefQualifier()) {
4706  case RQ_None:
4707    // Do nothing; we don't care about lvalueness or rvalueness.
4708    break;
4709
4710  case RQ_LValue:
4711    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4712      // non-const lvalue reference cannot bind to an rvalue
4713      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4714                 ImplicitParamType);
4715      return ICS;
4716    }
4717    break;
4718
4719  case RQ_RValue:
4720    if (!FromClassification.isRValue()) {
4721      // rvalue reference cannot bind to an lvalue
4722      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4723                 ImplicitParamType);
4724      return ICS;
4725    }
4726    break;
4727  }
4728
4729  // Success. Mark this as a reference binding.
4730  ICS.setStandard();
4731  ICS.Standard.setAsIdentityConversion();
4732  ICS.Standard.Second = SecondKind;
4733  ICS.Standard.setFromType(FromType);
4734  ICS.Standard.setAllToTypes(ImplicitParamType);
4735  ICS.Standard.ReferenceBinding = true;
4736  ICS.Standard.DirectBinding = true;
4737  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4738  ICS.Standard.BindsToFunctionLvalue = false;
4739  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4740  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4741    = (Method->getRefQualifier() == RQ_None);
4742  return ICS;
4743}
4744
4745/// PerformObjectArgumentInitialization - Perform initialization of
4746/// the implicit object parameter for the given Method with the given
4747/// expression.
4748ExprResult
4749Sema::PerformObjectArgumentInitialization(Expr *From,
4750                                          NestedNameSpecifier *Qualifier,
4751                                          NamedDecl *FoundDecl,
4752                                          CXXMethodDecl *Method) {
4753  QualType FromRecordType, DestType;
4754  QualType ImplicitParamRecordType  =
4755    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4756
4757  Expr::Classification FromClassification;
4758  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4759    FromRecordType = PT->getPointeeType();
4760    DestType = Method->getThisType(Context);
4761    FromClassification = Expr::Classification::makeSimpleLValue();
4762  } else {
4763    FromRecordType = From->getType();
4764    DestType = ImplicitParamRecordType;
4765    FromClassification = From->Classify(Context);
4766  }
4767
4768  // Note that we always use the true parent context when performing
4769  // the actual argument initialization.
4770  ImplicitConversionSequence ICS
4771    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4772                                      Method, Method->getParent());
4773  if (ICS.isBad()) {
4774    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4775      Qualifiers FromQs = FromRecordType.getQualifiers();
4776      Qualifiers ToQs = DestType.getQualifiers();
4777      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4778      if (CVR) {
4779        Diag(From->getLocStart(),
4780             diag::err_member_function_call_bad_cvr)
4781          << Method->getDeclName() << FromRecordType << (CVR - 1)
4782          << From->getSourceRange();
4783        Diag(Method->getLocation(), diag::note_previous_decl)
4784          << Method->getDeclName();
4785        return ExprError();
4786      }
4787    }
4788
4789    return Diag(From->getLocStart(),
4790                diag::err_implicit_object_parameter_init)
4791       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4792  }
4793
4794  if (ICS.Standard.Second == ICK_Derived_To_Base) {
4795    ExprResult FromRes =
4796      PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4797    if (FromRes.isInvalid())
4798      return ExprError();
4799    From = FromRes.take();
4800  }
4801
4802  if (!Context.hasSameType(From->getType(), DestType))
4803    From = ImpCastExprToType(From, DestType, CK_NoOp,
4804                             From->getValueKind()).take();
4805  return Owned(From);
4806}
4807
4808/// TryContextuallyConvertToBool - Attempt to contextually convert the
4809/// expression From to bool (C++0x [conv]p3).
4810static ImplicitConversionSequence
4811TryContextuallyConvertToBool(Sema &S, Expr *From) {
4812  // FIXME: This is pretty broken.
4813  return TryImplicitConversion(S, From, S.Context.BoolTy,
4814                               // FIXME: Are these flags correct?
4815                               /*SuppressUserConversions=*/false,
4816                               /*AllowExplicit=*/true,
4817                               /*InOverloadResolution=*/false,
4818                               /*CStyle=*/false,
4819                               /*AllowObjCWritebackConversion=*/false);
4820}
4821
4822/// PerformContextuallyConvertToBool - Perform a contextual conversion
4823/// of the expression From to bool (C++0x [conv]p3).
4824ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4825  if (checkPlaceholderForOverload(*this, From))
4826    return ExprError();
4827
4828  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4829  if (!ICS.isBad())
4830    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4831
4832  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4833    return Diag(From->getLocStart(),
4834                diag::err_typecheck_bool_condition)
4835                  << From->getType() << From->getSourceRange();
4836  return ExprError();
4837}
4838
4839/// Check that the specified conversion is permitted in a converted constant
4840/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4841/// is acceptable.
4842static bool CheckConvertedConstantConversions(Sema &S,
4843                                              StandardConversionSequence &SCS) {
4844  // Since we know that the target type is an integral or unscoped enumeration
4845  // type, most conversion kinds are impossible. All possible First and Third
4846  // conversions are fine.
4847  switch (SCS.Second) {
4848  case ICK_Identity:
4849  case ICK_Integral_Promotion:
4850  case ICK_Integral_Conversion:
4851  case ICK_Zero_Event_Conversion:
4852    return true;
4853
4854  case ICK_Boolean_Conversion:
4855    // Conversion from an integral or unscoped enumeration type to bool is
4856    // classified as ICK_Boolean_Conversion, but it's also an integral
4857    // conversion, so it's permitted in a converted constant expression.
4858    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4859           SCS.getToType(2)->isBooleanType();
4860
4861  case ICK_Floating_Integral:
4862  case ICK_Complex_Real:
4863    return false;
4864
4865  case ICK_Lvalue_To_Rvalue:
4866  case ICK_Array_To_Pointer:
4867  case ICK_Function_To_Pointer:
4868  case ICK_NoReturn_Adjustment:
4869  case ICK_Qualification:
4870  case ICK_Compatible_Conversion:
4871  case ICK_Vector_Conversion:
4872  case ICK_Vector_Splat:
4873  case ICK_Derived_To_Base:
4874  case ICK_Pointer_Conversion:
4875  case ICK_Pointer_Member:
4876  case ICK_Block_Pointer_Conversion:
4877  case ICK_Writeback_Conversion:
4878  case ICK_Floating_Promotion:
4879  case ICK_Complex_Promotion:
4880  case ICK_Complex_Conversion:
4881  case ICK_Floating_Conversion:
4882  case ICK_TransparentUnionConversion:
4883    llvm_unreachable("unexpected second conversion kind");
4884
4885  case ICK_Num_Conversion_Kinds:
4886    break;
4887  }
4888
4889  llvm_unreachable("unknown conversion kind");
4890}
4891
4892/// CheckConvertedConstantExpression - Check that the expression From is a
4893/// converted constant expression of type T, perform the conversion and produce
4894/// the converted expression, per C++11 [expr.const]p3.
4895ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4896                                                  llvm::APSInt &Value,
4897                                                  CCEKind CCE) {
4898  assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4899  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4900
4901  if (checkPlaceholderForOverload(*this, From))
4902    return ExprError();
4903
4904  // C++11 [expr.const]p3 with proposed wording fixes:
4905  //  A converted constant expression of type T is a core constant expression,
4906  //  implicitly converted to a prvalue of type T, where the converted
4907  //  expression is a literal constant expression and the implicit conversion
4908  //  sequence contains only user-defined conversions, lvalue-to-rvalue
4909  //  conversions, integral promotions, and integral conversions other than
4910  //  narrowing conversions.
4911  ImplicitConversionSequence ICS =
4912    TryImplicitConversion(From, T,
4913                          /*SuppressUserConversions=*/false,
4914                          /*AllowExplicit=*/false,
4915                          /*InOverloadResolution=*/false,
4916                          /*CStyle=*/false,
4917                          /*AllowObjcWritebackConversion=*/false);
4918  StandardConversionSequence *SCS = 0;
4919  switch (ICS.getKind()) {
4920  case ImplicitConversionSequence::StandardConversion:
4921    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4922      return Diag(From->getLocStart(),
4923                  diag::err_typecheck_converted_constant_expression_disallowed)
4924               << From->getType() << From->getSourceRange() << T;
4925    SCS = &ICS.Standard;
4926    break;
4927  case ImplicitConversionSequence::UserDefinedConversion:
4928    // We are converting from class type to an integral or enumeration type, so
4929    // the Before sequence must be trivial.
4930    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4931      return Diag(From->getLocStart(),
4932                  diag::err_typecheck_converted_constant_expression_disallowed)
4933               << From->getType() << From->getSourceRange() << T;
4934    SCS = &ICS.UserDefined.After;
4935    break;
4936  case ImplicitConversionSequence::AmbiguousConversion:
4937  case ImplicitConversionSequence::BadConversion:
4938    if (!DiagnoseMultipleUserDefinedConversion(From, T))
4939      return Diag(From->getLocStart(),
4940                  diag::err_typecheck_converted_constant_expression)
4941                    << From->getType() << From->getSourceRange() << T;
4942    return ExprError();
4943
4944  case ImplicitConversionSequence::EllipsisConversion:
4945    llvm_unreachable("ellipsis conversion in converted constant expression");
4946  }
4947
4948  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4949  if (Result.isInvalid())
4950    return Result;
4951
4952  // Check for a narrowing implicit conversion.
4953  APValue PreNarrowingValue;
4954  QualType PreNarrowingType;
4955  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4956                                PreNarrowingType)) {
4957  case NK_Variable_Narrowing:
4958    // Implicit conversion to a narrower type, and the value is not a constant
4959    // expression. We'll diagnose this in a moment.
4960  case NK_Not_Narrowing:
4961    break;
4962
4963  case NK_Constant_Narrowing:
4964    Diag(From->getLocStart(),
4965         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4966                             diag::err_cce_narrowing)
4967      << CCE << /*Constant*/1
4968      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
4969    break;
4970
4971  case NK_Type_Narrowing:
4972    Diag(From->getLocStart(),
4973         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4974                             diag::err_cce_narrowing)
4975      << CCE << /*Constant*/0 << From->getType() << T;
4976    break;
4977  }
4978
4979  // Check the expression is a constant expression.
4980  SmallVector<PartialDiagnosticAt, 8> Notes;
4981  Expr::EvalResult Eval;
4982  Eval.Diag = &Notes;
4983
4984  if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
4985    // The expression can't be folded, so we can't keep it at this position in
4986    // the AST.
4987    Result = ExprError();
4988  } else {
4989    Value = Eval.Val.getInt();
4990
4991    if (Notes.empty()) {
4992      // It's a constant expression.
4993      return Result;
4994    }
4995  }
4996
4997  // It's not a constant expression. Produce an appropriate diagnostic.
4998  if (Notes.size() == 1 &&
4999      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5000    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5001  else {
5002    Diag(From->getLocStart(), diag::err_expr_not_cce)
5003      << CCE << From->getSourceRange();
5004    for (unsigned I = 0; I < Notes.size(); ++I)
5005      Diag(Notes[I].first, Notes[I].second);
5006  }
5007  return Result;
5008}
5009
5010/// dropPointerConversions - If the given standard conversion sequence
5011/// involves any pointer conversions, remove them.  This may change
5012/// the result type of the conversion sequence.
5013static void dropPointerConversion(StandardConversionSequence &SCS) {
5014  if (SCS.Second == ICK_Pointer_Conversion) {
5015    SCS.Second = ICK_Identity;
5016    SCS.Third = ICK_Identity;
5017    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5018  }
5019}
5020
5021/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5022/// convert the expression From to an Objective-C pointer type.
5023static ImplicitConversionSequence
5024TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5025  // Do an implicit conversion to 'id'.
5026  QualType Ty = S.Context.getObjCIdType();
5027  ImplicitConversionSequence ICS
5028    = TryImplicitConversion(S, From, Ty,
5029                            // FIXME: Are these flags correct?
5030                            /*SuppressUserConversions=*/false,
5031                            /*AllowExplicit=*/true,
5032                            /*InOverloadResolution=*/false,
5033                            /*CStyle=*/false,
5034                            /*AllowObjCWritebackConversion=*/false);
5035
5036  // Strip off any final conversions to 'id'.
5037  switch (ICS.getKind()) {
5038  case ImplicitConversionSequence::BadConversion:
5039  case ImplicitConversionSequence::AmbiguousConversion:
5040  case ImplicitConversionSequence::EllipsisConversion:
5041    break;
5042
5043  case ImplicitConversionSequence::UserDefinedConversion:
5044    dropPointerConversion(ICS.UserDefined.After);
5045    break;
5046
5047  case ImplicitConversionSequence::StandardConversion:
5048    dropPointerConversion(ICS.Standard);
5049    break;
5050  }
5051
5052  return ICS;
5053}
5054
5055/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5056/// conversion of the expression From to an Objective-C pointer type.
5057ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5058  if (checkPlaceholderForOverload(*this, From))
5059    return ExprError();
5060
5061  QualType Ty = Context.getObjCIdType();
5062  ImplicitConversionSequence ICS =
5063    TryContextuallyConvertToObjCPointer(*this, From);
5064  if (!ICS.isBad())
5065    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5066  return ExprError();
5067}
5068
5069/// Determine whether the provided type is an integral type, or an enumeration
5070/// type of a permitted flavor.
5071bool Sema::ICEConvertDiagnoser::match(QualType T) {
5072  return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5073                                 : T->isIntegralOrUnscopedEnumerationType();
5074}
5075
5076static ExprResult
5077diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5078                            Sema::ContextualImplicitConverter &Converter,
5079                            QualType T, UnresolvedSetImpl &ViableConversions) {
5080
5081  if (Converter.Suppress)
5082    return ExprError();
5083
5084  Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5085  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5086    CXXConversionDecl *Conv =
5087        cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5088    QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5089    Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5090  }
5091  return SemaRef.Owned(From);
5092}
5093
5094static bool
5095diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5096                           Sema::ContextualImplicitConverter &Converter,
5097                           QualType T, bool HadMultipleCandidates,
5098                           UnresolvedSetImpl &ExplicitConversions) {
5099  if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5100    DeclAccessPair Found = ExplicitConversions[0];
5101    CXXConversionDecl *Conversion =
5102        cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5103
5104    // The user probably meant to invoke the given explicit
5105    // conversion; use it.
5106    QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5107    std::string TypeStr;
5108    ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5109
5110    Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5111        << FixItHint::CreateInsertion(From->getLocStart(),
5112                                      "static_cast<" + TypeStr + ">(")
5113        << FixItHint::CreateInsertion(
5114               SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5115    Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5116
5117    // If we aren't in a SFINAE context, build a call to the
5118    // explicit conversion function.
5119    if (SemaRef.isSFINAEContext())
5120      return true;
5121
5122    SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5123    ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5124                                                       HadMultipleCandidates);
5125    if (Result.isInvalid())
5126      return true;
5127    // Record usage of conversion in an implicit cast.
5128    From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5129                                    CK_UserDefinedConversion, Result.get(), 0,
5130                                    Result.get()->getValueKind());
5131  }
5132  return false;
5133}
5134
5135static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5136                             Sema::ContextualImplicitConverter &Converter,
5137                             QualType T, bool HadMultipleCandidates,
5138                             DeclAccessPair &Found) {
5139  CXXConversionDecl *Conversion =
5140      cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5141  SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5142
5143  QualType ToType = Conversion->getConversionType().getNonReferenceType();
5144  if (!Converter.SuppressConversion) {
5145    if (SemaRef.isSFINAEContext())
5146      return true;
5147
5148    Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5149        << From->getSourceRange();
5150  }
5151
5152  ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5153                                                     HadMultipleCandidates);
5154  if (Result.isInvalid())
5155    return true;
5156  // Record usage of conversion in an implicit cast.
5157  From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5158                                  CK_UserDefinedConversion, Result.get(), 0,
5159                                  Result.get()->getValueKind());
5160  return false;
5161}
5162
5163static ExprResult finishContextualImplicitConversion(
5164    Sema &SemaRef, SourceLocation Loc, Expr *From,
5165    Sema::ContextualImplicitConverter &Converter) {
5166  if (!Converter.match(From->getType()) && !Converter.Suppress)
5167    Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5168        << From->getSourceRange();
5169
5170  return SemaRef.DefaultLvalueConversion(From);
5171}
5172
5173static void
5174collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5175                                  UnresolvedSetImpl &ViableConversions,
5176                                  OverloadCandidateSet &CandidateSet) {
5177  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5178    DeclAccessPair FoundDecl = ViableConversions[I];
5179    NamedDecl *D = FoundDecl.getDecl();
5180    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5181    if (isa<UsingShadowDecl>(D))
5182      D = cast<UsingShadowDecl>(D)->getTargetDecl();
5183
5184    CXXConversionDecl *Conv;
5185    FunctionTemplateDecl *ConvTemplate;
5186    if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5187      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5188    else
5189      Conv = cast<CXXConversionDecl>(D);
5190
5191    if (ConvTemplate)
5192      SemaRef.AddTemplateConversionCandidate(
5193          ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet);
5194    else
5195      SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5196                                     ToType, CandidateSet);
5197  }
5198}
5199
5200/// \brief Attempt to convert the given expression to a type which is accepted
5201/// by the given converter.
5202///
5203/// This routine will attempt to convert an expression of class type to a
5204/// type accepted by the specified converter. In C++11 and before, the class
5205/// must have a single non-explicit conversion function converting to a matching
5206/// type. In C++1y, there can be multiple such conversion functions, but only
5207/// one target type.
5208///
5209/// \param Loc The source location of the construct that requires the
5210/// conversion.
5211///
5212/// \param From The expression we're converting from.
5213///
5214/// \param Converter Used to control and diagnose the conversion process.
5215///
5216/// \returns The expression, converted to an integral or enumeration type if
5217/// successful.
5218ExprResult Sema::PerformContextualImplicitConversion(
5219    SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5220  // We can't perform any more checking for type-dependent expressions.
5221  if (From->isTypeDependent())
5222    return Owned(From);
5223
5224  // Process placeholders immediately.
5225  if (From->hasPlaceholderType()) {
5226    ExprResult result = CheckPlaceholderExpr(From);
5227    if (result.isInvalid())
5228      return result;
5229    From = result.take();
5230  }
5231
5232  // If the expression already has a matching type, we're golden.
5233  QualType T = From->getType();
5234  if (Converter.match(T))
5235    return DefaultLvalueConversion(From);
5236
5237  // FIXME: Check for missing '()' if T is a function type?
5238
5239  // We can only perform contextual implicit conversions on objects of class
5240  // type.
5241  const RecordType *RecordTy = T->getAs<RecordType>();
5242  if (!RecordTy || !getLangOpts().CPlusPlus) {
5243    if (!Converter.Suppress)
5244      Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5245    return Owned(From);
5246  }
5247
5248  // We must have a complete class type.
5249  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5250    ContextualImplicitConverter &Converter;
5251    Expr *From;
5252
5253    TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5254        : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5255
5256    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5257      Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5258    }
5259  } IncompleteDiagnoser(Converter, From);
5260
5261  if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5262    return Owned(From);
5263
5264  // Look for a conversion to an integral or enumeration type.
5265  UnresolvedSet<4>
5266      ViableConversions; // These are *potentially* viable in C++1y.
5267  UnresolvedSet<4> ExplicitConversions;
5268  std::pair<CXXRecordDecl::conversion_iterator,
5269            CXXRecordDecl::conversion_iterator> Conversions =
5270      cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5271
5272  bool HadMultipleCandidates =
5273      (std::distance(Conversions.first, Conversions.second) > 1);
5274
5275  // To check that there is only one target type, in C++1y:
5276  QualType ToType;
5277  bool HasUniqueTargetType = true;
5278
5279  // Collect explicit or viable (potentially in C++1y) conversions.
5280  for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5281                                          E = Conversions.second;
5282       I != E; ++I) {
5283    NamedDecl *D = (*I)->getUnderlyingDecl();
5284    CXXConversionDecl *Conversion;
5285    FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5286    if (ConvTemplate) {
5287      if (getLangOpts().CPlusPlus1y)
5288        Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5289      else
5290        continue; // C++11 does not consider conversion operator templates(?).
5291    } else
5292      Conversion = cast<CXXConversionDecl>(D);
5293
5294    assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5295           "Conversion operator templates are considered potentially "
5296           "viable in C++1y");
5297
5298    QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5299    if (Converter.match(CurToType) || ConvTemplate) {
5300
5301      if (Conversion->isExplicit()) {
5302        // FIXME: For C++1y, do we need this restriction?
5303        // cf. diagnoseNoViableConversion()
5304        if (!ConvTemplate)
5305          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5306      } else {
5307        if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5308          if (ToType.isNull())
5309            ToType = CurToType.getUnqualifiedType();
5310          else if (HasUniqueTargetType &&
5311                   (CurToType.getUnqualifiedType() != ToType))
5312            HasUniqueTargetType = false;
5313        }
5314        ViableConversions.addDecl(I.getDecl(), I.getAccess());
5315      }
5316    }
5317  }
5318
5319  if (getLangOpts().CPlusPlus1y) {
5320    // C++1y [conv]p6:
5321    // ... An expression e of class type E appearing in such a context
5322    // is said to be contextually implicitly converted to a specified
5323    // type T and is well-formed if and only if e can be implicitly
5324    // converted to a type T that is determined as follows: E is searched
5325    // for conversion functions whose return type is cv T or reference to
5326    // cv T such that T is allowed by the context. There shall be
5327    // exactly one such T.
5328
5329    // If no unique T is found:
5330    if (ToType.isNull()) {
5331      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5332                                     HadMultipleCandidates,
5333                                     ExplicitConversions))
5334        return ExprError();
5335      return finishContextualImplicitConversion(*this, Loc, From, Converter);
5336    }
5337
5338    // If more than one unique Ts are found:
5339    if (!HasUniqueTargetType)
5340      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5341                                         ViableConversions);
5342
5343    // If one unique T is found:
5344    // First, build a candidate set from the previously recorded
5345    // potentially viable conversions.
5346    OverloadCandidateSet CandidateSet(Loc);
5347    collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5348                                      CandidateSet);
5349
5350    // Then, perform overload resolution over the candidate set.
5351    OverloadCandidateSet::iterator Best;
5352    switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5353    case OR_Success: {
5354      // Apply this conversion.
5355      DeclAccessPair Found =
5356          DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5357      if (recordConversion(*this, Loc, From, Converter, T,
5358                           HadMultipleCandidates, Found))
5359        return ExprError();
5360      break;
5361    }
5362    case OR_Ambiguous:
5363      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5364                                         ViableConversions);
5365    case OR_No_Viable_Function:
5366      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5367                                     HadMultipleCandidates,
5368                                     ExplicitConversions))
5369        return ExprError();
5370    // fall through 'OR_Deleted' case.
5371    case OR_Deleted:
5372      // We'll complain below about a non-integral condition type.
5373      break;
5374    }
5375  } else {
5376    switch (ViableConversions.size()) {
5377    case 0: {
5378      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5379                                     HadMultipleCandidates,
5380                                     ExplicitConversions))
5381        return ExprError();
5382
5383      // We'll complain below about a non-integral condition type.
5384      break;
5385    }
5386    case 1: {
5387      // Apply this conversion.
5388      DeclAccessPair Found = ViableConversions[0];
5389      if (recordConversion(*this, Loc, From, Converter, T,
5390                           HadMultipleCandidates, Found))
5391        return ExprError();
5392      break;
5393    }
5394    default:
5395      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5396                                         ViableConversions);
5397    }
5398  }
5399
5400  return finishContextualImplicitConversion(*this, Loc, From, Converter);
5401}
5402
5403/// AddOverloadCandidate - Adds the given function to the set of
5404/// candidate functions, using the given function call arguments.  If
5405/// @p SuppressUserConversions, then don't allow user-defined
5406/// conversions via constructors or conversion operators.
5407///
5408/// \param PartialOverloading true if we are performing "partial" overloading
5409/// based on an incomplete set of function arguments. This feature is used by
5410/// code completion.
5411void
5412Sema::AddOverloadCandidate(FunctionDecl *Function,
5413                           DeclAccessPair FoundDecl,
5414                           ArrayRef<Expr *> Args,
5415                           OverloadCandidateSet& CandidateSet,
5416                           bool SuppressUserConversions,
5417                           bool PartialOverloading,
5418                           bool AllowExplicit) {
5419  const FunctionProtoType* Proto
5420    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5421  assert(Proto && "Functions without a prototype cannot be overloaded");
5422  assert(!Function->getDescribedFunctionTemplate() &&
5423         "Use AddTemplateOverloadCandidate for function templates");
5424
5425  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5426    if (!isa<CXXConstructorDecl>(Method)) {
5427      // If we get here, it's because we're calling a member function
5428      // that is named without a member access expression (e.g.,
5429      // "this->f") that was either written explicitly or created
5430      // implicitly. This can happen with a qualified call to a member
5431      // function, e.g., X::f(). We use an empty type for the implied
5432      // object argument (C++ [over.call.func]p3), and the acting context
5433      // is irrelevant.
5434      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5435                         QualType(), Expr::Classification::makeSimpleLValue(),
5436                         Args, CandidateSet, SuppressUserConversions);
5437      return;
5438    }
5439    // We treat a constructor like a non-member function, since its object
5440    // argument doesn't participate in overload resolution.
5441  }
5442
5443  if (!CandidateSet.isNewCandidate(Function))
5444    return;
5445
5446  // Overload resolution is always an unevaluated context.
5447  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5448
5449  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5450    // C++ [class.copy]p3:
5451    //   A member function template is never instantiated to perform the copy
5452    //   of a class object to an object of its class type.
5453    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5454    if (Args.size() == 1 &&
5455        Constructor->isSpecializationCopyingObject() &&
5456        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5457         IsDerivedFrom(Args[0]->getType(), ClassType)))
5458      return;
5459  }
5460
5461  // Add this candidate
5462  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5463  Candidate.FoundDecl = FoundDecl;
5464  Candidate.Function = Function;
5465  Candidate.Viable = true;
5466  Candidate.IsSurrogate = false;
5467  Candidate.IgnoreObjectArgument = false;
5468  Candidate.ExplicitCallArguments = Args.size();
5469
5470  unsigned NumArgsInProto = Proto->getNumArgs();
5471
5472  // (C++ 13.3.2p2): A candidate function having fewer than m
5473  // parameters is viable only if it has an ellipsis in its parameter
5474  // list (8.3.5).
5475  if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5476      !Proto->isVariadic()) {
5477    Candidate.Viable = false;
5478    Candidate.FailureKind = ovl_fail_too_many_arguments;
5479    return;
5480  }
5481
5482  // (C++ 13.3.2p2): A candidate function having more than m parameters
5483  // is viable only if the (m+1)st parameter has a default argument
5484  // (8.3.6). For the purposes of overload resolution, the
5485  // parameter list is truncated on the right, so that there are
5486  // exactly m parameters.
5487  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5488  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5489    // Not enough arguments.
5490    Candidate.Viable = false;
5491    Candidate.FailureKind = ovl_fail_too_few_arguments;
5492    return;
5493  }
5494
5495  // (CUDA B.1): Check for invalid calls between targets.
5496  if (getLangOpts().CUDA)
5497    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5498      if (CheckCUDATarget(Caller, Function)) {
5499        Candidate.Viable = false;
5500        Candidate.FailureKind = ovl_fail_bad_target;
5501        return;
5502      }
5503
5504  // Determine the implicit conversion sequences for each of the
5505  // arguments.
5506  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5507    if (ArgIdx < NumArgsInProto) {
5508      // (C++ 13.3.2p3): for F to be a viable function, there shall
5509      // exist for each argument an implicit conversion sequence
5510      // (13.3.3.1) that converts that argument to the corresponding
5511      // parameter of F.
5512      QualType ParamType = Proto->getArgType(ArgIdx);
5513      Candidate.Conversions[ArgIdx]
5514        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5515                                SuppressUserConversions,
5516                                /*InOverloadResolution=*/true,
5517                                /*AllowObjCWritebackConversion=*/
5518                                  getLangOpts().ObjCAutoRefCount,
5519                                AllowExplicit);
5520      if (Candidate.Conversions[ArgIdx].isBad()) {
5521        Candidate.Viable = false;
5522        Candidate.FailureKind = ovl_fail_bad_conversion;
5523        break;
5524      }
5525    } else {
5526      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5527      // argument for which there is no corresponding parameter is
5528      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5529      Candidate.Conversions[ArgIdx].setEllipsis();
5530    }
5531  }
5532}
5533
5534/// \brief Add all of the function declarations in the given function set to
5535/// the overload canddiate set.
5536void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5537                                 ArrayRef<Expr *> Args,
5538                                 OverloadCandidateSet& CandidateSet,
5539                                 bool SuppressUserConversions,
5540                               TemplateArgumentListInfo *ExplicitTemplateArgs) {
5541  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5542    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5543    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5544      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5545        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5546                           cast<CXXMethodDecl>(FD)->getParent(),
5547                           Args[0]->getType(), Args[0]->Classify(Context),
5548                           Args.slice(1), CandidateSet,
5549                           SuppressUserConversions);
5550      else
5551        AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5552                             SuppressUserConversions);
5553    } else {
5554      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5555      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5556          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5557        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5558                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5559                                   ExplicitTemplateArgs,
5560                                   Args[0]->getType(),
5561                                   Args[0]->Classify(Context), Args.slice(1),
5562                                   CandidateSet, SuppressUserConversions);
5563      else
5564        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5565                                     ExplicitTemplateArgs, Args,
5566                                     CandidateSet, SuppressUserConversions);
5567    }
5568  }
5569}
5570
5571/// AddMethodCandidate - Adds a named decl (which is some kind of
5572/// method) as a method candidate to the given overload set.
5573void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5574                              QualType ObjectType,
5575                              Expr::Classification ObjectClassification,
5576                              ArrayRef<Expr *> Args,
5577                              OverloadCandidateSet& CandidateSet,
5578                              bool SuppressUserConversions) {
5579  NamedDecl *Decl = FoundDecl.getDecl();
5580  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5581
5582  if (isa<UsingShadowDecl>(Decl))
5583    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5584
5585  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5586    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5587           "Expected a member function template");
5588    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5589                               /*ExplicitArgs*/ 0,
5590                               ObjectType, ObjectClassification,
5591                               Args, CandidateSet,
5592                               SuppressUserConversions);
5593  } else {
5594    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5595                       ObjectType, ObjectClassification,
5596                       Args,
5597                       CandidateSet, SuppressUserConversions);
5598  }
5599}
5600
5601/// AddMethodCandidate - Adds the given C++ member function to the set
5602/// of candidate functions, using the given function call arguments
5603/// and the object argument (@c Object). For example, in a call
5604/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5605/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5606/// allow user-defined conversions via constructors or conversion
5607/// operators.
5608void
5609Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5610                         CXXRecordDecl *ActingContext, QualType ObjectType,
5611                         Expr::Classification ObjectClassification,
5612                         ArrayRef<Expr *> Args,
5613                         OverloadCandidateSet& CandidateSet,
5614                         bool SuppressUserConversions) {
5615  const FunctionProtoType* Proto
5616    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5617  assert(Proto && "Methods without a prototype cannot be overloaded");
5618  assert(!isa<CXXConstructorDecl>(Method) &&
5619         "Use AddOverloadCandidate for constructors");
5620
5621  if (!CandidateSet.isNewCandidate(Method))
5622    return;
5623
5624  // Overload resolution is always an unevaluated context.
5625  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5626
5627  // Add this candidate
5628  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5629  Candidate.FoundDecl = FoundDecl;
5630  Candidate.Function = Method;
5631  Candidate.IsSurrogate = false;
5632  Candidate.IgnoreObjectArgument = false;
5633  Candidate.ExplicitCallArguments = Args.size();
5634
5635  unsigned NumArgsInProto = Proto->getNumArgs();
5636
5637  // (C++ 13.3.2p2): A candidate function having fewer than m
5638  // parameters is viable only if it has an ellipsis in its parameter
5639  // list (8.3.5).
5640  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5641    Candidate.Viable = false;
5642    Candidate.FailureKind = ovl_fail_too_many_arguments;
5643    return;
5644  }
5645
5646  // (C++ 13.3.2p2): A candidate function having more than m parameters
5647  // is viable only if the (m+1)st parameter has a default argument
5648  // (8.3.6). For the purposes of overload resolution, the
5649  // parameter list is truncated on the right, so that there are
5650  // exactly m parameters.
5651  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5652  if (Args.size() < MinRequiredArgs) {
5653    // Not enough arguments.
5654    Candidate.Viable = false;
5655    Candidate.FailureKind = ovl_fail_too_few_arguments;
5656    return;
5657  }
5658
5659  Candidate.Viable = true;
5660
5661  if (Method->isStatic() || ObjectType.isNull())
5662    // The implicit object argument is ignored.
5663    Candidate.IgnoreObjectArgument = true;
5664  else {
5665    // Determine the implicit conversion sequence for the object
5666    // parameter.
5667    Candidate.Conversions[0]
5668      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5669                                        Method, ActingContext);
5670    if (Candidate.Conversions[0].isBad()) {
5671      Candidate.Viable = false;
5672      Candidate.FailureKind = ovl_fail_bad_conversion;
5673      return;
5674    }
5675  }
5676
5677  // Determine the implicit conversion sequences for each of the
5678  // arguments.
5679  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5680    if (ArgIdx < NumArgsInProto) {
5681      // (C++ 13.3.2p3): for F to be a viable function, there shall
5682      // exist for each argument an implicit conversion sequence
5683      // (13.3.3.1) that converts that argument to the corresponding
5684      // parameter of F.
5685      QualType ParamType = Proto->getArgType(ArgIdx);
5686      Candidate.Conversions[ArgIdx + 1]
5687        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5688                                SuppressUserConversions,
5689                                /*InOverloadResolution=*/true,
5690                                /*AllowObjCWritebackConversion=*/
5691                                  getLangOpts().ObjCAutoRefCount);
5692      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5693        Candidate.Viable = false;
5694        Candidate.FailureKind = ovl_fail_bad_conversion;
5695        break;
5696      }
5697    } else {
5698      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5699      // argument for which there is no corresponding parameter is
5700      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5701      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5702    }
5703  }
5704}
5705
5706/// \brief Add a C++ member function template as a candidate to the candidate
5707/// set, using template argument deduction to produce an appropriate member
5708/// function template specialization.
5709void
5710Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5711                                 DeclAccessPair FoundDecl,
5712                                 CXXRecordDecl *ActingContext,
5713                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5714                                 QualType ObjectType,
5715                                 Expr::Classification ObjectClassification,
5716                                 ArrayRef<Expr *> Args,
5717                                 OverloadCandidateSet& CandidateSet,
5718                                 bool SuppressUserConversions) {
5719  if (!CandidateSet.isNewCandidate(MethodTmpl))
5720    return;
5721
5722  // C++ [over.match.funcs]p7:
5723  //   In each case where a candidate is a function template, candidate
5724  //   function template specializations are generated using template argument
5725  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5726  //   candidate functions in the usual way.113) A given name can refer to one
5727  //   or more function templates and also to a set of overloaded non-template
5728  //   functions. In such a case, the candidate functions generated from each
5729  //   function template are combined with the set of non-template candidate
5730  //   functions.
5731  TemplateDeductionInfo Info(CandidateSet.getLocation());
5732  FunctionDecl *Specialization = 0;
5733  if (TemplateDeductionResult Result
5734      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5735                                Specialization, Info)) {
5736    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5737    Candidate.FoundDecl = FoundDecl;
5738    Candidate.Function = MethodTmpl->getTemplatedDecl();
5739    Candidate.Viable = false;
5740    Candidate.FailureKind = ovl_fail_bad_deduction;
5741    Candidate.IsSurrogate = false;
5742    Candidate.IgnoreObjectArgument = false;
5743    Candidate.ExplicitCallArguments = Args.size();
5744    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5745                                                          Info);
5746    return;
5747  }
5748
5749  // Add the function template specialization produced by template argument
5750  // deduction as a candidate.
5751  assert(Specialization && "Missing member function template specialization?");
5752  assert(isa<CXXMethodDecl>(Specialization) &&
5753         "Specialization is not a member function?");
5754  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5755                     ActingContext, ObjectType, ObjectClassification, Args,
5756                     CandidateSet, SuppressUserConversions);
5757}
5758
5759/// \brief Add a C++ function template specialization as a candidate
5760/// in the candidate set, using template argument deduction to produce
5761/// an appropriate function template specialization.
5762void
5763Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5764                                   DeclAccessPair FoundDecl,
5765                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5766                                   ArrayRef<Expr *> Args,
5767                                   OverloadCandidateSet& CandidateSet,
5768                                   bool SuppressUserConversions) {
5769  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5770    return;
5771
5772  // C++ [over.match.funcs]p7:
5773  //   In each case where a candidate is a function template, candidate
5774  //   function template specializations are generated using template argument
5775  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5776  //   candidate functions in the usual way.113) A given name can refer to one
5777  //   or more function templates and also to a set of overloaded non-template
5778  //   functions. In such a case, the candidate functions generated from each
5779  //   function template are combined with the set of non-template candidate
5780  //   functions.
5781  TemplateDeductionInfo Info(CandidateSet.getLocation());
5782  FunctionDecl *Specialization = 0;
5783  if (TemplateDeductionResult Result
5784        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5785                                  Specialization, Info)) {
5786    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5787    Candidate.FoundDecl = FoundDecl;
5788    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5789    Candidate.Viable = false;
5790    Candidate.FailureKind = ovl_fail_bad_deduction;
5791    Candidate.IsSurrogate = false;
5792    Candidate.IgnoreObjectArgument = false;
5793    Candidate.ExplicitCallArguments = Args.size();
5794    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5795                                                          Info);
5796    return;
5797  }
5798
5799  // Add the function template specialization produced by template argument
5800  // deduction as a candidate.
5801  assert(Specialization && "Missing function template specialization?");
5802  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5803                       SuppressUserConversions);
5804}
5805
5806/// AddConversionCandidate - Add a C++ conversion function as a
5807/// candidate in the candidate set (C++ [over.match.conv],
5808/// C++ [over.match.copy]). From is the expression we're converting from,
5809/// and ToType is the type that we're eventually trying to convert to
5810/// (which may or may not be the same type as the type that the
5811/// conversion function produces).
5812void
5813Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5814                             DeclAccessPair FoundDecl,
5815                             CXXRecordDecl *ActingContext,
5816                             Expr *From, QualType ToType,
5817                             OverloadCandidateSet& CandidateSet) {
5818  assert(!Conversion->getDescribedFunctionTemplate() &&
5819         "Conversion function templates use AddTemplateConversionCandidate");
5820  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5821  if (!CandidateSet.isNewCandidate(Conversion))
5822    return;
5823
5824  // If the conversion function has an undeduced return type, trigger its
5825  // deduction now.
5826  if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5827    if (DeduceReturnType(Conversion, From->getExprLoc()))
5828      return;
5829    ConvType = Conversion->getConversionType().getNonReferenceType();
5830  }
5831
5832  // Overload resolution is always an unevaluated context.
5833  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5834
5835  // Add this candidate
5836  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5837  Candidate.FoundDecl = FoundDecl;
5838  Candidate.Function = Conversion;
5839  Candidate.IsSurrogate = false;
5840  Candidate.IgnoreObjectArgument = false;
5841  Candidate.FinalConversion.setAsIdentityConversion();
5842  Candidate.FinalConversion.setFromType(ConvType);
5843  Candidate.FinalConversion.setAllToTypes(ToType);
5844  Candidate.Viable = true;
5845  Candidate.ExplicitCallArguments = 1;
5846
5847  // C++ [over.match.funcs]p4:
5848  //   For conversion functions, the function is considered to be a member of
5849  //   the class of the implicit implied object argument for the purpose of
5850  //   defining the type of the implicit object parameter.
5851  //
5852  // Determine the implicit conversion sequence for the implicit
5853  // object parameter.
5854  QualType ImplicitParamType = From->getType();
5855  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5856    ImplicitParamType = FromPtrType->getPointeeType();
5857  CXXRecordDecl *ConversionContext
5858    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5859
5860  Candidate.Conversions[0]
5861    = TryObjectArgumentInitialization(*this, From->getType(),
5862                                      From->Classify(Context),
5863                                      Conversion, ConversionContext);
5864
5865  if (Candidate.Conversions[0].isBad()) {
5866    Candidate.Viable = false;
5867    Candidate.FailureKind = ovl_fail_bad_conversion;
5868    return;
5869  }
5870
5871  // We won't go through a user-define type conversion function to convert a
5872  // derived to base as such conversions are given Conversion Rank. They only
5873  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5874  QualType FromCanon
5875    = Context.getCanonicalType(From->getType().getUnqualifiedType());
5876  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5877  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5878    Candidate.Viable = false;
5879    Candidate.FailureKind = ovl_fail_trivial_conversion;
5880    return;
5881  }
5882
5883  // To determine what the conversion from the result of calling the
5884  // conversion function to the type we're eventually trying to
5885  // convert to (ToType), we need to synthesize a call to the
5886  // conversion function and attempt copy initialization from it. This
5887  // makes sure that we get the right semantics with respect to
5888  // lvalues/rvalues and the type. Fortunately, we can allocate this
5889  // call on the stack and we don't need its arguments to be
5890  // well-formed.
5891  DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5892                            VK_LValue, From->getLocStart());
5893  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5894                                Context.getPointerType(Conversion->getType()),
5895                                CK_FunctionToPointerDecay,
5896                                &ConversionRef, VK_RValue);
5897
5898  QualType ConversionType = Conversion->getConversionType();
5899  if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5900    Candidate.Viable = false;
5901    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5902    return;
5903  }
5904
5905  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5906
5907  // Note that it is safe to allocate CallExpr on the stack here because
5908  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5909  // allocator).
5910  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5911  CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
5912                From->getLocStart());
5913  ImplicitConversionSequence ICS =
5914    TryCopyInitialization(*this, &Call, ToType,
5915                          /*SuppressUserConversions=*/true,
5916                          /*InOverloadResolution=*/false,
5917                          /*AllowObjCWritebackConversion=*/false);
5918
5919  switch (ICS.getKind()) {
5920  case ImplicitConversionSequence::StandardConversion:
5921    Candidate.FinalConversion = ICS.Standard;
5922
5923    // C++ [over.ics.user]p3:
5924    //   If the user-defined conversion is specified by a specialization of a
5925    //   conversion function template, the second standard conversion sequence
5926    //   shall have exact match rank.
5927    if (Conversion->getPrimaryTemplate() &&
5928        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5929      Candidate.Viable = false;
5930      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5931    }
5932
5933    // C++0x [dcl.init.ref]p5:
5934    //    In the second case, if the reference is an rvalue reference and
5935    //    the second standard conversion sequence of the user-defined
5936    //    conversion sequence includes an lvalue-to-rvalue conversion, the
5937    //    program is ill-formed.
5938    if (ToType->isRValueReferenceType() &&
5939        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5940      Candidate.Viable = false;
5941      Candidate.FailureKind = ovl_fail_bad_final_conversion;
5942    }
5943    break;
5944
5945  case ImplicitConversionSequence::BadConversion:
5946    Candidate.Viable = false;
5947    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5948    break;
5949
5950  default:
5951    llvm_unreachable(
5952           "Can only end up with a standard conversion sequence or failure");
5953  }
5954}
5955
5956/// \brief Adds a conversion function template specialization
5957/// candidate to the overload set, using template argument deduction
5958/// to deduce the template arguments of the conversion function
5959/// template from the type that we are converting to (C++
5960/// [temp.deduct.conv]).
5961void
5962Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5963                                     DeclAccessPair FoundDecl,
5964                                     CXXRecordDecl *ActingDC,
5965                                     Expr *From, QualType ToType,
5966                                     OverloadCandidateSet &CandidateSet) {
5967  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5968         "Only conversion function templates permitted here");
5969
5970  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5971    return;
5972
5973  TemplateDeductionInfo Info(CandidateSet.getLocation());
5974  CXXConversionDecl *Specialization = 0;
5975  if (TemplateDeductionResult Result
5976        = DeduceTemplateArguments(FunctionTemplate, ToType,
5977                                  Specialization, Info)) {
5978    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5979    Candidate.FoundDecl = FoundDecl;
5980    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5981    Candidate.Viable = false;
5982    Candidate.FailureKind = ovl_fail_bad_deduction;
5983    Candidate.IsSurrogate = false;
5984    Candidate.IgnoreObjectArgument = false;
5985    Candidate.ExplicitCallArguments = 1;
5986    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5987                                                          Info);
5988    return;
5989  }
5990
5991  // Add the conversion function template specialization produced by
5992  // template argument deduction as a candidate.
5993  assert(Specialization && "Missing function template specialization?");
5994  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5995                         CandidateSet);
5996}
5997
5998/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5999/// converts the given @c Object to a function pointer via the
6000/// conversion function @c Conversion, and then attempts to call it
6001/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6002/// the type of function that we'll eventually be calling.
6003void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6004                                 DeclAccessPair FoundDecl,
6005                                 CXXRecordDecl *ActingContext,
6006                                 const FunctionProtoType *Proto,
6007                                 Expr *Object,
6008                                 ArrayRef<Expr *> Args,
6009                                 OverloadCandidateSet& CandidateSet) {
6010  if (!CandidateSet.isNewCandidate(Conversion))
6011    return;
6012
6013  // Overload resolution is always an unevaluated context.
6014  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6015
6016  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6017  Candidate.FoundDecl = FoundDecl;
6018  Candidate.Function = 0;
6019  Candidate.Surrogate = Conversion;
6020  Candidate.Viable = true;
6021  Candidate.IsSurrogate = true;
6022  Candidate.IgnoreObjectArgument = false;
6023  Candidate.ExplicitCallArguments = Args.size();
6024
6025  // Determine the implicit conversion sequence for the implicit
6026  // object parameter.
6027  ImplicitConversionSequence ObjectInit
6028    = TryObjectArgumentInitialization(*this, Object->getType(),
6029                                      Object->Classify(Context),
6030                                      Conversion, ActingContext);
6031  if (ObjectInit.isBad()) {
6032    Candidate.Viable = false;
6033    Candidate.FailureKind = ovl_fail_bad_conversion;
6034    Candidate.Conversions[0] = ObjectInit;
6035    return;
6036  }
6037
6038  // The first conversion is actually a user-defined conversion whose
6039  // first conversion is ObjectInit's standard conversion (which is
6040  // effectively a reference binding). Record it as such.
6041  Candidate.Conversions[0].setUserDefined();
6042  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6043  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6044  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6045  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6046  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6047  Candidate.Conversions[0].UserDefined.After
6048    = Candidate.Conversions[0].UserDefined.Before;
6049  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6050
6051  // Find the
6052  unsigned NumArgsInProto = Proto->getNumArgs();
6053
6054  // (C++ 13.3.2p2): A candidate function having fewer than m
6055  // parameters is viable only if it has an ellipsis in its parameter
6056  // list (8.3.5).
6057  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
6058    Candidate.Viable = false;
6059    Candidate.FailureKind = ovl_fail_too_many_arguments;
6060    return;
6061  }
6062
6063  // Function types don't have any default arguments, so just check if
6064  // we have enough arguments.
6065  if (Args.size() < NumArgsInProto) {
6066    // Not enough arguments.
6067    Candidate.Viable = false;
6068    Candidate.FailureKind = ovl_fail_too_few_arguments;
6069    return;
6070  }
6071
6072  // Determine the implicit conversion sequences for each of the
6073  // arguments.
6074  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6075    if (ArgIdx < NumArgsInProto) {
6076      // (C++ 13.3.2p3): for F to be a viable function, there shall
6077      // exist for each argument an implicit conversion sequence
6078      // (13.3.3.1) that converts that argument to the corresponding
6079      // parameter of F.
6080      QualType ParamType = Proto->getArgType(ArgIdx);
6081      Candidate.Conversions[ArgIdx + 1]
6082        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6083                                /*SuppressUserConversions=*/false,
6084                                /*InOverloadResolution=*/false,
6085                                /*AllowObjCWritebackConversion=*/
6086                                  getLangOpts().ObjCAutoRefCount);
6087      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6088        Candidate.Viable = false;
6089        Candidate.FailureKind = ovl_fail_bad_conversion;
6090        break;
6091      }
6092    } else {
6093      // (C++ 13.3.2p2): For the purposes of overload resolution, any
6094      // argument for which there is no corresponding parameter is
6095      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6096      Candidate.Conversions[ArgIdx + 1].setEllipsis();
6097    }
6098  }
6099}
6100
6101/// \brief Add overload candidates for overloaded operators that are
6102/// member functions.
6103///
6104/// Add the overloaded operator candidates that are member functions
6105/// for the operator Op that was used in an operator expression such
6106/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6107/// CandidateSet will store the added overload candidates. (C++
6108/// [over.match.oper]).
6109void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6110                                       SourceLocation OpLoc,
6111                                       ArrayRef<Expr *> Args,
6112                                       OverloadCandidateSet& CandidateSet,
6113                                       SourceRange OpRange) {
6114  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6115
6116  // C++ [over.match.oper]p3:
6117  //   For a unary operator @ with an operand of a type whose
6118  //   cv-unqualified version is T1, and for a binary operator @ with
6119  //   a left operand of a type whose cv-unqualified version is T1 and
6120  //   a right operand of a type whose cv-unqualified version is T2,
6121  //   three sets of candidate functions, designated member
6122  //   candidates, non-member candidates and built-in candidates, are
6123  //   constructed as follows:
6124  QualType T1 = Args[0]->getType();
6125
6126  //     -- If T1 is a complete class type or a class currently being
6127  //        defined, the set of member candidates is the result of the
6128  //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6129  //        the set of member candidates is empty.
6130  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6131    // Complete the type if it can be completed.
6132    RequireCompleteType(OpLoc, T1, 0);
6133    // If the type is neither complete nor being defined, bail out now.
6134    if (!T1Rec->getDecl()->getDefinition())
6135      return;
6136
6137    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6138    LookupQualifiedName(Operators, T1Rec->getDecl());
6139    Operators.suppressDiagnostics();
6140
6141    for (LookupResult::iterator Oper = Operators.begin(),
6142                             OperEnd = Operators.end();
6143         Oper != OperEnd;
6144         ++Oper)
6145      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6146                         Args[0]->Classify(Context),
6147                         Args.slice(1),
6148                         CandidateSet,
6149                         /* SuppressUserConversions = */ false);
6150  }
6151}
6152
6153/// AddBuiltinCandidate - Add a candidate for a built-in
6154/// operator. ResultTy and ParamTys are the result and parameter types
6155/// of the built-in candidate, respectively. Args and NumArgs are the
6156/// arguments being passed to the candidate. IsAssignmentOperator
6157/// should be true when this built-in candidate is an assignment
6158/// operator. NumContextualBoolArguments is the number of arguments
6159/// (at the beginning of the argument list) that will be contextually
6160/// converted to bool.
6161void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6162                               ArrayRef<Expr *> Args,
6163                               OverloadCandidateSet& CandidateSet,
6164                               bool IsAssignmentOperator,
6165                               unsigned NumContextualBoolArguments) {
6166  // Overload resolution is always an unevaluated context.
6167  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6168
6169  // Add this candidate
6170  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6171  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
6172  Candidate.Function = 0;
6173  Candidate.IsSurrogate = false;
6174  Candidate.IgnoreObjectArgument = false;
6175  Candidate.BuiltinTypes.ResultTy = ResultTy;
6176  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6177    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6178
6179  // Determine the implicit conversion sequences for each of the
6180  // arguments.
6181  Candidate.Viable = true;
6182  Candidate.ExplicitCallArguments = Args.size();
6183  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6184    // C++ [over.match.oper]p4:
6185    //   For the built-in assignment operators, conversions of the
6186    //   left operand are restricted as follows:
6187    //     -- no temporaries are introduced to hold the left operand, and
6188    //     -- no user-defined conversions are applied to the left
6189    //        operand to achieve a type match with the left-most
6190    //        parameter of a built-in candidate.
6191    //
6192    // We block these conversions by turning off user-defined
6193    // conversions, since that is the only way that initialization of
6194    // a reference to a non-class type can occur from something that
6195    // is not of the same type.
6196    if (ArgIdx < NumContextualBoolArguments) {
6197      assert(ParamTys[ArgIdx] == Context.BoolTy &&
6198             "Contextual conversion to bool requires bool type");
6199      Candidate.Conversions[ArgIdx]
6200        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6201    } else {
6202      Candidate.Conversions[ArgIdx]
6203        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6204                                ArgIdx == 0 && IsAssignmentOperator,
6205                                /*InOverloadResolution=*/false,
6206                                /*AllowObjCWritebackConversion=*/
6207                                  getLangOpts().ObjCAutoRefCount);
6208    }
6209    if (Candidate.Conversions[ArgIdx].isBad()) {
6210      Candidate.Viable = false;
6211      Candidate.FailureKind = ovl_fail_bad_conversion;
6212      break;
6213    }
6214  }
6215}
6216
6217namespace {
6218
6219/// BuiltinCandidateTypeSet - A set of types that will be used for the
6220/// candidate operator functions for built-in operators (C++
6221/// [over.built]). The types are separated into pointer types and
6222/// enumeration types.
6223class BuiltinCandidateTypeSet  {
6224  /// TypeSet - A set of types.
6225  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6226
6227  /// PointerTypes - The set of pointer types that will be used in the
6228  /// built-in candidates.
6229  TypeSet PointerTypes;
6230
6231  /// MemberPointerTypes - The set of member pointer types that will be
6232  /// used in the built-in candidates.
6233  TypeSet MemberPointerTypes;
6234
6235  /// EnumerationTypes - The set of enumeration types that will be
6236  /// used in the built-in candidates.
6237  TypeSet EnumerationTypes;
6238
6239  /// \brief The set of vector types that will be used in the built-in
6240  /// candidates.
6241  TypeSet VectorTypes;
6242
6243  /// \brief A flag indicating non-record types are viable candidates
6244  bool HasNonRecordTypes;
6245
6246  /// \brief A flag indicating whether either arithmetic or enumeration types
6247  /// were present in the candidate set.
6248  bool HasArithmeticOrEnumeralTypes;
6249
6250  /// \brief A flag indicating whether the nullptr type was present in the
6251  /// candidate set.
6252  bool HasNullPtrType;
6253
6254  /// Sema - The semantic analysis instance where we are building the
6255  /// candidate type set.
6256  Sema &SemaRef;
6257
6258  /// Context - The AST context in which we will build the type sets.
6259  ASTContext &Context;
6260
6261  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6262                                               const Qualifiers &VisibleQuals);
6263  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6264
6265public:
6266  /// iterator - Iterates through the types that are part of the set.
6267  typedef TypeSet::iterator iterator;
6268
6269  BuiltinCandidateTypeSet(Sema &SemaRef)
6270    : HasNonRecordTypes(false),
6271      HasArithmeticOrEnumeralTypes(false),
6272      HasNullPtrType(false),
6273      SemaRef(SemaRef),
6274      Context(SemaRef.Context) { }
6275
6276  void AddTypesConvertedFrom(QualType Ty,
6277                             SourceLocation Loc,
6278                             bool AllowUserConversions,
6279                             bool AllowExplicitConversions,
6280                             const Qualifiers &VisibleTypeConversionsQuals);
6281
6282  /// pointer_begin - First pointer type found;
6283  iterator pointer_begin() { return PointerTypes.begin(); }
6284
6285  /// pointer_end - Past the last pointer type found;
6286  iterator pointer_end() { return PointerTypes.end(); }
6287
6288  /// member_pointer_begin - First member pointer type found;
6289  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6290
6291  /// member_pointer_end - Past the last member pointer type found;
6292  iterator member_pointer_end() { return MemberPointerTypes.end(); }
6293
6294  /// enumeration_begin - First enumeration type found;
6295  iterator enumeration_begin() { return EnumerationTypes.begin(); }
6296
6297  /// enumeration_end - Past the last enumeration type found;
6298  iterator enumeration_end() { return EnumerationTypes.end(); }
6299
6300  iterator vector_begin() { return VectorTypes.begin(); }
6301  iterator vector_end() { return VectorTypes.end(); }
6302
6303  bool hasNonRecordTypes() { return HasNonRecordTypes; }
6304  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6305  bool hasNullPtrType() const { return HasNullPtrType; }
6306};
6307
6308} // end anonymous namespace
6309
6310/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6311/// the set of pointer types along with any more-qualified variants of
6312/// that type. For example, if @p Ty is "int const *", this routine
6313/// will add "int const *", "int const volatile *", "int const
6314/// restrict *", and "int const volatile restrict *" to the set of
6315/// pointer types. Returns true if the add of @p Ty itself succeeded,
6316/// false otherwise.
6317///
6318/// FIXME: what to do about extended qualifiers?
6319bool
6320BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6321                                             const Qualifiers &VisibleQuals) {
6322
6323  // Insert this type.
6324  if (!PointerTypes.insert(Ty))
6325    return false;
6326
6327  QualType PointeeTy;
6328  const PointerType *PointerTy = Ty->getAs<PointerType>();
6329  bool buildObjCPtr = false;
6330  if (!PointerTy) {
6331    const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6332    PointeeTy = PTy->getPointeeType();
6333    buildObjCPtr = true;
6334  } else {
6335    PointeeTy = PointerTy->getPointeeType();
6336  }
6337
6338  // Don't add qualified variants of arrays. For one, they're not allowed
6339  // (the qualifier would sink to the element type), and for another, the
6340  // only overload situation where it matters is subscript or pointer +- int,
6341  // and those shouldn't have qualifier variants anyway.
6342  if (PointeeTy->isArrayType())
6343    return true;
6344
6345  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6346  bool hasVolatile = VisibleQuals.hasVolatile();
6347  bool hasRestrict = VisibleQuals.hasRestrict();
6348
6349  // Iterate through all strict supersets of BaseCVR.
6350  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6351    if ((CVR | BaseCVR) != CVR) continue;
6352    // Skip over volatile if no volatile found anywhere in the types.
6353    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6354
6355    // Skip over restrict if no restrict found anywhere in the types, or if
6356    // the type cannot be restrict-qualified.
6357    if ((CVR & Qualifiers::Restrict) &&
6358        (!hasRestrict ||
6359         (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6360      continue;
6361
6362    // Build qualified pointee type.
6363    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6364
6365    // Build qualified pointer type.
6366    QualType QPointerTy;
6367    if (!buildObjCPtr)
6368      QPointerTy = Context.getPointerType(QPointeeTy);
6369    else
6370      QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6371
6372    // Insert qualified pointer type.
6373    PointerTypes.insert(QPointerTy);
6374  }
6375
6376  return true;
6377}
6378
6379/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6380/// to the set of pointer types along with any more-qualified variants of
6381/// that type. For example, if @p Ty is "int const *", this routine
6382/// will add "int const *", "int const volatile *", "int const
6383/// restrict *", and "int const volatile restrict *" to the set of
6384/// pointer types. Returns true if the add of @p Ty itself succeeded,
6385/// false otherwise.
6386///
6387/// FIXME: what to do about extended qualifiers?
6388bool
6389BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6390    QualType Ty) {
6391  // Insert this type.
6392  if (!MemberPointerTypes.insert(Ty))
6393    return false;
6394
6395  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6396  assert(PointerTy && "type was not a member pointer type!");
6397
6398  QualType PointeeTy = PointerTy->getPointeeType();
6399  // Don't add qualified variants of arrays. For one, they're not allowed
6400  // (the qualifier would sink to the element type), and for another, the
6401  // only overload situation where it matters is subscript or pointer +- int,
6402  // and those shouldn't have qualifier variants anyway.
6403  if (PointeeTy->isArrayType())
6404    return true;
6405  const Type *ClassTy = PointerTy->getClass();
6406
6407  // Iterate through all strict supersets of the pointee type's CVR
6408  // qualifiers.
6409  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6410  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6411    if ((CVR | BaseCVR) != CVR) continue;
6412
6413    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6414    MemberPointerTypes.insert(
6415      Context.getMemberPointerType(QPointeeTy, ClassTy));
6416  }
6417
6418  return true;
6419}
6420
6421/// AddTypesConvertedFrom - Add each of the types to which the type @p
6422/// Ty can be implicit converted to the given set of @p Types. We're
6423/// primarily interested in pointer types and enumeration types. We also
6424/// take member pointer types, for the conditional operator.
6425/// AllowUserConversions is true if we should look at the conversion
6426/// functions of a class type, and AllowExplicitConversions if we
6427/// should also include the explicit conversion functions of a class
6428/// type.
6429void
6430BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6431                                               SourceLocation Loc,
6432                                               bool AllowUserConversions,
6433                                               bool AllowExplicitConversions,
6434                                               const Qualifiers &VisibleQuals) {
6435  // Only deal with canonical types.
6436  Ty = Context.getCanonicalType(Ty);
6437
6438  // Look through reference types; they aren't part of the type of an
6439  // expression for the purposes of conversions.
6440  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6441    Ty = RefTy->getPointeeType();
6442
6443  // If we're dealing with an array type, decay to the pointer.
6444  if (Ty->isArrayType())
6445    Ty = SemaRef.Context.getArrayDecayedType(Ty);
6446
6447  // Otherwise, we don't care about qualifiers on the type.
6448  Ty = Ty.getLocalUnqualifiedType();
6449
6450  // Flag if we ever add a non-record type.
6451  const RecordType *TyRec = Ty->getAs<RecordType>();
6452  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6453
6454  // Flag if we encounter an arithmetic type.
6455  HasArithmeticOrEnumeralTypes =
6456    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6457
6458  if (Ty->isObjCIdType() || Ty->isObjCClassType())
6459    PointerTypes.insert(Ty);
6460  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6461    // Insert our type, and its more-qualified variants, into the set
6462    // of types.
6463    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6464      return;
6465  } else if (Ty->isMemberPointerType()) {
6466    // Member pointers are far easier, since the pointee can't be converted.
6467    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6468      return;
6469  } else if (Ty->isEnumeralType()) {
6470    HasArithmeticOrEnumeralTypes = true;
6471    EnumerationTypes.insert(Ty);
6472  } else if (Ty->isVectorType()) {
6473    // We treat vector types as arithmetic types in many contexts as an
6474    // extension.
6475    HasArithmeticOrEnumeralTypes = true;
6476    VectorTypes.insert(Ty);
6477  } else if (Ty->isNullPtrType()) {
6478    HasNullPtrType = true;
6479  } else if (AllowUserConversions && TyRec) {
6480    // No conversion functions in incomplete types.
6481    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6482      return;
6483
6484    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6485    std::pair<CXXRecordDecl::conversion_iterator,
6486              CXXRecordDecl::conversion_iterator>
6487      Conversions = ClassDecl->getVisibleConversionFunctions();
6488    for (CXXRecordDecl::conversion_iterator
6489           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6490      NamedDecl *D = I.getDecl();
6491      if (isa<UsingShadowDecl>(D))
6492        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6493
6494      // Skip conversion function templates; they don't tell us anything
6495      // about which builtin types we can convert to.
6496      if (isa<FunctionTemplateDecl>(D))
6497        continue;
6498
6499      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6500      if (AllowExplicitConversions || !Conv->isExplicit()) {
6501        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6502                              VisibleQuals);
6503      }
6504    }
6505  }
6506}
6507
6508/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6509/// the volatile- and non-volatile-qualified assignment operators for the
6510/// given type to the candidate set.
6511static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6512                                                   QualType T,
6513                                                   ArrayRef<Expr *> Args,
6514                                    OverloadCandidateSet &CandidateSet) {
6515  QualType ParamTypes[2];
6516
6517  // T& operator=(T&, T)
6518  ParamTypes[0] = S.Context.getLValueReferenceType(T);
6519  ParamTypes[1] = T;
6520  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6521                        /*IsAssignmentOperator=*/true);
6522
6523  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6524    // volatile T& operator=(volatile T&, T)
6525    ParamTypes[0]
6526      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6527    ParamTypes[1] = T;
6528    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6529                          /*IsAssignmentOperator=*/true);
6530  }
6531}
6532
6533/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6534/// if any, found in visible type conversion functions found in ArgExpr's type.
6535static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6536    Qualifiers VRQuals;
6537    const RecordType *TyRec;
6538    if (const MemberPointerType *RHSMPType =
6539        ArgExpr->getType()->getAs<MemberPointerType>())
6540      TyRec = RHSMPType->getClass()->getAs<RecordType>();
6541    else
6542      TyRec = ArgExpr->getType()->getAs<RecordType>();
6543    if (!TyRec) {
6544      // Just to be safe, assume the worst case.
6545      VRQuals.addVolatile();
6546      VRQuals.addRestrict();
6547      return VRQuals;
6548    }
6549
6550    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6551    if (!ClassDecl->hasDefinition())
6552      return VRQuals;
6553
6554    std::pair<CXXRecordDecl::conversion_iterator,
6555              CXXRecordDecl::conversion_iterator>
6556      Conversions = ClassDecl->getVisibleConversionFunctions();
6557
6558    for (CXXRecordDecl::conversion_iterator
6559           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6560      NamedDecl *D = I.getDecl();
6561      if (isa<UsingShadowDecl>(D))
6562        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6563      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6564        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6565        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6566          CanTy = ResTypeRef->getPointeeType();
6567        // Need to go down the pointer/mempointer chain and add qualifiers
6568        // as see them.
6569        bool done = false;
6570        while (!done) {
6571          if (CanTy.isRestrictQualified())
6572            VRQuals.addRestrict();
6573          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6574            CanTy = ResTypePtr->getPointeeType();
6575          else if (const MemberPointerType *ResTypeMPtr =
6576                CanTy->getAs<MemberPointerType>())
6577            CanTy = ResTypeMPtr->getPointeeType();
6578          else
6579            done = true;
6580          if (CanTy.isVolatileQualified())
6581            VRQuals.addVolatile();
6582          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6583            return VRQuals;
6584        }
6585      }
6586    }
6587    return VRQuals;
6588}
6589
6590namespace {
6591
6592/// \brief Helper class to manage the addition of builtin operator overload
6593/// candidates. It provides shared state and utility methods used throughout
6594/// the process, as well as a helper method to add each group of builtin
6595/// operator overloads from the standard to a candidate set.
6596class BuiltinOperatorOverloadBuilder {
6597  // Common instance state available to all overload candidate addition methods.
6598  Sema &S;
6599  ArrayRef<Expr *> Args;
6600  Qualifiers VisibleTypeConversionsQuals;
6601  bool HasArithmeticOrEnumeralCandidateType;
6602  SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6603  OverloadCandidateSet &CandidateSet;
6604
6605  // Define some constants used to index and iterate over the arithemetic types
6606  // provided via the getArithmeticType() method below.
6607  // The "promoted arithmetic types" are the arithmetic
6608  // types are that preserved by promotion (C++ [over.built]p2).
6609  static const unsigned FirstIntegralType = 3;
6610  static const unsigned LastIntegralType = 20;
6611  static const unsigned FirstPromotedIntegralType = 3,
6612                        LastPromotedIntegralType = 11;
6613  static const unsigned FirstPromotedArithmeticType = 0,
6614                        LastPromotedArithmeticType = 11;
6615  static const unsigned NumArithmeticTypes = 20;
6616
6617  /// \brief Get the canonical type for a given arithmetic type index.
6618  CanQualType getArithmeticType(unsigned index) {
6619    assert(index < NumArithmeticTypes);
6620    static CanQualType ASTContext::* const
6621      ArithmeticTypes[NumArithmeticTypes] = {
6622      // Start of promoted types.
6623      &ASTContext::FloatTy,
6624      &ASTContext::DoubleTy,
6625      &ASTContext::LongDoubleTy,
6626
6627      // Start of integral types.
6628      &ASTContext::IntTy,
6629      &ASTContext::LongTy,
6630      &ASTContext::LongLongTy,
6631      &ASTContext::Int128Ty,
6632      &ASTContext::UnsignedIntTy,
6633      &ASTContext::UnsignedLongTy,
6634      &ASTContext::UnsignedLongLongTy,
6635      &ASTContext::UnsignedInt128Ty,
6636      // End of promoted types.
6637
6638      &ASTContext::BoolTy,
6639      &ASTContext::CharTy,
6640      &ASTContext::WCharTy,
6641      &ASTContext::Char16Ty,
6642      &ASTContext::Char32Ty,
6643      &ASTContext::SignedCharTy,
6644      &ASTContext::ShortTy,
6645      &ASTContext::UnsignedCharTy,
6646      &ASTContext::UnsignedShortTy,
6647      // End of integral types.
6648      // FIXME: What about complex? What about half?
6649    };
6650    return S.Context.*ArithmeticTypes[index];
6651  }
6652
6653  /// \brief Gets the canonical type resulting from the usual arithemetic
6654  /// converions for the given arithmetic types.
6655  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6656    // Accelerator table for performing the usual arithmetic conversions.
6657    // The rules are basically:
6658    //   - if either is floating-point, use the wider floating-point
6659    //   - if same signedness, use the higher rank
6660    //   - if same size, use unsigned of the higher rank
6661    //   - use the larger type
6662    // These rules, together with the axiom that higher ranks are
6663    // never smaller, are sufficient to precompute all of these results
6664    // *except* when dealing with signed types of higher rank.
6665    // (we could precompute SLL x UI for all known platforms, but it's
6666    // better not to make any assumptions).
6667    // We assume that int128 has a higher rank than long long on all platforms.
6668    enum PromotedType {
6669            Dep=-1,
6670            Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6671    };
6672    static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6673                                        [LastPromotedArithmeticType] = {
6674/* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6675/* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6676/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6677/*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6678/*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6679/* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6680/*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6681/*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6682/*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6683/* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6684/*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6685    };
6686
6687    assert(L < LastPromotedArithmeticType);
6688    assert(R < LastPromotedArithmeticType);
6689    int Idx = ConversionsTable[L][R];
6690
6691    // Fast path: the table gives us a concrete answer.
6692    if (Idx != Dep) return getArithmeticType(Idx);
6693
6694    // Slow path: we need to compare widths.
6695    // An invariant is that the signed type has higher rank.
6696    CanQualType LT = getArithmeticType(L),
6697                RT = getArithmeticType(R);
6698    unsigned LW = S.Context.getIntWidth(LT),
6699             RW = S.Context.getIntWidth(RT);
6700
6701    // If they're different widths, use the signed type.
6702    if (LW > RW) return LT;
6703    else if (LW < RW) return RT;
6704
6705    // Otherwise, use the unsigned type of the signed type's rank.
6706    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6707    assert(L == SLL || R == SLL);
6708    return S.Context.UnsignedLongLongTy;
6709  }
6710
6711  /// \brief Helper method to factor out the common pattern of adding overloads
6712  /// for '++' and '--' builtin operators.
6713  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6714                                           bool HasVolatile,
6715                                           bool HasRestrict) {
6716    QualType ParamTypes[2] = {
6717      S.Context.getLValueReferenceType(CandidateTy),
6718      S.Context.IntTy
6719    };
6720
6721    // Non-volatile version.
6722    if (Args.size() == 1)
6723      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6724    else
6725      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6726
6727    // Use a heuristic to reduce number of builtin candidates in the set:
6728    // add volatile version only if there are conversions to a volatile type.
6729    if (HasVolatile) {
6730      ParamTypes[0] =
6731        S.Context.getLValueReferenceType(
6732          S.Context.getVolatileType(CandidateTy));
6733      if (Args.size() == 1)
6734        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6735      else
6736        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6737    }
6738
6739    // Add restrict version only if there are conversions to a restrict type
6740    // and our candidate type is a non-restrict-qualified pointer.
6741    if (HasRestrict && CandidateTy->isAnyPointerType() &&
6742        !CandidateTy.isRestrictQualified()) {
6743      ParamTypes[0]
6744        = S.Context.getLValueReferenceType(
6745            S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6746      if (Args.size() == 1)
6747        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6748      else
6749        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6750
6751      if (HasVolatile) {
6752        ParamTypes[0]
6753          = S.Context.getLValueReferenceType(
6754              S.Context.getCVRQualifiedType(CandidateTy,
6755                                            (Qualifiers::Volatile |
6756                                             Qualifiers::Restrict)));
6757        if (Args.size() == 1)
6758          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6759        else
6760          S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6761      }
6762    }
6763
6764  }
6765
6766public:
6767  BuiltinOperatorOverloadBuilder(
6768    Sema &S, ArrayRef<Expr *> Args,
6769    Qualifiers VisibleTypeConversionsQuals,
6770    bool HasArithmeticOrEnumeralCandidateType,
6771    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6772    OverloadCandidateSet &CandidateSet)
6773    : S(S), Args(Args),
6774      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6775      HasArithmeticOrEnumeralCandidateType(
6776        HasArithmeticOrEnumeralCandidateType),
6777      CandidateTypes(CandidateTypes),
6778      CandidateSet(CandidateSet) {
6779    // Validate some of our static helper constants in debug builds.
6780    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6781           "Invalid first promoted integral type");
6782    assert(getArithmeticType(LastPromotedIntegralType - 1)
6783             == S.Context.UnsignedInt128Ty &&
6784           "Invalid last promoted integral type");
6785    assert(getArithmeticType(FirstPromotedArithmeticType)
6786             == S.Context.FloatTy &&
6787           "Invalid first promoted arithmetic type");
6788    assert(getArithmeticType(LastPromotedArithmeticType - 1)
6789             == S.Context.UnsignedInt128Ty &&
6790           "Invalid last promoted arithmetic type");
6791  }
6792
6793  // C++ [over.built]p3:
6794  //
6795  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6796  //   is either volatile or empty, there exist candidate operator
6797  //   functions of the form
6798  //
6799  //       VQ T&      operator++(VQ T&);
6800  //       T          operator++(VQ T&, int);
6801  //
6802  // C++ [over.built]p4:
6803  //
6804  //   For every pair (T, VQ), where T is an arithmetic type other
6805  //   than bool, and VQ is either volatile or empty, there exist
6806  //   candidate operator functions of the form
6807  //
6808  //       VQ T&      operator--(VQ T&);
6809  //       T          operator--(VQ T&, int);
6810  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6811    if (!HasArithmeticOrEnumeralCandidateType)
6812      return;
6813
6814    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6815         Arith < NumArithmeticTypes; ++Arith) {
6816      addPlusPlusMinusMinusStyleOverloads(
6817        getArithmeticType(Arith),
6818        VisibleTypeConversionsQuals.hasVolatile(),
6819        VisibleTypeConversionsQuals.hasRestrict());
6820    }
6821  }
6822
6823  // C++ [over.built]p5:
6824  //
6825  //   For every pair (T, VQ), where T is a cv-qualified or
6826  //   cv-unqualified object type, and VQ is either volatile or
6827  //   empty, there exist candidate operator functions of the form
6828  //
6829  //       T*VQ&      operator++(T*VQ&);
6830  //       T*VQ&      operator--(T*VQ&);
6831  //       T*         operator++(T*VQ&, int);
6832  //       T*         operator--(T*VQ&, int);
6833  void addPlusPlusMinusMinusPointerOverloads() {
6834    for (BuiltinCandidateTypeSet::iterator
6835              Ptr = CandidateTypes[0].pointer_begin(),
6836           PtrEnd = CandidateTypes[0].pointer_end();
6837         Ptr != PtrEnd; ++Ptr) {
6838      // Skip pointer types that aren't pointers to object types.
6839      if (!(*Ptr)->getPointeeType()->isObjectType())
6840        continue;
6841
6842      addPlusPlusMinusMinusStyleOverloads(*Ptr,
6843        (!(*Ptr).isVolatileQualified() &&
6844         VisibleTypeConversionsQuals.hasVolatile()),
6845        (!(*Ptr).isRestrictQualified() &&
6846         VisibleTypeConversionsQuals.hasRestrict()));
6847    }
6848  }
6849
6850  // C++ [over.built]p6:
6851  //   For every cv-qualified or cv-unqualified object type T, there
6852  //   exist candidate operator functions of the form
6853  //
6854  //       T&         operator*(T*);
6855  //
6856  // C++ [over.built]p7:
6857  //   For every function type T that does not have cv-qualifiers or a
6858  //   ref-qualifier, there exist candidate operator functions of the form
6859  //       T&         operator*(T*);
6860  void addUnaryStarPointerOverloads() {
6861    for (BuiltinCandidateTypeSet::iterator
6862              Ptr = CandidateTypes[0].pointer_begin(),
6863           PtrEnd = CandidateTypes[0].pointer_end();
6864         Ptr != PtrEnd; ++Ptr) {
6865      QualType ParamTy = *Ptr;
6866      QualType PointeeTy = ParamTy->getPointeeType();
6867      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6868        continue;
6869
6870      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6871        if (Proto->getTypeQuals() || Proto->getRefQualifier())
6872          continue;
6873
6874      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6875                            &ParamTy, Args, CandidateSet);
6876    }
6877  }
6878
6879  // C++ [over.built]p9:
6880  //  For every promoted arithmetic type T, there exist candidate
6881  //  operator functions of the form
6882  //
6883  //       T         operator+(T);
6884  //       T         operator-(T);
6885  void addUnaryPlusOrMinusArithmeticOverloads() {
6886    if (!HasArithmeticOrEnumeralCandidateType)
6887      return;
6888
6889    for (unsigned Arith = FirstPromotedArithmeticType;
6890         Arith < LastPromotedArithmeticType; ++Arith) {
6891      QualType ArithTy = getArithmeticType(Arith);
6892      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
6893    }
6894
6895    // Extension: We also add these operators for vector types.
6896    for (BuiltinCandidateTypeSet::iterator
6897              Vec = CandidateTypes[0].vector_begin(),
6898           VecEnd = CandidateTypes[0].vector_end();
6899         Vec != VecEnd; ++Vec) {
6900      QualType VecTy = *Vec;
6901      S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
6902    }
6903  }
6904
6905  // C++ [over.built]p8:
6906  //   For every type T, there exist candidate operator functions of
6907  //   the form
6908  //
6909  //       T*         operator+(T*);
6910  void addUnaryPlusPointerOverloads() {
6911    for (BuiltinCandidateTypeSet::iterator
6912              Ptr = CandidateTypes[0].pointer_begin(),
6913           PtrEnd = CandidateTypes[0].pointer_end();
6914         Ptr != PtrEnd; ++Ptr) {
6915      QualType ParamTy = *Ptr;
6916      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
6917    }
6918  }
6919
6920  // C++ [over.built]p10:
6921  //   For every promoted integral type T, there exist candidate
6922  //   operator functions of the form
6923  //
6924  //        T         operator~(T);
6925  void addUnaryTildePromotedIntegralOverloads() {
6926    if (!HasArithmeticOrEnumeralCandidateType)
6927      return;
6928
6929    for (unsigned Int = FirstPromotedIntegralType;
6930         Int < LastPromotedIntegralType; ++Int) {
6931      QualType IntTy = getArithmeticType(Int);
6932      S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
6933    }
6934
6935    // Extension: We also add this operator for vector types.
6936    for (BuiltinCandidateTypeSet::iterator
6937              Vec = CandidateTypes[0].vector_begin(),
6938           VecEnd = CandidateTypes[0].vector_end();
6939         Vec != VecEnd; ++Vec) {
6940      QualType VecTy = *Vec;
6941      S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
6942    }
6943  }
6944
6945  // C++ [over.match.oper]p16:
6946  //   For every pointer to member type T, there exist candidate operator
6947  //   functions of the form
6948  //
6949  //        bool operator==(T,T);
6950  //        bool operator!=(T,T);
6951  void addEqualEqualOrNotEqualMemberPointerOverloads() {
6952    /// Set of (canonical) types that we've already handled.
6953    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6954
6955    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6956      for (BuiltinCandidateTypeSet::iterator
6957                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6958             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6959           MemPtr != MemPtrEnd;
6960           ++MemPtr) {
6961        // Don't add the same builtin candidate twice.
6962        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6963          continue;
6964
6965        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6966        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
6967      }
6968    }
6969  }
6970
6971  // C++ [over.built]p15:
6972  //
6973  //   For every T, where T is an enumeration type, a pointer type, or
6974  //   std::nullptr_t, there exist candidate operator functions of the form
6975  //
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  //        bool       operator!=(T, T);
6982  void addRelationalPointerOrEnumeralOverloads() {
6983    // C++ [over.match.oper]p3:
6984    //   [...]the built-in candidates include all of the candidate operator
6985    //   functions defined in 13.6 that, compared to the given operator, [...]
6986    //   do not have the same parameter-type-list as any non-template non-member
6987    //   candidate.
6988    //
6989    // Note that in practice, this only affects enumeration types because there
6990    // aren't any built-in candidates of record type, and a user-defined operator
6991    // must have an operand of record or enumeration type. Also, the only other
6992    // overloaded operator with enumeration arguments, operator=,
6993    // cannot be overloaded for enumeration types, so this is the only place
6994    // where we must suppress candidates like this.
6995    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6996      UserDefinedBinaryOperators;
6997
6998    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6999      if (CandidateTypes[ArgIdx].enumeration_begin() !=
7000          CandidateTypes[ArgIdx].enumeration_end()) {
7001        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7002                                         CEnd = CandidateSet.end();
7003             C != CEnd; ++C) {
7004          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7005            continue;
7006
7007          if (C->Function->isFunctionTemplateSpecialization())
7008            continue;
7009
7010          QualType FirstParamType =
7011            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7012          QualType SecondParamType =
7013            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7014
7015          // Skip if either parameter isn't of enumeral type.
7016          if (!FirstParamType->isEnumeralType() ||
7017              !SecondParamType->isEnumeralType())
7018            continue;
7019
7020          // Add this operator to the set of known user-defined operators.
7021          UserDefinedBinaryOperators.insert(
7022            std::make_pair(S.Context.getCanonicalType(FirstParamType),
7023                           S.Context.getCanonicalType(SecondParamType)));
7024        }
7025      }
7026    }
7027
7028    /// Set of (canonical) types that we've already handled.
7029    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7030
7031    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7032      for (BuiltinCandidateTypeSet::iterator
7033                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7034             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7035           Ptr != PtrEnd; ++Ptr) {
7036        // Don't add the same builtin candidate twice.
7037        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7038          continue;
7039
7040        QualType ParamTypes[2] = { *Ptr, *Ptr };
7041        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7042      }
7043      for (BuiltinCandidateTypeSet::iterator
7044                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7045             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7046           Enum != EnumEnd; ++Enum) {
7047        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7048
7049        // Don't add the same builtin candidate twice, or if a user defined
7050        // candidate exists.
7051        if (!AddedTypes.insert(CanonType) ||
7052            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7053                                                            CanonType)))
7054          continue;
7055
7056        QualType ParamTypes[2] = { *Enum, *Enum };
7057        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7058      }
7059
7060      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7061        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7062        if (AddedTypes.insert(NullPtrTy) &&
7063            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7064                                                             NullPtrTy))) {
7065          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7066          S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7067                                CandidateSet);
7068        }
7069      }
7070    }
7071  }
7072
7073  // C++ [over.built]p13:
7074  //
7075  //   For every cv-qualified or cv-unqualified object type T
7076  //   there exist candidate operator functions of the form
7077  //
7078  //      T*         operator+(T*, ptrdiff_t);
7079  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7080  //      T*         operator-(T*, ptrdiff_t);
7081  //      T*         operator+(ptrdiff_t, T*);
7082  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7083  //
7084  // C++ [over.built]p14:
7085  //
7086  //   For every T, where T is a pointer to object type, there
7087  //   exist candidate operator functions of the form
7088  //
7089  //      ptrdiff_t  operator-(T, T);
7090  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7091    /// Set of (canonical) types that we've already handled.
7092    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7093
7094    for (int Arg = 0; Arg < 2; ++Arg) {
7095      QualType AsymetricParamTypes[2] = {
7096        S.Context.getPointerDiffType(),
7097        S.Context.getPointerDiffType(),
7098      };
7099      for (BuiltinCandidateTypeSet::iterator
7100                Ptr = CandidateTypes[Arg].pointer_begin(),
7101             PtrEnd = CandidateTypes[Arg].pointer_end();
7102           Ptr != PtrEnd; ++Ptr) {
7103        QualType PointeeTy = (*Ptr)->getPointeeType();
7104        if (!PointeeTy->isObjectType())
7105          continue;
7106
7107        AsymetricParamTypes[Arg] = *Ptr;
7108        if (Arg == 0 || Op == OO_Plus) {
7109          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7110          // T* operator+(ptrdiff_t, T*);
7111          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7112        }
7113        if (Op == OO_Minus) {
7114          // ptrdiff_t operator-(T, T);
7115          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7116            continue;
7117
7118          QualType ParamTypes[2] = { *Ptr, *Ptr };
7119          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7120                                Args, CandidateSet);
7121        }
7122      }
7123    }
7124  }
7125
7126  // C++ [over.built]p12:
7127  //
7128  //   For every pair of promoted arithmetic types L and R, there
7129  //   exist candidate operator functions of the form
7130  //
7131  //        LR         operator*(L, R);
7132  //        LR         operator/(L, R);
7133  //        LR         operator+(L, R);
7134  //        LR         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  //        bool       operator!=(L, R);
7141  //
7142  //   where LR is the result of the usual arithmetic conversions
7143  //   between types L and R.
7144  //
7145  // C++ [over.built]p24:
7146  //
7147  //   For every pair of promoted arithmetic types L and R, there exist
7148  //   candidate operator functions of the form
7149  //
7150  //        LR       operator?(bool, L, R);
7151  //
7152  //   where LR is the result of the usual arithmetic conversions
7153  //   between types L and R.
7154  // Our candidates ignore the first parameter.
7155  void addGenericBinaryArithmeticOverloads(bool isComparison) {
7156    if (!HasArithmeticOrEnumeralCandidateType)
7157      return;
7158
7159    for (unsigned Left = FirstPromotedArithmeticType;
7160         Left < LastPromotedArithmeticType; ++Left) {
7161      for (unsigned Right = FirstPromotedArithmeticType;
7162           Right < LastPromotedArithmeticType; ++Right) {
7163        QualType LandR[2] = { getArithmeticType(Left),
7164                              getArithmeticType(Right) };
7165        QualType Result =
7166          isComparison ? S.Context.BoolTy
7167                       : getUsualArithmeticConversions(Left, Right);
7168        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7169      }
7170    }
7171
7172    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7173    // conditional operator for vector types.
7174    for (BuiltinCandidateTypeSet::iterator
7175              Vec1 = CandidateTypes[0].vector_begin(),
7176           Vec1End = CandidateTypes[0].vector_end();
7177         Vec1 != Vec1End; ++Vec1) {
7178      for (BuiltinCandidateTypeSet::iterator
7179                Vec2 = CandidateTypes[1].vector_begin(),
7180             Vec2End = CandidateTypes[1].vector_end();
7181           Vec2 != Vec2End; ++Vec2) {
7182        QualType LandR[2] = { *Vec1, *Vec2 };
7183        QualType Result = S.Context.BoolTy;
7184        if (!isComparison) {
7185          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7186            Result = *Vec1;
7187          else
7188            Result = *Vec2;
7189        }
7190
7191        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7192      }
7193    }
7194  }
7195
7196  // C++ [over.built]p17:
7197  //
7198  //   For every pair of promoted integral types L and R, there
7199  //   exist candidate operator functions of the form
7200  //
7201  //      LR         operator%(L, R);
7202  //      LR         operator&(L, R);
7203  //      LR         operator^(L, R);
7204  //      LR         operator|(L, R);
7205  //      L          operator<<(L, R);
7206  //      L          operator>>(L, R);
7207  //
7208  //   where LR is the result of the usual arithmetic conversions
7209  //   between types L and R.
7210  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7211    if (!HasArithmeticOrEnumeralCandidateType)
7212      return;
7213
7214    for (unsigned Left = FirstPromotedIntegralType;
7215         Left < LastPromotedIntegralType; ++Left) {
7216      for (unsigned Right = FirstPromotedIntegralType;
7217           Right < LastPromotedIntegralType; ++Right) {
7218        QualType LandR[2] = { getArithmeticType(Left),
7219                              getArithmeticType(Right) };
7220        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7221            ? LandR[0]
7222            : getUsualArithmeticConversions(Left, Right);
7223        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7224      }
7225    }
7226  }
7227
7228  // C++ [over.built]p20:
7229  //
7230  //   For every pair (T, VQ), where T is an enumeration or
7231  //   pointer to member type and VQ is either volatile or
7232  //   empty, there exist candidate operator functions of the form
7233  //
7234  //        VQ T&      operator=(VQ T&, T);
7235  void addAssignmentMemberPointerOrEnumeralOverloads() {
7236    /// Set of (canonical) types that we've already handled.
7237    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7238
7239    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7240      for (BuiltinCandidateTypeSet::iterator
7241                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7242             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7243           Enum != EnumEnd; ++Enum) {
7244        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7245          continue;
7246
7247        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7248      }
7249
7250      for (BuiltinCandidateTypeSet::iterator
7251                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7252             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7253           MemPtr != MemPtrEnd; ++MemPtr) {
7254        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7255          continue;
7256
7257        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7258      }
7259    }
7260  }
7261
7262  // C++ [over.built]p19:
7263  //
7264  //   For every pair (T, VQ), where T is any type and VQ is either
7265  //   volatile or empty, there exist candidate operator functions
7266  //   of the form
7267  //
7268  //        T*VQ&      operator=(T*VQ&, T*);
7269  //
7270  // C++ [over.built]p21:
7271  //
7272  //   For every pair (T, VQ), where T is a cv-qualified or
7273  //   cv-unqualified object type and VQ is either volatile or
7274  //   empty, there exist candidate operator functions of the form
7275  //
7276  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7277  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7278  void addAssignmentPointerOverloads(bool isEqualOp) {
7279    /// Set of (canonical) types that we've already handled.
7280    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7281
7282    for (BuiltinCandidateTypeSet::iterator
7283              Ptr = CandidateTypes[0].pointer_begin(),
7284           PtrEnd = CandidateTypes[0].pointer_end();
7285         Ptr != PtrEnd; ++Ptr) {
7286      // If this is operator=, keep track of the builtin candidates we added.
7287      if (isEqualOp)
7288        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7289      else if (!(*Ptr)->getPointeeType()->isObjectType())
7290        continue;
7291
7292      // non-volatile version
7293      QualType ParamTypes[2] = {
7294        S.Context.getLValueReferenceType(*Ptr),
7295        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7296      };
7297      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7298                            /*IsAssigmentOperator=*/ isEqualOp);
7299
7300      bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7301                          VisibleTypeConversionsQuals.hasVolatile();
7302      if (NeedVolatile) {
7303        // volatile version
7304        ParamTypes[0] =
7305          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7306        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7307                              /*IsAssigmentOperator=*/isEqualOp);
7308      }
7309
7310      if (!(*Ptr).isRestrictQualified() &&
7311          VisibleTypeConversionsQuals.hasRestrict()) {
7312        // restrict version
7313        ParamTypes[0]
7314          = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7315        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7316                              /*IsAssigmentOperator=*/isEqualOp);
7317
7318        if (NeedVolatile) {
7319          // volatile restrict version
7320          ParamTypes[0]
7321            = S.Context.getLValueReferenceType(
7322                S.Context.getCVRQualifiedType(*Ptr,
7323                                              (Qualifiers::Volatile |
7324                                               Qualifiers::Restrict)));
7325          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7326                                /*IsAssigmentOperator=*/isEqualOp);
7327        }
7328      }
7329    }
7330
7331    if (isEqualOp) {
7332      for (BuiltinCandidateTypeSet::iterator
7333                Ptr = CandidateTypes[1].pointer_begin(),
7334             PtrEnd = CandidateTypes[1].pointer_end();
7335           Ptr != PtrEnd; ++Ptr) {
7336        // Make sure we don't add the same candidate twice.
7337        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7338          continue;
7339
7340        QualType ParamTypes[2] = {
7341          S.Context.getLValueReferenceType(*Ptr),
7342          *Ptr,
7343        };
7344
7345        // non-volatile version
7346        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7347                              /*IsAssigmentOperator=*/true);
7348
7349        bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7350                           VisibleTypeConversionsQuals.hasVolatile();
7351        if (NeedVolatile) {
7352          // volatile version
7353          ParamTypes[0] =
7354            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7355          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7356                                /*IsAssigmentOperator=*/true);
7357        }
7358
7359        if (!(*Ptr).isRestrictQualified() &&
7360            VisibleTypeConversionsQuals.hasRestrict()) {
7361          // restrict version
7362          ParamTypes[0]
7363            = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7364          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7365                                /*IsAssigmentOperator=*/true);
7366
7367          if (NeedVolatile) {
7368            // volatile restrict version
7369            ParamTypes[0]
7370              = S.Context.getLValueReferenceType(
7371                  S.Context.getCVRQualifiedType(*Ptr,
7372                                                (Qualifiers::Volatile |
7373                                                 Qualifiers::Restrict)));
7374            S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7375                                  /*IsAssigmentOperator=*/true);
7376          }
7377        }
7378      }
7379    }
7380  }
7381
7382  // C++ [over.built]p18:
7383  //
7384  //   For every triple (L, VQ, R), where L is an arithmetic type,
7385  //   VQ is either volatile or empty, and R is a promoted
7386  //   arithmetic type, there exist candidate operator functions of
7387  //   the form
7388  //
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  //        VQ L&      operator-=(VQ L&, R);
7394  void addAssignmentArithmeticOverloads(bool isEqualOp) {
7395    if (!HasArithmeticOrEnumeralCandidateType)
7396      return;
7397
7398    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7399      for (unsigned Right = FirstPromotedArithmeticType;
7400           Right < LastPromotedArithmeticType; ++Right) {
7401        QualType ParamTypes[2];
7402        ParamTypes[1] = getArithmeticType(Right);
7403
7404        // Add this built-in operator as a candidate (VQ is empty).
7405        ParamTypes[0] =
7406          S.Context.getLValueReferenceType(getArithmeticType(Left));
7407        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7408                              /*IsAssigmentOperator=*/isEqualOp);
7409
7410        // Add this built-in operator as a candidate (VQ is 'volatile').
7411        if (VisibleTypeConversionsQuals.hasVolatile()) {
7412          ParamTypes[0] =
7413            S.Context.getVolatileType(getArithmeticType(Left));
7414          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7415          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7416                                /*IsAssigmentOperator=*/isEqualOp);
7417        }
7418      }
7419    }
7420
7421    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7422    for (BuiltinCandidateTypeSet::iterator
7423              Vec1 = CandidateTypes[0].vector_begin(),
7424           Vec1End = CandidateTypes[0].vector_end();
7425         Vec1 != Vec1End; ++Vec1) {
7426      for (BuiltinCandidateTypeSet::iterator
7427                Vec2 = CandidateTypes[1].vector_begin(),
7428             Vec2End = CandidateTypes[1].vector_end();
7429           Vec2 != Vec2End; ++Vec2) {
7430        QualType ParamTypes[2];
7431        ParamTypes[1] = *Vec2;
7432        // Add this built-in operator as a candidate (VQ is empty).
7433        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7434        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7435                              /*IsAssigmentOperator=*/isEqualOp);
7436
7437        // Add this built-in operator as a candidate (VQ is 'volatile').
7438        if (VisibleTypeConversionsQuals.hasVolatile()) {
7439          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7440          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7441          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7442                                /*IsAssigmentOperator=*/isEqualOp);
7443        }
7444      }
7445    }
7446  }
7447
7448  // C++ [over.built]p22:
7449  //
7450  //   For every triple (L, VQ, R), where L is an integral type, VQ
7451  //   is either volatile or empty, and R is a promoted integral
7452  //   type, there exist candidate operator functions of the form
7453  //
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  //        VQ L&       operator|=(VQ L&, R);
7460  void addAssignmentIntegralOverloads() {
7461    if (!HasArithmeticOrEnumeralCandidateType)
7462      return;
7463
7464    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7465      for (unsigned Right = FirstPromotedIntegralType;
7466           Right < LastPromotedIntegralType; ++Right) {
7467        QualType ParamTypes[2];
7468        ParamTypes[1] = getArithmeticType(Right);
7469
7470        // Add this built-in operator as a candidate (VQ is empty).
7471        ParamTypes[0] =
7472          S.Context.getLValueReferenceType(getArithmeticType(Left));
7473        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7474        if (VisibleTypeConversionsQuals.hasVolatile()) {
7475          // Add this built-in operator as a candidate (VQ is 'volatile').
7476          ParamTypes[0] = getArithmeticType(Left);
7477          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7478          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7479          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7480        }
7481      }
7482    }
7483  }
7484
7485  // C++ [over.operator]p23:
7486  //
7487  //   There also exist candidate operator functions of the form
7488  //
7489  //        bool        operator!(bool);
7490  //        bool        operator&&(bool, bool);
7491  //        bool        operator||(bool, bool);
7492  void addExclaimOverload() {
7493    QualType ParamTy = S.Context.BoolTy;
7494    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7495                          /*IsAssignmentOperator=*/false,
7496                          /*NumContextualBoolArguments=*/1);
7497  }
7498  void addAmpAmpOrPipePipeOverload() {
7499    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7500    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7501                          /*IsAssignmentOperator=*/false,
7502                          /*NumContextualBoolArguments=*/2);
7503  }
7504
7505  // C++ [over.built]p13:
7506  //
7507  //   For every cv-qualified or cv-unqualified object type T there
7508  //   exist candidate operator functions of the form
7509  //
7510  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7511  //        T&         operator[](T*, ptrdiff_t);
7512  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7513  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7514  //        T&         operator[](ptrdiff_t, T*);
7515  void addSubscriptOverloads() {
7516    for (BuiltinCandidateTypeSet::iterator
7517              Ptr = CandidateTypes[0].pointer_begin(),
7518           PtrEnd = CandidateTypes[0].pointer_end();
7519         Ptr != PtrEnd; ++Ptr) {
7520      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7521      QualType PointeeType = (*Ptr)->getPointeeType();
7522      if (!PointeeType->isObjectType())
7523        continue;
7524
7525      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7526
7527      // T& operator[](T*, ptrdiff_t)
7528      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7529    }
7530
7531    for (BuiltinCandidateTypeSet::iterator
7532              Ptr = CandidateTypes[1].pointer_begin(),
7533           PtrEnd = CandidateTypes[1].pointer_end();
7534         Ptr != PtrEnd; ++Ptr) {
7535      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7536      QualType PointeeType = (*Ptr)->getPointeeType();
7537      if (!PointeeType->isObjectType())
7538        continue;
7539
7540      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7541
7542      // T& operator[](ptrdiff_t, T*)
7543      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7544    }
7545  }
7546
7547  // C++ [over.built]p11:
7548  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7549  //    C1 is the same type as C2 or is a derived class of C2, T is an object
7550  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7551  //    there exist candidate operator functions of the form
7552  //
7553  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7554  //
7555  //    where CV12 is the union of CV1 and CV2.
7556  void addArrowStarOverloads() {
7557    for (BuiltinCandidateTypeSet::iterator
7558             Ptr = CandidateTypes[0].pointer_begin(),
7559           PtrEnd = CandidateTypes[0].pointer_end();
7560         Ptr != PtrEnd; ++Ptr) {
7561      QualType C1Ty = (*Ptr);
7562      QualType C1;
7563      QualifierCollector Q1;
7564      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7565      if (!isa<RecordType>(C1))
7566        continue;
7567      // heuristic to reduce number of builtin candidates in the set.
7568      // Add volatile/restrict version only if there are conversions to a
7569      // volatile/restrict type.
7570      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7571        continue;
7572      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7573        continue;
7574      for (BuiltinCandidateTypeSet::iterator
7575                MemPtr = CandidateTypes[1].member_pointer_begin(),
7576             MemPtrEnd = CandidateTypes[1].member_pointer_end();
7577           MemPtr != MemPtrEnd; ++MemPtr) {
7578        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7579        QualType C2 = QualType(mptr->getClass(), 0);
7580        C2 = C2.getUnqualifiedType();
7581        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7582          break;
7583        QualType ParamTypes[2] = { *Ptr, *MemPtr };
7584        // build CV12 T&
7585        QualType T = mptr->getPointeeType();
7586        if (!VisibleTypeConversionsQuals.hasVolatile() &&
7587            T.isVolatileQualified())
7588          continue;
7589        if (!VisibleTypeConversionsQuals.hasRestrict() &&
7590            T.isRestrictQualified())
7591          continue;
7592        T = Q1.apply(S.Context, T);
7593        QualType ResultTy = S.Context.getLValueReferenceType(T);
7594        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7595      }
7596    }
7597  }
7598
7599  // Note that we don't consider the first argument, since it has been
7600  // contextually converted to bool long ago. The candidates below are
7601  // therefore added as binary.
7602  //
7603  // C++ [over.built]p25:
7604  //   For every type T, where T is a pointer, pointer-to-member, or scoped
7605  //   enumeration type, there exist candidate operator functions of the form
7606  //
7607  //        T        operator?(bool, T, T);
7608  //
7609  void addConditionalOperatorOverloads() {
7610    /// Set of (canonical) types that we've already handled.
7611    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7612
7613    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7614      for (BuiltinCandidateTypeSet::iterator
7615                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7616             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7617           Ptr != PtrEnd; ++Ptr) {
7618        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7619          continue;
7620
7621        QualType ParamTypes[2] = { *Ptr, *Ptr };
7622        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
7623      }
7624
7625      for (BuiltinCandidateTypeSet::iterator
7626                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7627             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7628           MemPtr != MemPtrEnd; ++MemPtr) {
7629        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7630          continue;
7631
7632        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7633        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
7634      }
7635
7636      if (S.getLangOpts().CPlusPlus11) {
7637        for (BuiltinCandidateTypeSet::iterator
7638                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7639               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7640             Enum != EnumEnd; ++Enum) {
7641          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7642            continue;
7643
7644          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7645            continue;
7646
7647          QualType ParamTypes[2] = { *Enum, *Enum };
7648          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
7649        }
7650      }
7651    }
7652  }
7653};
7654
7655} // end anonymous namespace
7656
7657/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7658/// operator overloads to the candidate set (C++ [over.built]), based
7659/// on the operator @p Op and the arguments given. For example, if the
7660/// operator is a binary '+', this routine might add "int
7661/// operator+(int, int)" to cover integer addition.
7662void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7663                                        SourceLocation OpLoc,
7664                                        ArrayRef<Expr *> Args,
7665                                        OverloadCandidateSet &CandidateSet) {
7666  // Find all of the types that the arguments can convert to, but only
7667  // if the operator we're looking at has built-in operator candidates
7668  // that make use of these types. Also record whether we encounter non-record
7669  // candidate types or either arithmetic or enumeral candidate types.
7670  Qualifiers VisibleTypeConversionsQuals;
7671  VisibleTypeConversionsQuals.addConst();
7672  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7673    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7674
7675  bool HasNonRecordCandidateType = false;
7676  bool HasArithmeticOrEnumeralCandidateType = false;
7677  SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7678  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7679    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7680    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7681                                                 OpLoc,
7682                                                 true,
7683                                                 (Op == OO_Exclaim ||
7684                                                  Op == OO_AmpAmp ||
7685                                                  Op == OO_PipePipe),
7686                                                 VisibleTypeConversionsQuals);
7687    HasNonRecordCandidateType = HasNonRecordCandidateType ||
7688        CandidateTypes[ArgIdx].hasNonRecordTypes();
7689    HasArithmeticOrEnumeralCandidateType =
7690        HasArithmeticOrEnumeralCandidateType ||
7691        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7692  }
7693
7694  // Exit early when no non-record types have been added to the candidate set
7695  // for any of the arguments to the operator.
7696  //
7697  // We can't exit early for !, ||, or &&, since there we have always have
7698  // 'bool' overloads.
7699  if (!HasNonRecordCandidateType &&
7700      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7701    return;
7702
7703  // Setup an object to manage the common state for building overloads.
7704  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
7705                                           VisibleTypeConversionsQuals,
7706                                           HasArithmeticOrEnumeralCandidateType,
7707                                           CandidateTypes, CandidateSet);
7708
7709  // Dispatch over the operation to add in only those overloads which apply.
7710  switch (Op) {
7711  case OO_None:
7712  case NUM_OVERLOADED_OPERATORS:
7713    llvm_unreachable("Expected an overloaded operator");
7714
7715  case OO_New:
7716  case OO_Delete:
7717  case OO_Array_New:
7718  case OO_Array_Delete:
7719  case OO_Call:
7720    llvm_unreachable(
7721                    "Special operators don't use AddBuiltinOperatorCandidates");
7722
7723  case OO_Comma:
7724  case OO_Arrow:
7725    // C++ [over.match.oper]p3:
7726    //   -- For the operator ',', the unary operator '&', or the
7727    //      operator '->', the built-in candidates set is empty.
7728    break;
7729
7730  case OO_Plus: // '+' is either unary or binary
7731    if (Args.size() == 1)
7732      OpBuilder.addUnaryPlusPointerOverloads();
7733    // Fall through.
7734
7735  case OO_Minus: // '-' is either unary or binary
7736    if (Args.size() == 1) {
7737      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7738    } else {
7739      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7740      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7741    }
7742    break;
7743
7744  case OO_Star: // '*' is either unary or binary
7745    if (Args.size() == 1)
7746      OpBuilder.addUnaryStarPointerOverloads();
7747    else
7748      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7749    break;
7750
7751  case OO_Slash:
7752    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7753    break;
7754
7755  case OO_PlusPlus:
7756  case OO_MinusMinus:
7757    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7758    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7759    break;
7760
7761  case OO_EqualEqual:
7762  case OO_ExclaimEqual:
7763    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7764    // Fall through.
7765
7766  case OO_Less:
7767  case OO_Greater:
7768  case OO_LessEqual:
7769  case OO_GreaterEqual:
7770    OpBuilder.addRelationalPointerOrEnumeralOverloads();
7771    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7772    break;
7773
7774  case OO_Percent:
7775  case OO_Caret:
7776  case OO_Pipe:
7777  case OO_LessLess:
7778  case OO_GreaterGreater:
7779    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7780    break;
7781
7782  case OO_Amp: // '&' is either unary or binary
7783    if (Args.size() == 1)
7784      // C++ [over.match.oper]p3:
7785      //   -- For the operator ',', the unary operator '&', or the
7786      //      operator '->', the built-in candidates set is empty.
7787      break;
7788
7789    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7790    break;
7791
7792  case OO_Tilde:
7793    OpBuilder.addUnaryTildePromotedIntegralOverloads();
7794    break;
7795
7796  case OO_Equal:
7797    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7798    // Fall through.
7799
7800  case OO_PlusEqual:
7801  case OO_MinusEqual:
7802    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7803    // Fall through.
7804
7805  case OO_StarEqual:
7806  case OO_SlashEqual:
7807    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7808    break;
7809
7810  case OO_PercentEqual:
7811  case OO_LessLessEqual:
7812  case OO_GreaterGreaterEqual:
7813  case OO_AmpEqual:
7814  case OO_CaretEqual:
7815  case OO_PipeEqual:
7816    OpBuilder.addAssignmentIntegralOverloads();
7817    break;
7818
7819  case OO_Exclaim:
7820    OpBuilder.addExclaimOverload();
7821    break;
7822
7823  case OO_AmpAmp:
7824  case OO_PipePipe:
7825    OpBuilder.addAmpAmpOrPipePipeOverload();
7826    break;
7827
7828  case OO_Subscript:
7829    OpBuilder.addSubscriptOverloads();
7830    break;
7831
7832  case OO_ArrowStar:
7833    OpBuilder.addArrowStarOverloads();
7834    break;
7835
7836  case OO_Conditional:
7837    OpBuilder.addConditionalOperatorOverloads();
7838    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7839    break;
7840  }
7841}
7842
7843/// \brief Add function candidates found via argument-dependent lookup
7844/// to the set of overloading candidates.
7845///
7846/// This routine performs argument-dependent name lookup based on the
7847/// given function name (which may also be an operator name) and adds
7848/// all of the overload candidates found by ADL to the overload
7849/// candidate set (C++ [basic.lookup.argdep]).
7850void
7851Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7852                                           bool Operator, SourceLocation Loc,
7853                                           ArrayRef<Expr *> Args,
7854                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7855                                           OverloadCandidateSet& CandidateSet,
7856                                           bool PartialOverloading) {
7857  ADLResult Fns;
7858
7859  // FIXME: This approach for uniquing ADL results (and removing
7860  // redundant candidates from the set) relies on pointer-equality,
7861  // which means we need to key off the canonical decl.  However,
7862  // always going back to the canonical decl might not get us the
7863  // right set of default arguments.  What default arguments are
7864  // we supposed to consider on ADL candidates, anyway?
7865
7866  // FIXME: Pass in the explicit template arguments?
7867  ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
7868
7869  // Erase all of the candidates we already knew about.
7870  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7871                                   CandEnd = CandidateSet.end();
7872       Cand != CandEnd; ++Cand)
7873    if (Cand->Function) {
7874      Fns.erase(Cand->Function);
7875      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7876        Fns.erase(FunTmpl);
7877    }
7878
7879  // For each of the ADL candidates we found, add it to the overload
7880  // set.
7881  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7882    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7883    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7884      if (ExplicitTemplateArgs)
7885        continue;
7886
7887      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7888                           PartialOverloading);
7889    } else
7890      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7891                                   FoundDecl, ExplicitTemplateArgs,
7892                                   Args, CandidateSet);
7893  }
7894}
7895
7896/// isBetterOverloadCandidate - Determines whether the first overload
7897/// candidate is a better candidate than the second (C++ 13.3.3p1).
7898bool
7899isBetterOverloadCandidate(Sema &S,
7900                          const OverloadCandidate &Cand1,
7901                          const OverloadCandidate &Cand2,
7902                          SourceLocation Loc,
7903                          bool UserDefinedConversion) {
7904  // Define viable functions to be better candidates than non-viable
7905  // functions.
7906  if (!Cand2.Viable)
7907    return Cand1.Viable;
7908  else if (!Cand1.Viable)
7909    return false;
7910
7911  // C++ [over.match.best]p1:
7912  //
7913  //   -- if F is a static member function, ICS1(F) is defined such
7914  //      that ICS1(F) is neither better nor worse than ICS1(G) for
7915  //      any function G, and, symmetrically, ICS1(G) is neither
7916  //      better nor worse than ICS1(F).
7917  unsigned StartArg = 0;
7918  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7919    StartArg = 1;
7920
7921  // C++ [over.match.best]p1:
7922  //   A viable function F1 is defined to be a better function than another
7923  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7924  //   conversion sequence than ICSi(F2), and then...
7925  unsigned NumArgs = Cand1.NumConversions;
7926  assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7927  bool HasBetterConversion = false;
7928  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7929    switch (CompareImplicitConversionSequences(S,
7930                                               Cand1.Conversions[ArgIdx],
7931                                               Cand2.Conversions[ArgIdx])) {
7932    case ImplicitConversionSequence::Better:
7933      // Cand1 has a better conversion sequence.
7934      HasBetterConversion = true;
7935      break;
7936
7937    case ImplicitConversionSequence::Worse:
7938      // Cand1 can't be better than Cand2.
7939      return false;
7940
7941    case ImplicitConversionSequence::Indistinguishable:
7942      // Do nothing.
7943      break;
7944    }
7945  }
7946
7947  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7948  //       ICSj(F2), or, if not that,
7949  if (HasBetterConversion)
7950    return true;
7951
7952  //     - F1 is a non-template function and F2 is a function template
7953  //       specialization, or, if not that,
7954  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7955      Cand2.Function && Cand2.Function->getPrimaryTemplate())
7956    return true;
7957
7958  //   -- F1 and F2 are function template specializations, and the function
7959  //      template for F1 is more specialized than the template for F2
7960  //      according to the partial ordering rules described in 14.5.5.2, or,
7961  //      if not that,
7962  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7963      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7964    if (FunctionTemplateDecl *BetterTemplate
7965          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7966                                         Cand2.Function->getPrimaryTemplate(),
7967                                         Loc,
7968                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7969                                                             : TPOC_Call,
7970                                         Cand1.ExplicitCallArguments,
7971                                         Cand2.ExplicitCallArguments))
7972      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7973  }
7974
7975  //   -- the context is an initialization by user-defined conversion
7976  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7977  //      from the return type of F1 to the destination type (i.e.,
7978  //      the type of the entity being initialized) is a better
7979  //      conversion sequence than the standard conversion sequence
7980  //      from the return type of F2 to the destination type.
7981  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7982      isa<CXXConversionDecl>(Cand1.Function) &&
7983      isa<CXXConversionDecl>(Cand2.Function)) {
7984    // First check whether we prefer one of the conversion functions over the
7985    // other. This only distinguishes the results in non-standard, extension
7986    // cases such as the conversion from a lambda closure type to a function
7987    // pointer or block.
7988    ImplicitConversionSequence::CompareKind FuncResult
7989      = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7990    if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7991      return FuncResult;
7992
7993    switch (CompareStandardConversionSequences(S,
7994                                               Cand1.FinalConversion,
7995                                               Cand2.FinalConversion)) {
7996    case ImplicitConversionSequence::Better:
7997      // Cand1 has a better conversion sequence.
7998      return true;
7999
8000    case ImplicitConversionSequence::Worse:
8001      // Cand1 can't be better than Cand2.
8002      return false;
8003
8004    case ImplicitConversionSequence::Indistinguishable:
8005      // Do nothing
8006      break;
8007    }
8008  }
8009
8010  return false;
8011}
8012
8013/// \brief Computes the best viable function (C++ 13.3.3)
8014/// within an overload candidate set.
8015///
8016/// \param Loc The location of the function name (or operator symbol) for
8017/// which overload resolution occurs.
8018///
8019/// \param Best If overload resolution was successful or found a deleted
8020/// function, \p Best points to the candidate function found.
8021///
8022/// \returns The result of overload resolution.
8023OverloadingResult
8024OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8025                                         iterator &Best,
8026                                         bool UserDefinedConversion) {
8027  // Find the best viable function.
8028  Best = end();
8029  for (iterator Cand = begin(); Cand != end(); ++Cand) {
8030    if (Cand->Viable)
8031      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8032                                                     UserDefinedConversion))
8033        Best = Cand;
8034  }
8035
8036  // If we didn't find any viable functions, abort.
8037  if (Best == end())
8038    return OR_No_Viable_Function;
8039
8040  // Make sure that this function is better than every other viable
8041  // function. If not, we have an ambiguity.
8042  for (iterator Cand = begin(); Cand != end(); ++Cand) {
8043    if (Cand->Viable &&
8044        Cand != Best &&
8045        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8046                                   UserDefinedConversion)) {
8047      Best = end();
8048      return OR_Ambiguous;
8049    }
8050  }
8051
8052  // Best is the best viable function.
8053  if (Best->Function &&
8054      (Best->Function->isDeleted() ||
8055       S.isFunctionConsideredUnavailable(Best->Function)))
8056    return OR_Deleted;
8057
8058  return OR_Success;
8059}
8060
8061namespace {
8062
8063enum OverloadCandidateKind {
8064  oc_function,
8065  oc_method,
8066  oc_constructor,
8067  oc_function_template,
8068  oc_method_template,
8069  oc_constructor_template,
8070  oc_implicit_default_constructor,
8071  oc_implicit_copy_constructor,
8072  oc_implicit_move_constructor,
8073  oc_implicit_copy_assignment,
8074  oc_implicit_move_assignment,
8075  oc_implicit_inherited_constructor
8076};
8077
8078OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8079                                                FunctionDecl *Fn,
8080                                                std::string &Description) {
8081  bool isTemplate = false;
8082
8083  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8084    isTemplate = true;
8085    Description = S.getTemplateArgumentBindingsText(
8086      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8087  }
8088
8089  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8090    if (!Ctor->isImplicit())
8091      return isTemplate ? oc_constructor_template : oc_constructor;
8092
8093    if (Ctor->getInheritedConstructor())
8094      return oc_implicit_inherited_constructor;
8095
8096    if (Ctor->isDefaultConstructor())
8097      return oc_implicit_default_constructor;
8098
8099    if (Ctor->isMoveConstructor())
8100      return oc_implicit_move_constructor;
8101
8102    assert(Ctor->isCopyConstructor() &&
8103           "unexpected sort of implicit constructor");
8104    return oc_implicit_copy_constructor;
8105  }
8106
8107  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8108    // This actually gets spelled 'candidate function' for now, but
8109    // it doesn't hurt to split it out.
8110    if (!Meth->isImplicit())
8111      return isTemplate ? oc_method_template : oc_method;
8112
8113    if (Meth->isMoveAssignmentOperator())
8114      return oc_implicit_move_assignment;
8115
8116    if (Meth->isCopyAssignmentOperator())
8117      return oc_implicit_copy_assignment;
8118
8119    assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8120    return oc_method;
8121  }
8122
8123  return isTemplate ? oc_function_template : oc_function;
8124}
8125
8126void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8127  const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8128  if (!Ctor) return;
8129
8130  Ctor = Ctor->getInheritedConstructor();
8131  if (!Ctor) return;
8132
8133  S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8134}
8135
8136} // end anonymous namespace
8137
8138// Notes the location of an overload candidate.
8139void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8140  std::string FnDesc;
8141  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8142  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8143                             << (unsigned) K << FnDesc;
8144  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8145  Diag(Fn->getLocation(), PD);
8146  MaybeEmitInheritedConstructorNote(*this, Fn);
8147}
8148
8149//Notes the location of all overload candidates designated through
8150// OverloadedExpr
8151void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8152  assert(OverloadedExpr->getType() == Context.OverloadTy);
8153
8154  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8155  OverloadExpr *OvlExpr = Ovl.Expression;
8156
8157  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8158                            IEnd = OvlExpr->decls_end();
8159       I != IEnd; ++I) {
8160    if (FunctionTemplateDecl *FunTmpl =
8161                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8162      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8163    } else if (FunctionDecl *Fun
8164                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8165      NoteOverloadCandidate(Fun, DestType);
8166    }
8167  }
8168}
8169
8170/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8171/// "lead" diagnostic; it will be given two arguments, the source and
8172/// target types of the conversion.
8173void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8174                                 Sema &S,
8175                                 SourceLocation CaretLoc,
8176                                 const PartialDiagnostic &PDiag) const {
8177  S.Diag(CaretLoc, PDiag)
8178    << Ambiguous.getFromType() << Ambiguous.getToType();
8179  // FIXME: The note limiting machinery is borrowed from
8180  // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8181  // refactoring here.
8182  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8183  unsigned CandsShown = 0;
8184  AmbiguousConversionSequence::const_iterator I, E;
8185  for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8186    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8187      break;
8188    ++CandsShown;
8189    S.NoteOverloadCandidate(*I);
8190  }
8191  if (I != E)
8192    S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8193}
8194
8195namespace {
8196
8197void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8198  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8199  assert(Conv.isBad());
8200  assert(Cand->Function && "for now, candidate must be a function");
8201  FunctionDecl *Fn = Cand->Function;
8202
8203  // There's a conversion slot for the object argument if this is a
8204  // non-constructor method.  Note that 'I' corresponds the
8205  // conversion-slot index.
8206  bool isObjectArgument = false;
8207  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8208    if (I == 0)
8209      isObjectArgument = true;
8210    else
8211      I--;
8212  }
8213
8214  std::string FnDesc;
8215  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8216
8217  Expr *FromExpr = Conv.Bad.FromExpr;
8218  QualType FromTy = Conv.Bad.getFromType();
8219  QualType ToTy = Conv.Bad.getToType();
8220
8221  if (FromTy == S.Context.OverloadTy) {
8222    assert(FromExpr && "overload set argument came from implicit argument?");
8223    Expr *E = FromExpr->IgnoreParens();
8224    if (isa<UnaryOperator>(E))
8225      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8226    DeclarationName Name = cast<OverloadExpr>(E)->getName();
8227
8228    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8229      << (unsigned) FnKind << FnDesc
8230      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8231      << ToTy << Name << I+1;
8232    MaybeEmitInheritedConstructorNote(S, Fn);
8233    return;
8234  }
8235
8236  // Do some hand-waving analysis to see if the non-viability is due
8237  // to a qualifier mismatch.
8238  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8239  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8240  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8241    CToTy = RT->getPointeeType();
8242  else {
8243    // TODO: detect and diagnose the full richness of const mismatches.
8244    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8245      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8246        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8247  }
8248
8249  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8250      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8251    Qualifiers FromQs = CFromTy.getQualifiers();
8252    Qualifiers ToQs = CToTy.getQualifiers();
8253
8254    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8255      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8256        << (unsigned) FnKind << FnDesc
8257        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8258        << FromTy
8259        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8260        << (unsigned) isObjectArgument << I+1;
8261      MaybeEmitInheritedConstructorNote(S, Fn);
8262      return;
8263    }
8264
8265    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8266      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8267        << (unsigned) FnKind << FnDesc
8268        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8269        << FromTy
8270        << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8271        << (unsigned) isObjectArgument << I+1;
8272      MaybeEmitInheritedConstructorNote(S, Fn);
8273      return;
8274    }
8275
8276    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8277      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8278      << (unsigned) FnKind << FnDesc
8279      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8280      << FromTy
8281      << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8282      << (unsigned) isObjectArgument << I+1;
8283      MaybeEmitInheritedConstructorNote(S, Fn);
8284      return;
8285    }
8286
8287    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8288    assert(CVR && "unexpected qualifiers mismatch");
8289
8290    if (isObjectArgument) {
8291      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8292        << (unsigned) FnKind << FnDesc
8293        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8294        << FromTy << (CVR - 1);
8295    } else {
8296      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8297        << (unsigned) FnKind << FnDesc
8298        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8299        << FromTy << (CVR - 1) << I+1;
8300    }
8301    MaybeEmitInheritedConstructorNote(S, Fn);
8302    return;
8303  }
8304
8305  // Special diagnostic for failure to convert an initializer list, since
8306  // telling the user that it has type void is not useful.
8307  if (FromExpr && isa<InitListExpr>(FromExpr)) {
8308    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8309      << (unsigned) FnKind << FnDesc
8310      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8311      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8312    MaybeEmitInheritedConstructorNote(S, Fn);
8313    return;
8314  }
8315
8316  // Diagnose references or pointers to incomplete types differently,
8317  // since it's far from impossible that the incompleteness triggered
8318  // the failure.
8319  QualType TempFromTy = FromTy.getNonReferenceType();
8320  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8321    TempFromTy = PTy->getPointeeType();
8322  if (TempFromTy->isIncompleteType()) {
8323    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8324      << (unsigned) FnKind << FnDesc
8325      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8326      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8327    MaybeEmitInheritedConstructorNote(S, Fn);
8328    return;
8329  }
8330
8331  // Diagnose base -> derived pointer conversions.
8332  unsigned BaseToDerivedConversion = 0;
8333  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8334    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8335      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8336                                               FromPtrTy->getPointeeType()) &&
8337          !FromPtrTy->getPointeeType()->isIncompleteType() &&
8338          !ToPtrTy->getPointeeType()->isIncompleteType() &&
8339          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8340                          FromPtrTy->getPointeeType()))
8341        BaseToDerivedConversion = 1;
8342    }
8343  } else if (const ObjCObjectPointerType *FromPtrTy
8344                                    = FromTy->getAs<ObjCObjectPointerType>()) {
8345    if (const ObjCObjectPointerType *ToPtrTy
8346                                        = ToTy->getAs<ObjCObjectPointerType>())
8347      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8348        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8349          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8350                                                FromPtrTy->getPointeeType()) &&
8351              FromIface->isSuperClassOf(ToIface))
8352            BaseToDerivedConversion = 2;
8353  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8354    if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8355        !FromTy->isIncompleteType() &&
8356        !ToRefTy->getPointeeType()->isIncompleteType() &&
8357        S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8358      BaseToDerivedConversion = 3;
8359    } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8360               ToTy.getNonReferenceType().getCanonicalType() ==
8361               FromTy.getNonReferenceType().getCanonicalType()) {
8362      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8363        << (unsigned) FnKind << FnDesc
8364        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8365        << (unsigned) isObjectArgument << I + 1;
8366      MaybeEmitInheritedConstructorNote(S, Fn);
8367      return;
8368    }
8369  }
8370
8371  if (BaseToDerivedConversion) {
8372    S.Diag(Fn->getLocation(),
8373           diag::note_ovl_candidate_bad_base_to_derived_conv)
8374      << (unsigned) FnKind << FnDesc
8375      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8376      << (BaseToDerivedConversion - 1)
8377      << FromTy << ToTy << I+1;
8378    MaybeEmitInheritedConstructorNote(S, Fn);
8379    return;
8380  }
8381
8382  if (isa<ObjCObjectPointerType>(CFromTy) &&
8383      isa<PointerType>(CToTy)) {
8384      Qualifiers FromQs = CFromTy.getQualifiers();
8385      Qualifiers ToQs = CToTy.getQualifiers();
8386      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8387        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8388        << (unsigned) FnKind << FnDesc
8389        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8390        << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8391        MaybeEmitInheritedConstructorNote(S, Fn);
8392        return;
8393      }
8394  }
8395
8396  // Emit the generic diagnostic and, optionally, add the hints to it.
8397  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8398  FDiag << (unsigned) FnKind << FnDesc
8399    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8400    << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8401    << (unsigned) (Cand->Fix.Kind);
8402
8403  // If we can fix the conversion, suggest the FixIts.
8404  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8405       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8406    FDiag << *HI;
8407  S.Diag(Fn->getLocation(), FDiag);
8408
8409  MaybeEmitInheritedConstructorNote(S, Fn);
8410}
8411
8412/// Additional arity mismatch diagnosis specific to a function overload
8413/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8414/// over a candidate in any candidate set.
8415bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8416                        unsigned NumArgs) {
8417  FunctionDecl *Fn = Cand->Function;
8418  unsigned MinParams = Fn->getMinRequiredArguments();
8419
8420  // With invalid overloaded operators, it's possible that we think we
8421  // have an arity mismatch when in fact it looks like we have the
8422  // right number of arguments, because only overloaded operators have
8423  // the weird behavior of overloading member and non-member functions.
8424  // Just don't report anything.
8425  if (Fn->isInvalidDecl() &&
8426      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8427    return true;
8428
8429  if (NumArgs < MinParams) {
8430    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8431           (Cand->FailureKind == ovl_fail_bad_deduction &&
8432            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8433  } else {
8434    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8435           (Cand->FailureKind == ovl_fail_bad_deduction &&
8436            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8437  }
8438
8439  return false;
8440}
8441
8442/// General arity mismatch diagnosis over a candidate in a candidate set.
8443void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8444  assert(isa<FunctionDecl>(D) &&
8445      "The templated declaration should at least be a function"
8446      " when diagnosing bad template argument deduction due to too many"
8447      " or too few arguments");
8448
8449  FunctionDecl *Fn = cast<FunctionDecl>(D);
8450
8451  // TODO: treat calls to a missing default constructor as a special case
8452  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8453  unsigned MinParams = Fn->getMinRequiredArguments();
8454
8455  // at least / at most / exactly
8456  unsigned mode, modeCount;
8457  if (NumFormalArgs < MinParams) {
8458    if (MinParams != FnTy->getNumArgs() ||
8459        FnTy->isVariadic() || FnTy->isTemplateVariadic())
8460      mode = 0; // "at least"
8461    else
8462      mode = 2; // "exactly"
8463    modeCount = MinParams;
8464  } else {
8465    if (MinParams != FnTy->getNumArgs())
8466      mode = 1; // "at most"
8467    else
8468      mode = 2; // "exactly"
8469    modeCount = FnTy->getNumArgs();
8470  }
8471
8472  std::string Description;
8473  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8474
8475  if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8476    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8477      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8478      << Fn->getParamDecl(0) << NumFormalArgs;
8479  else
8480    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8481      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8482      << modeCount << NumFormalArgs;
8483  MaybeEmitInheritedConstructorNote(S, Fn);
8484}
8485
8486/// Arity mismatch diagnosis specific to a function overload candidate.
8487void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8488                           unsigned NumFormalArgs) {
8489  if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8490    DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8491}
8492
8493TemplateDecl *getDescribedTemplate(Decl *Templated) {
8494  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8495    return FD->getDescribedFunctionTemplate();
8496  else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8497    return RD->getDescribedClassTemplate();
8498
8499  llvm_unreachable("Unsupported: Getting the described template declaration"
8500                   " for bad deduction diagnosis");
8501}
8502
8503/// Diagnose a failed template-argument deduction.
8504void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8505                          DeductionFailureInfo &DeductionFailure,
8506                          unsigned NumArgs) {
8507  TemplateParameter Param = DeductionFailure.getTemplateParameter();
8508  NamedDecl *ParamD;
8509  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8510  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8511  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8512  switch (DeductionFailure.Result) {
8513  case Sema::TDK_Success:
8514    llvm_unreachable("TDK_success while diagnosing bad deduction");
8515
8516  case Sema::TDK_Incomplete: {
8517    assert(ParamD && "no parameter found for incomplete deduction result");
8518    S.Diag(Templated->getLocation(),
8519           diag::note_ovl_candidate_incomplete_deduction)
8520        << ParamD->getDeclName();
8521    MaybeEmitInheritedConstructorNote(S, Templated);
8522    return;
8523  }
8524
8525  case Sema::TDK_Underqualified: {
8526    assert(ParamD && "no parameter found for bad qualifiers deduction result");
8527    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8528
8529    QualType Param = DeductionFailure.getFirstArg()->getAsType();
8530
8531    // Param will have been canonicalized, but it should just be a
8532    // qualified version of ParamD, so move the qualifiers to that.
8533    QualifierCollector Qs;
8534    Qs.strip(Param);
8535    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8536    assert(S.Context.hasSameType(Param, NonCanonParam));
8537
8538    // Arg has also been canonicalized, but there's nothing we can do
8539    // about that.  It also doesn't matter as much, because it won't
8540    // have any template parameters in it (because deduction isn't
8541    // done on dependent types).
8542    QualType Arg = DeductionFailure.getSecondArg()->getAsType();
8543
8544    S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8545        << ParamD->getDeclName() << Arg << NonCanonParam;
8546    MaybeEmitInheritedConstructorNote(S, Templated);
8547    return;
8548  }
8549
8550  case Sema::TDK_Inconsistent: {
8551    assert(ParamD && "no parameter found for inconsistent deduction result");
8552    int which = 0;
8553    if (isa<TemplateTypeParmDecl>(ParamD))
8554      which = 0;
8555    else if (isa<NonTypeTemplateParmDecl>(ParamD))
8556      which = 1;
8557    else {
8558      which = 2;
8559    }
8560
8561    S.Diag(Templated->getLocation(),
8562           diag::note_ovl_candidate_inconsistent_deduction)
8563        << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8564        << *DeductionFailure.getSecondArg();
8565    MaybeEmitInheritedConstructorNote(S, Templated);
8566    return;
8567  }
8568
8569  case Sema::TDK_InvalidExplicitArguments:
8570    assert(ParamD && "no parameter found for invalid explicit arguments");
8571    if (ParamD->getDeclName())
8572      S.Diag(Templated->getLocation(),
8573             diag::note_ovl_candidate_explicit_arg_mismatch_named)
8574          << ParamD->getDeclName();
8575    else {
8576      int index = 0;
8577      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8578        index = TTP->getIndex();
8579      else if (NonTypeTemplateParmDecl *NTTP
8580                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8581        index = NTTP->getIndex();
8582      else
8583        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8584      S.Diag(Templated->getLocation(),
8585             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8586          << (index + 1);
8587    }
8588    MaybeEmitInheritedConstructorNote(S, Templated);
8589    return;
8590
8591  case Sema::TDK_TooManyArguments:
8592  case Sema::TDK_TooFewArguments:
8593    DiagnoseArityMismatch(S, Templated, NumArgs);
8594    return;
8595
8596  case Sema::TDK_InstantiationDepth:
8597    S.Diag(Templated->getLocation(),
8598           diag::note_ovl_candidate_instantiation_depth);
8599    MaybeEmitInheritedConstructorNote(S, Templated);
8600    return;
8601
8602  case Sema::TDK_SubstitutionFailure: {
8603    // Format the template argument list into the argument string.
8604    SmallString<128> TemplateArgString;
8605    if (TemplateArgumentList *Args =
8606            DeductionFailure.getTemplateArgumentList()) {
8607      TemplateArgString = " ";
8608      TemplateArgString += S.getTemplateArgumentBindingsText(
8609          getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
8610    }
8611
8612    // If this candidate was disabled by enable_if, say so.
8613    PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
8614    if (PDiag && PDiag->second.getDiagID() ==
8615          diag::err_typename_nested_not_found_enable_if) {
8616      // FIXME: Use the source range of the condition, and the fully-qualified
8617      //        name of the enable_if template. These are both present in PDiag.
8618      S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8619        << "'enable_if'" << TemplateArgString;
8620      return;
8621    }
8622
8623    // Format the SFINAE diagnostic into the argument string.
8624    // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8625    //        formatted message in another diagnostic.
8626    SmallString<128> SFINAEArgString;
8627    SourceRange R;
8628    if (PDiag) {
8629      SFINAEArgString = ": ";
8630      R = SourceRange(PDiag->first, PDiag->first);
8631      PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8632    }
8633
8634    S.Diag(Templated->getLocation(),
8635           diag::note_ovl_candidate_substitution_failure)
8636        << TemplateArgString << SFINAEArgString << R;
8637    MaybeEmitInheritedConstructorNote(S, Templated);
8638    return;
8639  }
8640
8641  case Sema::TDK_FailedOverloadResolution: {
8642    OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8643    S.Diag(Templated->getLocation(),
8644           diag::note_ovl_candidate_failed_overload_resolution)
8645        << R.Expression->getName();
8646    return;
8647  }
8648
8649  case Sema::TDK_NonDeducedMismatch: {
8650    // FIXME: Provide a source location to indicate what we couldn't match.
8651    TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8652    TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
8653    if (FirstTA.getKind() == TemplateArgument::Template &&
8654        SecondTA.getKind() == TemplateArgument::Template) {
8655      TemplateName FirstTN = FirstTA.getAsTemplate();
8656      TemplateName SecondTN = SecondTA.getAsTemplate();
8657      if (FirstTN.getKind() == TemplateName::Template &&
8658          SecondTN.getKind() == TemplateName::Template) {
8659        if (FirstTN.getAsTemplateDecl()->getName() ==
8660            SecondTN.getAsTemplateDecl()->getName()) {
8661          // FIXME: This fixes a bad diagnostic where both templates are named
8662          // the same.  This particular case is a bit difficult since:
8663          // 1) It is passed as a string to the diagnostic printer.
8664          // 2) The diagnostic printer only attempts to find a better
8665          //    name for types, not decls.
8666          // Ideally, this should folded into the diagnostic printer.
8667          S.Diag(Templated->getLocation(),
8668                 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8669              << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8670          return;
8671        }
8672      }
8673    }
8674    S.Diag(Templated->getLocation(),
8675           diag::note_ovl_candidate_non_deduced_mismatch)
8676        << FirstTA << SecondTA;
8677    return;
8678  }
8679  // TODO: diagnose these individually, then kill off
8680  // note_ovl_candidate_bad_deduction, which is uselessly vague.
8681  case Sema::TDK_MiscellaneousDeductionFailure:
8682    S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8683    MaybeEmitInheritedConstructorNote(S, Templated);
8684    return;
8685  }
8686}
8687
8688/// Diagnose a failed template-argument deduction, for function calls.
8689void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8690  unsigned TDK = Cand->DeductionFailure.Result;
8691  if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8692    if (CheckArityMismatch(S, Cand, NumArgs))
8693      return;
8694  }
8695  DiagnoseBadDeduction(S, Cand->Function, // pattern
8696                       Cand->DeductionFailure, NumArgs);
8697}
8698
8699/// CUDA: diagnose an invalid call across targets.
8700void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8701  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8702  FunctionDecl *Callee = Cand->Function;
8703
8704  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8705                           CalleeTarget = S.IdentifyCUDATarget(Callee);
8706
8707  std::string FnDesc;
8708  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8709
8710  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8711      << (unsigned) FnKind << CalleeTarget << CallerTarget;
8712}
8713
8714/// Generates a 'note' diagnostic for an overload candidate.  We've
8715/// already generated a primary error at the call site.
8716///
8717/// It really does need to be a single diagnostic with its caret
8718/// pointed at the candidate declaration.  Yes, this creates some
8719/// major challenges of technical writing.  Yes, this makes pointing
8720/// out problems with specific arguments quite awkward.  It's still
8721/// better than generating twenty screens of text for every failed
8722/// overload.
8723///
8724/// It would be great to be able to express per-candidate problems
8725/// more richly for those diagnostic clients that cared, but we'd
8726/// still have to be just as careful with the default diagnostics.
8727void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8728                           unsigned NumArgs) {
8729  FunctionDecl *Fn = Cand->Function;
8730
8731  // Note deleted candidates, but only if they're viable.
8732  if (Cand->Viable && (Fn->isDeleted() ||
8733      S.isFunctionConsideredUnavailable(Fn))) {
8734    std::string FnDesc;
8735    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8736
8737    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8738      << FnKind << FnDesc
8739      << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8740    MaybeEmitInheritedConstructorNote(S, Fn);
8741    return;
8742  }
8743
8744  // We don't really have anything else to say about viable candidates.
8745  if (Cand->Viable) {
8746    S.NoteOverloadCandidate(Fn);
8747    return;
8748  }
8749
8750  switch (Cand->FailureKind) {
8751  case ovl_fail_too_many_arguments:
8752  case ovl_fail_too_few_arguments:
8753    return DiagnoseArityMismatch(S, Cand, NumArgs);
8754
8755  case ovl_fail_bad_deduction:
8756    return DiagnoseBadDeduction(S, Cand, NumArgs);
8757
8758  case ovl_fail_trivial_conversion:
8759  case ovl_fail_bad_final_conversion:
8760  case ovl_fail_final_conversion_not_exact:
8761    return S.NoteOverloadCandidate(Fn);
8762
8763  case ovl_fail_bad_conversion: {
8764    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8765    for (unsigned N = Cand->NumConversions; I != N; ++I)
8766      if (Cand->Conversions[I].isBad())
8767        return DiagnoseBadConversion(S, Cand, I);
8768
8769    // FIXME: this currently happens when we're called from SemaInit
8770    // when user-conversion overload fails.  Figure out how to handle
8771    // those conditions and diagnose them well.
8772    return S.NoteOverloadCandidate(Fn);
8773  }
8774
8775  case ovl_fail_bad_target:
8776    return DiagnoseBadTarget(S, Cand);
8777  }
8778}
8779
8780void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8781  // Desugar the type of the surrogate down to a function type,
8782  // retaining as many typedefs as possible while still showing
8783  // the function type (and, therefore, its parameter types).
8784  QualType FnType = Cand->Surrogate->getConversionType();
8785  bool isLValueReference = false;
8786  bool isRValueReference = false;
8787  bool isPointer = false;
8788  if (const LValueReferenceType *FnTypeRef =
8789        FnType->getAs<LValueReferenceType>()) {
8790    FnType = FnTypeRef->getPointeeType();
8791    isLValueReference = true;
8792  } else if (const RValueReferenceType *FnTypeRef =
8793               FnType->getAs<RValueReferenceType>()) {
8794    FnType = FnTypeRef->getPointeeType();
8795    isRValueReference = true;
8796  }
8797  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8798    FnType = FnTypePtr->getPointeeType();
8799    isPointer = true;
8800  }
8801  // Desugar down to a function type.
8802  FnType = QualType(FnType->getAs<FunctionType>(), 0);
8803  // Reconstruct the pointer/reference as appropriate.
8804  if (isPointer) FnType = S.Context.getPointerType(FnType);
8805  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8806  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8807
8808  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8809    << FnType;
8810  MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8811}
8812
8813void NoteBuiltinOperatorCandidate(Sema &S,
8814                                  StringRef Opc,
8815                                  SourceLocation OpLoc,
8816                                  OverloadCandidate *Cand) {
8817  assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8818  std::string TypeStr("operator");
8819  TypeStr += Opc;
8820  TypeStr += "(";
8821  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8822  if (Cand->NumConversions == 1) {
8823    TypeStr += ")";
8824    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8825  } else {
8826    TypeStr += ", ";
8827    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8828    TypeStr += ")";
8829    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8830  }
8831}
8832
8833void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8834                                  OverloadCandidate *Cand) {
8835  unsigned NoOperands = Cand->NumConversions;
8836  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8837    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8838    if (ICS.isBad()) break; // all meaningless after first invalid
8839    if (!ICS.isAmbiguous()) continue;
8840
8841    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8842                              S.PDiag(diag::note_ambiguous_type_conversion));
8843  }
8844}
8845
8846static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8847  if (Cand->Function)
8848    return Cand->Function->getLocation();
8849  if (Cand->IsSurrogate)
8850    return Cand->Surrogate->getLocation();
8851  return SourceLocation();
8852}
8853
8854static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
8855  switch ((Sema::TemplateDeductionResult)DFI.Result) {
8856  case Sema::TDK_Success:
8857    llvm_unreachable("TDK_success while diagnosing bad deduction");
8858
8859  case Sema::TDK_Invalid:
8860  case Sema::TDK_Incomplete:
8861    return 1;
8862
8863  case Sema::TDK_Underqualified:
8864  case Sema::TDK_Inconsistent:
8865    return 2;
8866
8867  case Sema::TDK_SubstitutionFailure:
8868  case Sema::TDK_NonDeducedMismatch:
8869  case Sema::TDK_MiscellaneousDeductionFailure:
8870    return 3;
8871
8872  case Sema::TDK_InstantiationDepth:
8873  case Sema::TDK_FailedOverloadResolution:
8874    return 4;
8875
8876  case Sema::TDK_InvalidExplicitArguments:
8877    return 5;
8878
8879  case Sema::TDK_TooManyArguments:
8880  case Sema::TDK_TooFewArguments:
8881    return 6;
8882  }
8883  llvm_unreachable("Unhandled deduction result");
8884}
8885
8886struct CompareOverloadCandidatesForDisplay {
8887  Sema &S;
8888  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8889
8890  bool operator()(const OverloadCandidate *L,
8891                  const OverloadCandidate *R) {
8892    // Fast-path this check.
8893    if (L == R) return false;
8894
8895    // Order first by viability.
8896    if (L->Viable) {
8897      if (!R->Viable) return true;
8898
8899      // TODO: introduce a tri-valued comparison for overload
8900      // candidates.  Would be more worthwhile if we had a sort
8901      // that could exploit it.
8902      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8903      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8904    } else if (R->Viable)
8905      return false;
8906
8907    assert(L->Viable == R->Viable);
8908
8909    // Criteria by which we can sort non-viable candidates:
8910    if (!L->Viable) {
8911      // 1. Arity mismatches come after other candidates.
8912      if (L->FailureKind == ovl_fail_too_many_arguments ||
8913          L->FailureKind == ovl_fail_too_few_arguments)
8914        return false;
8915      if (R->FailureKind == ovl_fail_too_many_arguments ||
8916          R->FailureKind == ovl_fail_too_few_arguments)
8917        return true;
8918
8919      // 2. Bad conversions come first and are ordered by the number
8920      // of bad conversions and quality of good conversions.
8921      if (L->FailureKind == ovl_fail_bad_conversion) {
8922        if (R->FailureKind != ovl_fail_bad_conversion)
8923          return true;
8924
8925        // The conversion that can be fixed with a smaller number of changes,
8926        // comes first.
8927        unsigned numLFixes = L->Fix.NumConversionsFixed;
8928        unsigned numRFixes = R->Fix.NumConversionsFixed;
8929        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8930        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8931        if (numLFixes != numRFixes) {
8932          if (numLFixes < numRFixes)
8933            return true;
8934          else
8935            return false;
8936        }
8937
8938        // If there's any ordering between the defined conversions...
8939        // FIXME: this might not be transitive.
8940        assert(L->NumConversions == R->NumConversions);
8941
8942        int leftBetter = 0;
8943        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8944        for (unsigned E = L->NumConversions; I != E; ++I) {
8945          switch (CompareImplicitConversionSequences(S,
8946                                                     L->Conversions[I],
8947                                                     R->Conversions[I])) {
8948          case ImplicitConversionSequence::Better:
8949            leftBetter++;
8950            break;
8951
8952          case ImplicitConversionSequence::Worse:
8953            leftBetter--;
8954            break;
8955
8956          case ImplicitConversionSequence::Indistinguishable:
8957            break;
8958          }
8959        }
8960        if (leftBetter > 0) return true;
8961        if (leftBetter < 0) return false;
8962
8963      } else if (R->FailureKind == ovl_fail_bad_conversion)
8964        return false;
8965
8966      if (L->FailureKind == ovl_fail_bad_deduction) {
8967        if (R->FailureKind != ovl_fail_bad_deduction)
8968          return true;
8969
8970        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8971          return RankDeductionFailure(L->DeductionFailure)
8972               < RankDeductionFailure(R->DeductionFailure);
8973      } else if (R->FailureKind == ovl_fail_bad_deduction)
8974        return false;
8975
8976      // TODO: others?
8977    }
8978
8979    // Sort everything else by location.
8980    SourceLocation LLoc = GetLocationForCandidate(L);
8981    SourceLocation RLoc = GetLocationForCandidate(R);
8982
8983    // Put candidates without locations (e.g. builtins) at the end.
8984    if (LLoc.isInvalid()) return false;
8985    if (RLoc.isInvalid()) return true;
8986
8987    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8988  }
8989};
8990
8991/// CompleteNonViableCandidate - Normally, overload resolution only
8992/// computes up to the first. Produces the FixIt set if possible.
8993void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8994                                ArrayRef<Expr *> Args) {
8995  assert(!Cand->Viable);
8996
8997  // Don't do anything on failures other than bad conversion.
8998  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8999
9000  // We only want the FixIts if all the arguments can be corrected.
9001  bool Unfixable = false;
9002  // Use a implicit copy initialization to check conversion fixes.
9003  Cand->Fix.setConversionChecker(TryCopyInitialization);
9004
9005  // Skip forward to the first bad conversion.
9006  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9007  unsigned ConvCount = Cand->NumConversions;
9008  while (true) {
9009    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9010    ConvIdx++;
9011    if (Cand->Conversions[ConvIdx - 1].isBad()) {
9012      Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9013      break;
9014    }
9015  }
9016
9017  if (ConvIdx == ConvCount)
9018    return;
9019
9020  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9021         "remaining conversion is initialized?");
9022
9023  // FIXME: this should probably be preserved from the overload
9024  // operation somehow.
9025  bool SuppressUserConversions = false;
9026
9027  const FunctionProtoType* Proto;
9028  unsigned ArgIdx = ConvIdx;
9029
9030  if (Cand->IsSurrogate) {
9031    QualType ConvType
9032      = Cand->Surrogate->getConversionType().getNonReferenceType();
9033    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9034      ConvType = ConvPtrType->getPointeeType();
9035    Proto = ConvType->getAs<FunctionProtoType>();
9036    ArgIdx--;
9037  } else if (Cand->Function) {
9038    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9039    if (isa<CXXMethodDecl>(Cand->Function) &&
9040        !isa<CXXConstructorDecl>(Cand->Function))
9041      ArgIdx--;
9042  } else {
9043    // Builtin binary operator with a bad first conversion.
9044    assert(ConvCount <= 3);
9045    for (; ConvIdx != ConvCount; ++ConvIdx)
9046      Cand->Conversions[ConvIdx]
9047        = TryCopyInitialization(S, Args[ConvIdx],
9048                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
9049                                SuppressUserConversions,
9050                                /*InOverloadResolution*/ true,
9051                                /*AllowObjCWritebackConversion=*/
9052                                  S.getLangOpts().ObjCAutoRefCount);
9053    return;
9054  }
9055
9056  // Fill in the rest of the conversions.
9057  unsigned NumArgsInProto = Proto->getNumArgs();
9058  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9059    if (ArgIdx < NumArgsInProto) {
9060      Cand->Conversions[ConvIdx]
9061        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
9062                                SuppressUserConversions,
9063                                /*InOverloadResolution=*/true,
9064                                /*AllowObjCWritebackConversion=*/
9065                                  S.getLangOpts().ObjCAutoRefCount);
9066      // Store the FixIt in the candidate if it exists.
9067      if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9068        Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9069    }
9070    else
9071      Cand->Conversions[ConvIdx].setEllipsis();
9072  }
9073}
9074
9075} // end anonymous namespace
9076
9077/// PrintOverloadCandidates - When overload resolution fails, prints
9078/// diagnostic messages containing the candidates in the candidate
9079/// set.
9080void OverloadCandidateSet::NoteCandidates(Sema &S,
9081                                          OverloadCandidateDisplayKind OCD,
9082                                          ArrayRef<Expr *> Args,
9083                                          StringRef Opc,
9084                                          SourceLocation OpLoc) {
9085  // Sort the candidates by viability and position.  Sorting directly would
9086  // be prohibitive, so we make a set of pointers and sort those.
9087  SmallVector<OverloadCandidate*, 32> Cands;
9088  if (OCD == OCD_AllCandidates) Cands.reserve(size());
9089  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9090    if (Cand->Viable)
9091      Cands.push_back(Cand);
9092    else if (OCD == OCD_AllCandidates) {
9093      CompleteNonViableCandidate(S, Cand, Args);
9094      if (Cand->Function || Cand->IsSurrogate)
9095        Cands.push_back(Cand);
9096      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9097      // want to list every possible builtin candidate.
9098    }
9099  }
9100
9101  std::sort(Cands.begin(), Cands.end(),
9102            CompareOverloadCandidatesForDisplay(S));
9103
9104  bool ReportedAmbiguousConversions = false;
9105
9106  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9107  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9108  unsigned CandsShown = 0;
9109  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9110    OverloadCandidate *Cand = *I;
9111
9112    // Set an arbitrary limit on the number of candidate functions we'll spam
9113    // the user with.  FIXME: This limit should depend on details of the
9114    // candidate list.
9115    if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9116      break;
9117    }
9118    ++CandsShown;
9119
9120    if (Cand->Function)
9121      NoteFunctionCandidate(S, Cand, Args.size());
9122    else if (Cand->IsSurrogate)
9123      NoteSurrogateCandidate(S, Cand);
9124    else {
9125      assert(Cand->Viable &&
9126             "Non-viable built-in candidates are not added to Cands.");
9127      // Generally we only see ambiguities including viable builtin
9128      // operators if overload resolution got screwed up by an
9129      // ambiguous user-defined conversion.
9130      //
9131      // FIXME: It's quite possible for different conversions to see
9132      // different ambiguities, though.
9133      if (!ReportedAmbiguousConversions) {
9134        NoteAmbiguousUserConversions(S, OpLoc, Cand);
9135        ReportedAmbiguousConversions = true;
9136      }
9137
9138      // If this is a viable builtin, print it.
9139      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9140    }
9141  }
9142
9143  if (I != E)
9144    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9145}
9146
9147static SourceLocation
9148GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9149  return Cand->Specialization ? Cand->Specialization->getLocation()
9150                              : SourceLocation();
9151}
9152
9153struct CompareTemplateSpecCandidatesForDisplay {
9154  Sema &S;
9155  CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9156
9157  bool operator()(const TemplateSpecCandidate *L,
9158                  const TemplateSpecCandidate *R) {
9159    // Fast-path this check.
9160    if (L == R)
9161      return false;
9162
9163    // Assuming that both candidates are not matches...
9164
9165    // Sort by the ranking of deduction failures.
9166    if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9167      return RankDeductionFailure(L->DeductionFailure) <
9168             RankDeductionFailure(R->DeductionFailure);
9169
9170    // Sort everything else by location.
9171    SourceLocation LLoc = GetLocationForCandidate(L);
9172    SourceLocation RLoc = GetLocationForCandidate(R);
9173
9174    // Put candidates without locations (e.g. builtins) at the end.
9175    if (LLoc.isInvalid())
9176      return false;
9177    if (RLoc.isInvalid())
9178      return true;
9179
9180    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9181  }
9182};
9183
9184/// Diagnose a template argument deduction failure.
9185/// We are treating these failures as overload failures due to bad
9186/// deductions.
9187void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9188  DiagnoseBadDeduction(S, Specialization, // pattern
9189                       DeductionFailure, /*NumArgs=*/0);
9190}
9191
9192void TemplateSpecCandidateSet::destroyCandidates() {
9193  for (iterator i = begin(), e = end(); i != e; ++i) {
9194    i->DeductionFailure.Destroy();
9195  }
9196}
9197
9198void TemplateSpecCandidateSet::clear() {
9199  destroyCandidates();
9200  Candidates.clear();
9201}
9202
9203/// NoteCandidates - When no template specialization match is found, prints
9204/// diagnostic messages containing the non-matching specializations that form
9205/// the candidate set.
9206/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9207/// OCD == OCD_AllCandidates and Cand->Viable == false.
9208void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9209  // Sort the candidates by position (assuming no candidate is a match).
9210  // Sorting directly would be prohibitive, so we make a set of pointers
9211  // and sort those.
9212  SmallVector<TemplateSpecCandidate *, 32> Cands;
9213  Cands.reserve(size());
9214  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9215    if (Cand->Specialization)
9216      Cands.push_back(Cand);
9217    // Otherwise, this is a non matching builtin candidate.  We do not,
9218    // in general, want to list every possible builtin candidate.
9219  }
9220
9221  std::sort(Cands.begin(), Cands.end(),
9222            CompareTemplateSpecCandidatesForDisplay(S));
9223
9224  // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9225  // for generalization purposes (?).
9226  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9227
9228  SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9229  unsigned CandsShown = 0;
9230  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9231    TemplateSpecCandidate *Cand = *I;
9232
9233    // Set an arbitrary limit on the number of candidates we'll spam
9234    // the user with.  FIXME: This limit should depend on details of the
9235    // candidate list.
9236    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9237      break;
9238    ++CandsShown;
9239
9240    assert(Cand->Specialization &&
9241           "Non-matching built-in candidates are not added to Cands.");
9242    Cand->NoteDeductionFailure(S);
9243  }
9244
9245  if (I != E)
9246    S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9247}
9248
9249// [PossiblyAFunctionType]  -->   [Return]
9250// NonFunctionType --> NonFunctionType
9251// R (A) --> R(A)
9252// R (*)(A) --> R (A)
9253// R (&)(A) --> R (A)
9254// R (S::*)(A) --> R (A)
9255QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9256  QualType Ret = PossiblyAFunctionType;
9257  if (const PointerType *ToTypePtr =
9258    PossiblyAFunctionType->getAs<PointerType>())
9259    Ret = ToTypePtr->getPointeeType();
9260  else if (const ReferenceType *ToTypeRef =
9261    PossiblyAFunctionType->getAs<ReferenceType>())
9262    Ret = ToTypeRef->getPointeeType();
9263  else if (const MemberPointerType *MemTypePtr =
9264    PossiblyAFunctionType->getAs<MemberPointerType>())
9265    Ret = MemTypePtr->getPointeeType();
9266  Ret =
9267    Context.getCanonicalType(Ret).getUnqualifiedType();
9268  return Ret;
9269}
9270
9271// A helper class to help with address of function resolution
9272// - allows us to avoid passing around all those ugly parameters
9273class AddressOfFunctionResolver
9274{
9275  Sema& S;
9276  Expr* SourceExpr;
9277  const QualType& TargetType;
9278  QualType TargetFunctionType; // Extracted function type from target type
9279
9280  bool Complain;
9281  //DeclAccessPair& ResultFunctionAccessPair;
9282  ASTContext& Context;
9283
9284  bool TargetTypeIsNonStaticMemberFunction;
9285  bool FoundNonTemplateFunction;
9286  bool StaticMemberFunctionFromBoundPointer;
9287
9288  OverloadExpr::FindResult OvlExprInfo;
9289  OverloadExpr *OvlExpr;
9290  TemplateArgumentListInfo OvlExplicitTemplateArgs;
9291  SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9292  TemplateSpecCandidateSet FailedCandidates;
9293
9294public:
9295  AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9296                            const QualType &TargetType, bool Complain)
9297      : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9298        Complain(Complain), Context(S.getASTContext()),
9299        TargetTypeIsNonStaticMemberFunction(
9300            !!TargetType->getAs<MemberPointerType>()),
9301        FoundNonTemplateFunction(false),
9302        StaticMemberFunctionFromBoundPointer(false),
9303        OvlExprInfo(OverloadExpr::find(SourceExpr)),
9304        OvlExpr(OvlExprInfo.Expression),
9305        FailedCandidates(OvlExpr->getNameLoc()) {
9306    ExtractUnqualifiedFunctionTypeFromTargetType();
9307
9308    if (TargetFunctionType->isFunctionType()) {
9309      if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9310        if (!UME->isImplicitAccess() &&
9311            !S.ResolveSingleFunctionTemplateSpecialization(UME))
9312          StaticMemberFunctionFromBoundPointer = true;
9313    } else if (OvlExpr->hasExplicitTemplateArgs()) {
9314      DeclAccessPair dap;
9315      if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9316              OvlExpr, false, &dap)) {
9317        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9318          if (!Method->isStatic()) {
9319            // If the target type is a non-function type and the function found
9320            // is a non-static member function, pretend as if that was the
9321            // target, it's the only possible type to end up with.
9322            TargetTypeIsNonStaticMemberFunction = true;
9323
9324            // And skip adding the function if its not in the proper form.
9325            // We'll diagnose this due to an empty set of functions.
9326            if (!OvlExprInfo.HasFormOfMemberPointer)
9327              return;
9328          }
9329
9330        Matches.push_back(std::make_pair(dap, Fn));
9331      }
9332      return;
9333    }
9334
9335    if (OvlExpr->hasExplicitTemplateArgs())
9336      OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9337
9338    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9339      // C++ [over.over]p4:
9340      //   If more than one function is selected, [...]
9341      if (Matches.size() > 1) {
9342        if (FoundNonTemplateFunction)
9343          EliminateAllTemplateMatches();
9344        else
9345          EliminateAllExceptMostSpecializedTemplate();
9346      }
9347    }
9348  }
9349
9350private:
9351  bool isTargetTypeAFunction() const {
9352    return TargetFunctionType->isFunctionType();
9353  }
9354
9355  // [ToType]     [Return]
9356
9357  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9358  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9359  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9360  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9361    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9362  }
9363
9364  // return true if any matching specializations were found
9365  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9366                                   const DeclAccessPair& CurAccessFunPair) {
9367    if (CXXMethodDecl *Method
9368              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9369      // Skip non-static function templates when converting to pointer, and
9370      // static when converting to member pointer.
9371      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9372        return false;
9373    }
9374    else if (TargetTypeIsNonStaticMemberFunction)
9375      return false;
9376
9377    // C++ [over.over]p2:
9378    //   If the name is a function template, template argument deduction is
9379    //   done (14.8.2.2), and if the argument deduction succeeds, the
9380    //   resulting template argument list is used to generate a single
9381    //   function template specialization, which is added to the set of
9382    //   overloaded functions considered.
9383    FunctionDecl *Specialization = 0;
9384    TemplateDeductionInfo Info(FailedCandidates.getLocation());
9385    if (Sema::TemplateDeductionResult Result
9386          = S.DeduceTemplateArguments(FunctionTemplate,
9387                                      &OvlExplicitTemplateArgs,
9388                                      TargetFunctionType, Specialization,
9389                                      Info, /*InOverloadResolution=*/true)) {
9390      // Make a note of the failed deduction for diagnostics.
9391      FailedCandidates.addCandidate()
9392          .set(FunctionTemplate->getTemplatedDecl(),
9393               MakeDeductionFailureInfo(Context, Result, Info));
9394      return false;
9395    }
9396
9397    // Template argument deduction ensures that we have an exact match or
9398    // compatible pointer-to-function arguments that would be adjusted by ICS.
9399    // This function template specicalization works.
9400    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9401    assert(S.isSameOrCompatibleFunctionType(
9402              Context.getCanonicalType(Specialization->getType()),
9403              Context.getCanonicalType(TargetFunctionType)));
9404    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9405    return true;
9406  }
9407
9408  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9409                                      const DeclAccessPair& CurAccessFunPair) {
9410    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9411      // Skip non-static functions when converting to pointer, and static
9412      // when converting to member pointer.
9413      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9414        return false;
9415    }
9416    else if (TargetTypeIsNonStaticMemberFunction)
9417      return false;
9418
9419    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9420      if (S.getLangOpts().CUDA)
9421        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9422          if (S.CheckCUDATarget(Caller, FunDecl))
9423            return false;
9424
9425      // If any candidate has a placeholder return type, trigger its deduction
9426      // now.
9427      if (S.getLangOpts().CPlusPlus1y &&
9428          FunDecl->getResultType()->isUndeducedType() &&
9429          S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9430        return false;
9431
9432      QualType ResultTy;
9433      if (Context.hasSameUnqualifiedType(TargetFunctionType,
9434                                         FunDecl->getType()) ||
9435          S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9436                                 ResultTy)) {
9437        Matches.push_back(std::make_pair(CurAccessFunPair,
9438          cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9439        FoundNonTemplateFunction = true;
9440        return true;
9441      }
9442    }
9443
9444    return false;
9445  }
9446
9447  bool FindAllFunctionsThatMatchTargetTypeExactly() {
9448    bool Ret = false;
9449
9450    // If the overload expression doesn't have the form of a pointer to
9451    // member, don't try to convert it to a pointer-to-member type.
9452    if (IsInvalidFormOfPointerToMemberFunction())
9453      return false;
9454
9455    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9456                               E = OvlExpr->decls_end();
9457         I != E; ++I) {
9458      // Look through any using declarations to find the underlying function.
9459      NamedDecl *Fn = (*I)->getUnderlyingDecl();
9460
9461      // C++ [over.over]p3:
9462      //   Non-member functions and static member functions match
9463      //   targets of type "pointer-to-function" or "reference-to-function."
9464      //   Nonstatic member functions match targets of
9465      //   type "pointer-to-member-function."
9466      // Note that according to DR 247, the containing class does not matter.
9467      if (FunctionTemplateDecl *FunctionTemplate
9468                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
9469        if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9470          Ret = true;
9471      }
9472      // If we have explicit template arguments supplied, skip non-templates.
9473      else if (!OvlExpr->hasExplicitTemplateArgs() &&
9474               AddMatchingNonTemplateFunction(Fn, I.getPair()))
9475        Ret = true;
9476    }
9477    assert(Ret || Matches.empty());
9478    return Ret;
9479  }
9480
9481  void EliminateAllExceptMostSpecializedTemplate() {
9482    //   [...] and any given function template specialization F1 is
9483    //   eliminated if the set contains a second function template
9484    //   specialization whose function template is more specialized
9485    //   than the function template of F1 according to the partial
9486    //   ordering rules of 14.5.5.2.
9487
9488    // The algorithm specified above is quadratic. We instead use a
9489    // two-pass algorithm (similar to the one used to identify the
9490    // best viable function in an overload set) that identifies the
9491    // best function template (if it exists).
9492
9493    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9494    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9495      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9496
9497    // TODO: It looks like FailedCandidates does not serve much purpose
9498    // here, since the no_viable diagnostic has index 0.
9499    UnresolvedSetIterator Result = S.getMostSpecialized(
9500        MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
9501        SourceExpr->getLocStart(), S.PDiag(),
9502        S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9503                                                     .second->getDeclName(),
9504        S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9505        Complain, TargetFunctionType);
9506
9507    if (Result != MatchesCopy.end()) {
9508      // Make it the first and only element
9509      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9510      Matches[0].second = cast<FunctionDecl>(*Result);
9511      Matches.resize(1);
9512    }
9513  }
9514
9515  void EliminateAllTemplateMatches() {
9516    //   [...] any function template specializations in the set are
9517    //   eliminated if the set also contains a non-template function, [...]
9518    for (unsigned I = 0, N = Matches.size(); I != N; ) {
9519      if (Matches[I].second->getPrimaryTemplate() == 0)
9520        ++I;
9521      else {
9522        Matches[I] = Matches[--N];
9523        Matches.set_size(N);
9524      }
9525    }
9526  }
9527
9528public:
9529  void ComplainNoMatchesFound() const {
9530    assert(Matches.empty());
9531    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9532        << OvlExpr->getName() << TargetFunctionType
9533        << OvlExpr->getSourceRange();
9534    if (FailedCandidates.empty())
9535      S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9536    else {
9537      // We have some deduction failure messages. Use them to diagnose
9538      // the function templates, and diagnose the non-template candidates
9539      // normally.
9540      for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9541                                 IEnd = OvlExpr->decls_end();
9542           I != IEnd; ++I)
9543        if (FunctionDecl *Fun =
9544                dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9545          S.NoteOverloadCandidate(Fun, TargetFunctionType);
9546      FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9547    }
9548  }
9549
9550  bool IsInvalidFormOfPointerToMemberFunction() const {
9551    return TargetTypeIsNonStaticMemberFunction &&
9552      !OvlExprInfo.HasFormOfMemberPointer;
9553  }
9554
9555  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9556      // TODO: Should we condition this on whether any functions might
9557      // have matched, or is it more appropriate to do that in callers?
9558      // TODO: a fixit wouldn't hurt.
9559      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9560        << TargetType << OvlExpr->getSourceRange();
9561  }
9562
9563  bool IsStaticMemberFunctionFromBoundPointer() const {
9564    return StaticMemberFunctionFromBoundPointer;
9565  }
9566
9567  void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9568    S.Diag(OvlExpr->getLocStart(),
9569           diag::err_invalid_form_pointer_member_function)
9570      << OvlExpr->getSourceRange();
9571  }
9572
9573  void ComplainOfInvalidConversion() const {
9574    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9575      << OvlExpr->getName() << TargetType;
9576  }
9577
9578  void ComplainMultipleMatchesFound() const {
9579    assert(Matches.size() > 1);
9580    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9581      << OvlExpr->getName()
9582      << OvlExpr->getSourceRange();
9583    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9584  }
9585
9586  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9587
9588  int getNumMatches() const { return Matches.size(); }
9589
9590  FunctionDecl* getMatchingFunctionDecl() const {
9591    if (Matches.size() != 1) return 0;
9592    return Matches[0].second;
9593  }
9594
9595  const DeclAccessPair* getMatchingFunctionAccessPair() const {
9596    if (Matches.size() != 1) return 0;
9597    return &Matches[0].first;
9598  }
9599};
9600
9601/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9602/// an overloaded function (C++ [over.over]), where @p From is an
9603/// expression with overloaded function type and @p ToType is the type
9604/// we're trying to resolve to. For example:
9605///
9606/// @code
9607/// int f(double);
9608/// int f(int);
9609///
9610/// int (*pfd)(double) = f; // selects f(double)
9611/// @endcode
9612///
9613/// This routine returns the resulting FunctionDecl if it could be
9614/// resolved, and NULL otherwise. When @p Complain is true, this
9615/// routine will emit diagnostics if there is an error.
9616FunctionDecl *
9617Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9618                                         QualType TargetType,
9619                                         bool Complain,
9620                                         DeclAccessPair &FoundResult,
9621                                         bool *pHadMultipleCandidates) {
9622  assert(AddressOfExpr->getType() == Context.OverloadTy);
9623
9624  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9625                                     Complain);
9626  int NumMatches = Resolver.getNumMatches();
9627  FunctionDecl* Fn = 0;
9628  if (NumMatches == 0 && Complain) {
9629    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9630      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9631    else
9632      Resolver.ComplainNoMatchesFound();
9633  }
9634  else if (NumMatches > 1 && Complain)
9635    Resolver.ComplainMultipleMatchesFound();
9636  else if (NumMatches == 1) {
9637    Fn = Resolver.getMatchingFunctionDecl();
9638    assert(Fn);
9639    FoundResult = *Resolver.getMatchingFunctionAccessPair();
9640    if (Complain) {
9641      if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9642        Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9643      else
9644        CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9645    }
9646  }
9647
9648  if (pHadMultipleCandidates)
9649    *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9650  return Fn;
9651}
9652
9653/// \brief Given an expression that refers to an overloaded function, try to
9654/// resolve that overloaded function expression down to a single function.
9655///
9656/// This routine can only resolve template-ids that refer to a single function
9657/// template, where that template-id refers to a single template whose template
9658/// arguments are either provided by the template-id or have defaults,
9659/// as described in C++0x [temp.arg.explicit]p3.
9660FunctionDecl *
9661Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9662                                                  bool Complain,
9663                                                  DeclAccessPair *FoundResult) {
9664  // C++ [over.over]p1:
9665  //   [...] [Note: any redundant set of parentheses surrounding the
9666  //   overloaded function name is ignored (5.1). ]
9667  // C++ [over.over]p1:
9668  //   [...] The overloaded function name can be preceded by the &
9669  //   operator.
9670
9671  // If we didn't actually find any template-ids, we're done.
9672  if (!ovl->hasExplicitTemplateArgs())
9673    return 0;
9674
9675  TemplateArgumentListInfo ExplicitTemplateArgs;
9676  ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9677  TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
9678
9679  // Look through all of the overloaded functions, searching for one
9680  // whose type matches exactly.
9681  FunctionDecl *Matched = 0;
9682  for (UnresolvedSetIterator I = ovl->decls_begin(),
9683         E = ovl->decls_end(); I != E; ++I) {
9684    // C++0x [temp.arg.explicit]p3:
9685    //   [...] In contexts where deduction is done and fails, or in contexts
9686    //   where deduction is not done, if a template argument list is
9687    //   specified and it, along with any default template arguments,
9688    //   identifies a single function template specialization, then the
9689    //   template-id is an lvalue for the function template specialization.
9690    FunctionTemplateDecl *FunctionTemplate
9691      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9692
9693    // C++ [over.over]p2:
9694    //   If the name is a function template, template argument deduction is
9695    //   done (14.8.2.2), and if the argument deduction succeeds, the
9696    //   resulting template argument list is used to generate a single
9697    //   function template specialization, which is added to the set of
9698    //   overloaded functions considered.
9699    FunctionDecl *Specialization = 0;
9700    TemplateDeductionInfo Info(FailedCandidates.getLocation());
9701    if (TemplateDeductionResult Result
9702          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9703                                    Specialization, Info,
9704                                    /*InOverloadResolution=*/true)) {
9705      // Make a note of the failed deduction for diagnostics.
9706      // TODO: Actually use the failed-deduction info?
9707      FailedCandidates.addCandidate()
9708          .set(FunctionTemplate->getTemplatedDecl(),
9709               MakeDeductionFailureInfo(Context, Result, Info));
9710      continue;
9711    }
9712
9713    assert(Specialization && "no specialization and no error?");
9714
9715    // Multiple matches; we can't resolve to a single declaration.
9716    if (Matched) {
9717      if (Complain) {
9718        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9719          << ovl->getName();
9720        NoteAllOverloadCandidates(ovl);
9721      }
9722      return 0;
9723    }
9724
9725    Matched = Specialization;
9726    if (FoundResult) *FoundResult = I.getPair();
9727  }
9728
9729  if (Matched && getLangOpts().CPlusPlus1y &&
9730      Matched->getResultType()->isUndeducedType() &&
9731      DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9732    return 0;
9733
9734  return Matched;
9735}
9736
9737
9738
9739
9740// Resolve and fix an overloaded expression that can be resolved
9741// because it identifies a single function template specialization.
9742//
9743// Last three arguments should only be supplied if Complain = true
9744//
9745// Return true if it was logically possible to so resolve the
9746// expression, regardless of whether or not it succeeded.  Always
9747// returns true if 'complain' is set.
9748bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9749                      ExprResult &SrcExpr, bool doFunctionPointerConverion,
9750                   bool complain, const SourceRange& OpRangeForComplaining,
9751                                           QualType DestTypeForComplaining,
9752                                            unsigned DiagIDForComplaining) {
9753  assert(SrcExpr.get()->getType() == Context.OverloadTy);
9754
9755  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9756
9757  DeclAccessPair found;
9758  ExprResult SingleFunctionExpression;
9759  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9760                           ovl.Expression, /*complain*/ false, &found)) {
9761    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9762      SrcExpr = ExprError();
9763      return true;
9764    }
9765
9766    // It is only correct to resolve to an instance method if we're
9767    // resolving a form that's permitted to be a pointer to member.
9768    // Otherwise we'll end up making a bound member expression, which
9769    // is illegal in all the contexts we resolve like this.
9770    if (!ovl.HasFormOfMemberPointer &&
9771        isa<CXXMethodDecl>(fn) &&
9772        cast<CXXMethodDecl>(fn)->isInstance()) {
9773      if (!complain) return false;
9774
9775      Diag(ovl.Expression->getExprLoc(),
9776           diag::err_bound_member_function)
9777        << 0 << ovl.Expression->getSourceRange();
9778
9779      // TODO: I believe we only end up here if there's a mix of
9780      // static and non-static candidates (otherwise the expression
9781      // would have 'bound member' type, not 'overload' type).
9782      // Ideally we would note which candidate was chosen and why
9783      // the static candidates were rejected.
9784      SrcExpr = ExprError();
9785      return true;
9786    }
9787
9788    // Fix the expression to refer to 'fn'.
9789    SingleFunctionExpression =
9790      Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9791
9792    // If desired, do function-to-pointer decay.
9793    if (doFunctionPointerConverion) {
9794      SingleFunctionExpression =
9795        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9796      if (SingleFunctionExpression.isInvalid()) {
9797        SrcExpr = ExprError();
9798        return true;
9799      }
9800    }
9801  }
9802
9803  if (!SingleFunctionExpression.isUsable()) {
9804    if (complain) {
9805      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9806        << ovl.Expression->getName()
9807        << DestTypeForComplaining
9808        << OpRangeForComplaining
9809        << ovl.Expression->getQualifierLoc().getSourceRange();
9810      NoteAllOverloadCandidates(SrcExpr.get());
9811
9812      SrcExpr = ExprError();
9813      return true;
9814    }
9815
9816    return false;
9817  }
9818
9819  SrcExpr = SingleFunctionExpression;
9820  return true;
9821}
9822
9823/// \brief Add a single candidate to the overload set.
9824static void AddOverloadedCallCandidate(Sema &S,
9825                                       DeclAccessPair FoundDecl,
9826                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
9827                                       ArrayRef<Expr *> Args,
9828                                       OverloadCandidateSet &CandidateSet,
9829                                       bool PartialOverloading,
9830                                       bool KnownValid) {
9831  NamedDecl *Callee = FoundDecl.getDecl();
9832  if (isa<UsingShadowDecl>(Callee))
9833    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9834
9835  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9836    if (ExplicitTemplateArgs) {
9837      assert(!KnownValid && "Explicit template arguments?");
9838      return;
9839    }
9840    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9841                           PartialOverloading);
9842    return;
9843  }
9844
9845  if (FunctionTemplateDecl *FuncTemplate
9846      = dyn_cast<FunctionTemplateDecl>(Callee)) {
9847    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9848                                   ExplicitTemplateArgs, Args, CandidateSet);
9849    return;
9850  }
9851
9852  assert(!KnownValid && "unhandled case in overloaded call candidate");
9853}
9854
9855/// \brief Add the overload candidates named by callee and/or found by argument
9856/// dependent lookup to the given overload set.
9857void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9858                                       ArrayRef<Expr *> Args,
9859                                       OverloadCandidateSet &CandidateSet,
9860                                       bool PartialOverloading) {
9861
9862#ifndef NDEBUG
9863  // Verify that ArgumentDependentLookup is consistent with the rules
9864  // in C++0x [basic.lookup.argdep]p3:
9865  //
9866  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9867  //   and let Y be the lookup set produced by argument dependent
9868  //   lookup (defined as follows). If X contains
9869  //
9870  //     -- a declaration of a class member, or
9871  //
9872  //     -- a block-scope function declaration that is not a
9873  //        using-declaration, or
9874  //
9875  //     -- a declaration that is neither a function or a function
9876  //        template
9877  //
9878  //   then Y is empty.
9879
9880  if (ULE->requiresADL()) {
9881    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9882           E = ULE->decls_end(); I != E; ++I) {
9883      assert(!(*I)->getDeclContext()->isRecord());
9884      assert(isa<UsingShadowDecl>(*I) ||
9885             !(*I)->getDeclContext()->isFunctionOrMethod());
9886      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9887    }
9888  }
9889#endif
9890
9891  // It would be nice to avoid this copy.
9892  TemplateArgumentListInfo TABuffer;
9893  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9894  if (ULE->hasExplicitTemplateArgs()) {
9895    ULE->copyTemplateArgumentsInto(TABuffer);
9896    ExplicitTemplateArgs = &TABuffer;
9897  }
9898
9899  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9900         E = ULE->decls_end(); I != E; ++I)
9901    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9902                               CandidateSet, PartialOverloading,
9903                               /*KnownValid*/ true);
9904
9905  if (ULE->requiresADL())
9906    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9907                                         ULE->getExprLoc(),
9908                                         Args, ExplicitTemplateArgs,
9909                                         CandidateSet, PartialOverloading);
9910}
9911
9912/// Determine whether a declaration with the specified name could be moved into
9913/// a different namespace.
9914static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
9915  switch (Name.getCXXOverloadedOperator()) {
9916  case OO_New: case OO_Array_New:
9917  case OO_Delete: case OO_Array_Delete:
9918    return false;
9919
9920  default:
9921    return true;
9922  }
9923}
9924
9925/// Attempt to recover from an ill-formed use of a non-dependent name in a
9926/// template, where the non-dependent name was declared after the template
9927/// was defined. This is common in code written for a compilers which do not
9928/// correctly implement two-stage name lookup.
9929///
9930/// Returns true if a viable candidate was found and a diagnostic was issued.
9931static bool
9932DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9933                       const CXXScopeSpec &SS, LookupResult &R,
9934                       TemplateArgumentListInfo *ExplicitTemplateArgs,
9935                       ArrayRef<Expr *> Args) {
9936  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9937    return false;
9938
9939  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9940    if (DC->isTransparentContext())
9941      continue;
9942
9943    SemaRef.LookupQualifiedName(R, DC);
9944
9945    if (!R.empty()) {
9946      R.suppressDiagnostics();
9947
9948      if (isa<CXXRecordDecl>(DC)) {
9949        // Don't diagnose names we find in classes; we get much better
9950        // diagnostics for these from DiagnoseEmptyLookup.
9951        R.clear();
9952        return false;
9953      }
9954
9955      OverloadCandidateSet Candidates(FnLoc);
9956      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9957        AddOverloadedCallCandidate(SemaRef, I.getPair(),
9958                                   ExplicitTemplateArgs, Args,
9959                                   Candidates, false, /*KnownValid*/ false);
9960
9961      OverloadCandidateSet::iterator Best;
9962      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9963        // No viable functions. Don't bother the user with notes for functions
9964        // which don't work and shouldn't be found anyway.
9965        R.clear();
9966        return false;
9967      }
9968
9969      // Find the namespaces where ADL would have looked, and suggest
9970      // declaring the function there instead.
9971      Sema::AssociatedNamespaceSet AssociatedNamespaces;
9972      Sema::AssociatedClassSet AssociatedClasses;
9973      SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
9974                                                 AssociatedNamespaces,
9975                                                 AssociatedClasses);
9976      Sema::AssociatedNamespaceSet SuggestedNamespaces;
9977      if (canBeDeclaredInNamespace(R.getLookupName())) {
9978        DeclContext *Std = SemaRef.getStdNamespace();
9979        for (Sema::AssociatedNamespaceSet::iterator
9980               it = AssociatedNamespaces.begin(),
9981               end = AssociatedNamespaces.end(); it != end; ++it) {
9982          // Never suggest declaring a function within namespace 'std'.
9983          if (Std && Std->Encloses(*it))
9984            continue;
9985
9986          // Never suggest declaring a function within a namespace with a
9987          // reserved name, like __gnu_cxx.
9988          NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9989          if (NS &&
9990              NS->getQualifiedNameAsString().find("__") != std::string::npos)
9991            continue;
9992
9993          SuggestedNamespaces.insert(*it);
9994        }
9995      }
9996
9997      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9998        << R.getLookupName();
9999      if (SuggestedNamespaces.empty()) {
10000        SemaRef.Diag(Best->Function->getLocation(),
10001                     diag::note_not_found_by_two_phase_lookup)
10002          << R.getLookupName() << 0;
10003      } else if (SuggestedNamespaces.size() == 1) {
10004        SemaRef.Diag(Best->Function->getLocation(),
10005                     diag::note_not_found_by_two_phase_lookup)
10006          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10007      } else {
10008        // FIXME: It would be useful to list the associated namespaces here,
10009        // but the diagnostics infrastructure doesn't provide a way to produce
10010        // a localized representation of a list of items.
10011        SemaRef.Diag(Best->Function->getLocation(),
10012                     diag::note_not_found_by_two_phase_lookup)
10013          << R.getLookupName() << 2;
10014      }
10015
10016      // Try to recover by calling this function.
10017      return true;
10018    }
10019
10020    R.clear();
10021  }
10022
10023  return false;
10024}
10025
10026/// Attempt to recover from ill-formed use of a non-dependent operator in a
10027/// template, where the non-dependent operator was declared after the template
10028/// was defined.
10029///
10030/// Returns true if a viable candidate was found and a diagnostic was issued.
10031static bool
10032DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10033                               SourceLocation OpLoc,
10034                               ArrayRef<Expr *> Args) {
10035  DeclarationName OpName =
10036    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10037  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10038  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10039                                /*ExplicitTemplateArgs=*/0, Args);
10040}
10041
10042namespace {
10043class BuildRecoveryCallExprRAII {
10044  Sema &SemaRef;
10045public:
10046  BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10047    assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10048    SemaRef.IsBuildingRecoveryCallExpr = true;
10049  }
10050
10051  ~BuildRecoveryCallExprRAII() {
10052    SemaRef.IsBuildingRecoveryCallExpr = false;
10053  }
10054};
10055
10056}
10057
10058/// Attempts to recover from a call where no functions were found.
10059///
10060/// Returns true if new candidates were found.
10061static ExprResult
10062BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10063                      UnresolvedLookupExpr *ULE,
10064                      SourceLocation LParenLoc,
10065                      llvm::MutableArrayRef<Expr *> Args,
10066                      SourceLocation RParenLoc,
10067                      bool EmptyLookup, bool AllowTypoCorrection) {
10068  // Do not try to recover if it is already building a recovery call.
10069  // This stops infinite loops for template instantiations like
10070  //
10071  // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10072  // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10073  //
10074  if (SemaRef.IsBuildingRecoveryCallExpr)
10075    return ExprError();
10076  BuildRecoveryCallExprRAII RCE(SemaRef);
10077
10078  CXXScopeSpec SS;
10079  SS.Adopt(ULE->getQualifierLoc());
10080  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10081
10082  TemplateArgumentListInfo TABuffer;
10083  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
10084  if (ULE->hasExplicitTemplateArgs()) {
10085    ULE->copyTemplateArgumentsInto(TABuffer);
10086    ExplicitTemplateArgs = &TABuffer;
10087  }
10088
10089  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10090                 Sema::LookupOrdinaryName);
10091  FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10092                                  ExplicitTemplateArgs != 0);
10093  NoTypoCorrectionCCC RejectAll;
10094  CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10095      (CorrectionCandidateCallback*)&Validator :
10096      (CorrectionCandidateCallback*)&RejectAll;
10097  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10098                              ExplicitTemplateArgs, Args) &&
10099      (!EmptyLookup ||
10100       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
10101                                   ExplicitTemplateArgs, Args)))
10102    return ExprError();
10103
10104  assert(!R.empty() && "lookup results empty despite recovery");
10105
10106  // Build an implicit member call if appropriate.  Just drop the
10107  // casts and such from the call, we don't really care.
10108  ExprResult NewFn = ExprError();
10109  if ((*R.begin())->isCXXClassMember())
10110    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10111                                                    R, ExplicitTemplateArgs);
10112  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10113    NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10114                                        ExplicitTemplateArgs);
10115  else
10116    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10117
10118  if (NewFn.isInvalid())
10119    return ExprError();
10120
10121  // This shouldn't cause an infinite loop because we're giving it
10122  // an expression with viable lookup results, which should never
10123  // end up here.
10124  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
10125                               MultiExprArg(Args.data(), Args.size()),
10126                               RParenLoc);
10127}
10128
10129/// \brief Constructs and populates an OverloadedCandidateSet from
10130/// the given function.
10131/// \returns true when an the ExprResult output parameter has been set.
10132bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10133                                  UnresolvedLookupExpr *ULE,
10134                                  MultiExprArg Args,
10135                                  SourceLocation RParenLoc,
10136                                  OverloadCandidateSet *CandidateSet,
10137                                  ExprResult *Result) {
10138#ifndef NDEBUG
10139  if (ULE->requiresADL()) {
10140    // To do ADL, we must have found an unqualified name.
10141    assert(!ULE->getQualifier() && "qualified name with ADL");
10142
10143    // We don't perform ADL for implicit declarations of builtins.
10144    // Verify that this was correctly set up.
10145    FunctionDecl *F;
10146    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10147        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10148        F->getBuiltinID() && F->isImplicit())
10149      llvm_unreachable("performing ADL for builtin");
10150
10151    // We don't perform ADL in C.
10152    assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10153  }
10154#endif
10155
10156  UnbridgedCastsSet UnbridgedCasts;
10157  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10158    *Result = ExprError();
10159    return true;
10160  }
10161
10162  // Add the functions denoted by the callee to the set of candidate
10163  // functions, including those from argument-dependent lookup.
10164  AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10165
10166  // If we found nothing, try to recover.
10167  // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10168  // out if it fails.
10169  if (CandidateSet->empty()) {
10170    // In Microsoft mode, if we are inside a template class member function then
10171    // create a type dependent CallExpr. The goal is to postpone name lookup
10172    // to instantiation time to be able to search into type dependent base
10173    // classes.
10174    if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
10175        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10176      CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10177                                            Context.DependentTy, VK_RValue,
10178                                            RParenLoc);
10179      CE->setTypeDependent(true);
10180      *Result = Owned(CE);
10181      return true;
10182    }
10183    return false;
10184  }
10185
10186  UnbridgedCasts.restore();
10187  return false;
10188}
10189
10190/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10191/// the completed call expression. If overload resolution fails, emits
10192/// diagnostics and returns ExprError()
10193static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10194                                           UnresolvedLookupExpr *ULE,
10195                                           SourceLocation LParenLoc,
10196                                           MultiExprArg Args,
10197                                           SourceLocation RParenLoc,
10198                                           Expr *ExecConfig,
10199                                           OverloadCandidateSet *CandidateSet,
10200                                           OverloadCandidateSet::iterator *Best,
10201                                           OverloadingResult OverloadResult,
10202                                           bool AllowTypoCorrection) {
10203  if (CandidateSet->empty())
10204    return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10205                                 RParenLoc, /*EmptyLookup=*/true,
10206                                 AllowTypoCorrection);
10207
10208  switch (OverloadResult) {
10209  case OR_Success: {
10210    FunctionDecl *FDecl = (*Best)->Function;
10211    SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10212    if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10213      return ExprError();
10214    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10215    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10216                                         ExecConfig);
10217  }
10218
10219  case OR_No_Viable_Function: {
10220    // Try to recover by looking for viable functions which the user might
10221    // have meant to call.
10222    ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10223                                                Args, RParenLoc,
10224                                                /*EmptyLookup=*/false,
10225                                                AllowTypoCorrection);
10226    if (!Recovery.isInvalid())
10227      return Recovery;
10228
10229    SemaRef.Diag(Fn->getLocStart(),
10230         diag::err_ovl_no_viable_function_in_call)
10231      << ULE->getName() << Fn->getSourceRange();
10232    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10233    break;
10234  }
10235
10236  case OR_Ambiguous:
10237    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10238      << ULE->getName() << Fn->getSourceRange();
10239    CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10240    break;
10241
10242  case OR_Deleted: {
10243    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10244      << (*Best)->Function->isDeleted()
10245      << ULE->getName()
10246      << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10247      << Fn->getSourceRange();
10248    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10249
10250    // We emitted an error for the unvailable/deleted function call but keep
10251    // the call in the AST.
10252    FunctionDecl *FDecl = (*Best)->Function;
10253    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10254    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10255                                         ExecConfig);
10256  }
10257  }
10258
10259  // Overload resolution failed.
10260  return ExprError();
10261}
10262
10263/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10264/// (which eventually refers to the declaration Func) and the call
10265/// arguments Args/NumArgs, attempt to resolve the function call down
10266/// to a specific function. If overload resolution succeeds, returns
10267/// the call expression produced by overload resolution.
10268/// Otherwise, emits diagnostics and returns ExprError.
10269ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10270                                         UnresolvedLookupExpr *ULE,
10271                                         SourceLocation LParenLoc,
10272                                         MultiExprArg Args,
10273                                         SourceLocation RParenLoc,
10274                                         Expr *ExecConfig,
10275                                         bool AllowTypoCorrection) {
10276  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10277  ExprResult result;
10278
10279  if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10280                             &result))
10281    return result;
10282
10283  OverloadCandidateSet::iterator Best;
10284  OverloadingResult OverloadResult =
10285      CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10286
10287  return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10288                                  RParenLoc, ExecConfig, &CandidateSet,
10289                                  &Best, OverloadResult,
10290                                  AllowTypoCorrection);
10291}
10292
10293static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10294  return Functions.size() > 1 ||
10295    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10296}
10297
10298/// \brief Create a unary operation that may resolve to an overloaded
10299/// operator.
10300///
10301/// \param OpLoc The location of the operator itself (e.g., '*').
10302///
10303/// \param OpcIn The UnaryOperator::Opcode that describes this
10304/// operator.
10305///
10306/// \param Fns The set of non-member functions that will be
10307/// considered by overload resolution. The caller needs to build this
10308/// set based on the context using, e.g.,
10309/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10310/// set should not contain any member functions; those will be added
10311/// by CreateOverloadedUnaryOp().
10312///
10313/// \param Input The input argument.
10314ExprResult
10315Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10316                              const UnresolvedSetImpl &Fns,
10317                              Expr *Input) {
10318  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10319
10320  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10321  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10322  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10323  // TODO: provide better source location info.
10324  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10325
10326  if (checkPlaceholderForOverload(*this, Input))
10327    return ExprError();
10328
10329  Expr *Args[2] = { Input, 0 };
10330  unsigned NumArgs = 1;
10331
10332  // For post-increment and post-decrement, add the implicit '0' as
10333  // the second argument, so that we know this is a post-increment or
10334  // post-decrement.
10335  if (Opc == UO_PostInc || Opc == UO_PostDec) {
10336    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10337    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10338                                     SourceLocation());
10339    NumArgs = 2;
10340  }
10341
10342  ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10343
10344  if (Input->isTypeDependent()) {
10345    if (Fns.empty())
10346      return Owned(new (Context) UnaryOperator(Input,
10347                                               Opc,
10348                                               Context.DependentTy,
10349                                               VK_RValue, OK_Ordinary,
10350                                               OpLoc));
10351
10352    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10353    UnresolvedLookupExpr *Fn
10354      = UnresolvedLookupExpr::Create(Context, NamingClass,
10355                                     NestedNameSpecifierLoc(), OpNameInfo,
10356                                     /*ADL*/ true, IsOverloaded(Fns),
10357                                     Fns.begin(), Fns.end());
10358    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
10359                                                   Context.DependentTy,
10360                                                   VK_RValue,
10361                                                   OpLoc, false));
10362  }
10363
10364  // Build an empty overload set.
10365  OverloadCandidateSet CandidateSet(OpLoc);
10366
10367  // Add the candidates from the given function set.
10368  AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10369
10370  // Add operator candidates that are member functions.
10371  AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10372
10373  // Add candidates from ADL.
10374  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10375                                       ArgsArray, /*ExplicitTemplateArgs*/ 0,
10376                                       CandidateSet);
10377
10378  // Add builtin operator candidates.
10379  AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10380
10381  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10382
10383  // Perform overload resolution.
10384  OverloadCandidateSet::iterator Best;
10385  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10386  case OR_Success: {
10387    // We found a built-in operator or an overloaded operator.
10388    FunctionDecl *FnDecl = Best->Function;
10389
10390    if (FnDecl) {
10391      // We matched an overloaded operator. Build a call to that
10392      // operator.
10393
10394      // Convert the arguments.
10395      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10396        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
10397
10398        ExprResult InputRes =
10399          PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10400                                              Best->FoundDecl, Method);
10401        if (InputRes.isInvalid())
10402          return ExprError();
10403        Input = InputRes.take();
10404      } else {
10405        // Convert the arguments.
10406        ExprResult InputInit
10407          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10408                                                      Context,
10409                                                      FnDecl->getParamDecl(0)),
10410                                      SourceLocation(),
10411                                      Input);
10412        if (InputInit.isInvalid())
10413          return ExprError();
10414        Input = InputInit.take();
10415      }
10416
10417      // Determine the result type.
10418      QualType ResultTy = FnDecl->getResultType();
10419      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10420      ResultTy = ResultTy.getNonLValueExprType(Context);
10421
10422      // Build the actual expression node.
10423      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10424                                                HadMultipleCandidates, OpLoc);
10425      if (FnExpr.isInvalid())
10426        return ExprError();
10427
10428      Args[0] = Input;
10429      CallExpr *TheCall =
10430        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
10431                                          ResultTy, VK, OpLoc, false);
10432
10433      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10434                              FnDecl))
10435        return ExprError();
10436
10437      return MaybeBindToTemporary(TheCall);
10438    } else {
10439      // We matched a built-in operator. Convert the arguments, then
10440      // break out so that we will build the appropriate built-in
10441      // operator node.
10442      ExprResult InputRes =
10443        PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10444                                  Best->Conversions[0], AA_Passing);
10445      if (InputRes.isInvalid())
10446        return ExprError();
10447      Input = InputRes.take();
10448      break;
10449    }
10450  }
10451
10452  case OR_No_Viable_Function:
10453    // This is an erroneous use of an operator which can be overloaded by
10454    // a non-member function. Check for non-member operators which were
10455    // defined too late to be candidates.
10456    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10457      // FIXME: Recover by calling the found function.
10458      return ExprError();
10459
10460    // No viable function; fall through to handling this as a
10461    // built-in operator, which will produce an error message for us.
10462    break;
10463
10464  case OR_Ambiguous:
10465    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10466        << UnaryOperator::getOpcodeStr(Opc)
10467        << Input->getType()
10468        << Input->getSourceRange();
10469    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
10470                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10471    return ExprError();
10472
10473  case OR_Deleted:
10474    Diag(OpLoc, diag::err_ovl_deleted_oper)
10475      << Best->Function->isDeleted()
10476      << UnaryOperator::getOpcodeStr(Opc)
10477      << getDeletedOrUnavailableSuffix(Best->Function)
10478      << Input->getSourceRange();
10479    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10480                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10481    return ExprError();
10482  }
10483
10484  // Either we found no viable overloaded operator or we matched a
10485  // built-in operator. In either case, fall through to trying to
10486  // build a built-in operation.
10487  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10488}
10489
10490/// \brief Create a binary operation that may resolve to an overloaded
10491/// operator.
10492///
10493/// \param OpLoc The location of the operator itself (e.g., '+').
10494///
10495/// \param OpcIn The BinaryOperator::Opcode that describes this
10496/// operator.
10497///
10498/// \param Fns The set of non-member functions that will be
10499/// considered by overload resolution. The caller needs to build this
10500/// set based on the context using, e.g.,
10501/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10502/// set should not contain any member functions; those will be added
10503/// by CreateOverloadedBinOp().
10504///
10505/// \param LHS Left-hand argument.
10506/// \param RHS Right-hand argument.
10507ExprResult
10508Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10509                            unsigned OpcIn,
10510                            const UnresolvedSetImpl &Fns,
10511                            Expr *LHS, Expr *RHS) {
10512  Expr *Args[2] = { LHS, RHS };
10513  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10514
10515  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10516  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10517  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10518
10519  // If either side is type-dependent, create an appropriate dependent
10520  // expression.
10521  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10522    if (Fns.empty()) {
10523      // If there are no functions to store, just build a dependent
10524      // BinaryOperator or CompoundAssignment.
10525      if (Opc <= BO_Assign || Opc > BO_OrAssign)
10526        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10527                                                  Context.DependentTy,
10528                                                  VK_RValue, OK_Ordinary,
10529                                                  OpLoc,
10530                                                  FPFeatures.fp_contract));
10531
10532      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10533                                                        Context.DependentTy,
10534                                                        VK_LValue,
10535                                                        OK_Ordinary,
10536                                                        Context.DependentTy,
10537                                                        Context.DependentTy,
10538                                                        OpLoc,
10539                                                        FPFeatures.fp_contract));
10540    }
10541
10542    // FIXME: save results of ADL from here?
10543    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10544    // TODO: provide better source location info in DNLoc component.
10545    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10546    UnresolvedLookupExpr *Fn
10547      = UnresolvedLookupExpr::Create(Context, NamingClass,
10548                                     NestedNameSpecifierLoc(), OpNameInfo,
10549                                     /*ADL*/ true, IsOverloaded(Fns),
10550                                     Fns.begin(), Fns.end());
10551    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10552                                                Context.DependentTy, VK_RValue,
10553                                                OpLoc, FPFeatures.fp_contract));
10554  }
10555
10556  // Always do placeholder-like conversions on the RHS.
10557  if (checkPlaceholderForOverload(*this, Args[1]))
10558    return ExprError();
10559
10560  // Do placeholder-like conversion on the LHS; note that we should
10561  // not get here with a PseudoObject LHS.
10562  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10563  if (checkPlaceholderForOverload(*this, Args[0]))
10564    return ExprError();
10565
10566  // If this is the assignment operator, we only perform overload resolution
10567  // if the left-hand side is a class or enumeration type. This is actually
10568  // a hack. The standard requires that we do overload resolution between the
10569  // various built-in candidates, but as DR507 points out, this can lead to
10570  // problems. So we do it this way, which pretty much follows what GCC does.
10571  // Note that we go the traditional code path for compound assignment forms.
10572  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10573    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10574
10575  // If this is the .* operator, which is not overloadable, just
10576  // create a built-in binary operator.
10577  if (Opc == BO_PtrMemD)
10578    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10579
10580  // Build an empty overload set.
10581  OverloadCandidateSet CandidateSet(OpLoc);
10582
10583  // Add the candidates from the given function set.
10584  AddFunctionCandidates(Fns, Args, CandidateSet, false);
10585
10586  // Add operator candidates that are member functions.
10587  AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10588
10589  // Add candidates from ADL.
10590  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10591                                       OpLoc, Args,
10592                                       /*ExplicitTemplateArgs*/ 0,
10593                                       CandidateSet);
10594
10595  // Add builtin operator candidates.
10596  AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10597
10598  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10599
10600  // Perform overload resolution.
10601  OverloadCandidateSet::iterator Best;
10602  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10603    case OR_Success: {
10604      // We found a built-in operator or an overloaded operator.
10605      FunctionDecl *FnDecl = Best->Function;
10606
10607      if (FnDecl) {
10608        // We matched an overloaded operator. Build a call to that
10609        // operator.
10610
10611        // Convert the arguments.
10612        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10613          // Best->Access is only meaningful for class members.
10614          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10615
10616          ExprResult Arg1 =
10617            PerformCopyInitialization(
10618              InitializedEntity::InitializeParameter(Context,
10619                                                     FnDecl->getParamDecl(0)),
10620              SourceLocation(), Owned(Args[1]));
10621          if (Arg1.isInvalid())
10622            return ExprError();
10623
10624          ExprResult Arg0 =
10625            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10626                                                Best->FoundDecl, Method);
10627          if (Arg0.isInvalid())
10628            return ExprError();
10629          Args[0] = Arg0.takeAs<Expr>();
10630          Args[1] = RHS = Arg1.takeAs<Expr>();
10631        } else {
10632          // Convert the arguments.
10633          ExprResult Arg0 = PerformCopyInitialization(
10634            InitializedEntity::InitializeParameter(Context,
10635                                                   FnDecl->getParamDecl(0)),
10636            SourceLocation(), Owned(Args[0]));
10637          if (Arg0.isInvalid())
10638            return ExprError();
10639
10640          ExprResult Arg1 =
10641            PerformCopyInitialization(
10642              InitializedEntity::InitializeParameter(Context,
10643                                                     FnDecl->getParamDecl(1)),
10644              SourceLocation(), Owned(Args[1]));
10645          if (Arg1.isInvalid())
10646            return ExprError();
10647          Args[0] = LHS = Arg0.takeAs<Expr>();
10648          Args[1] = RHS = Arg1.takeAs<Expr>();
10649        }
10650
10651        // Determine the result type.
10652        QualType ResultTy = FnDecl->getResultType();
10653        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10654        ResultTy = ResultTy.getNonLValueExprType(Context);
10655
10656        // Build the actual expression node.
10657        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10658                                                  Best->FoundDecl,
10659                                                  HadMultipleCandidates, OpLoc);
10660        if (FnExpr.isInvalid())
10661          return ExprError();
10662
10663        CXXOperatorCallExpr *TheCall =
10664          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10665                                            Args, ResultTy, VK, OpLoc,
10666                                            FPFeatures.fp_contract);
10667
10668        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10669                                FnDecl))
10670          return ExprError();
10671
10672        ArrayRef<const Expr *> ArgsArray(Args, 2);
10673        // Cut off the implicit 'this'.
10674        if (isa<CXXMethodDecl>(FnDecl))
10675          ArgsArray = ArgsArray.slice(1);
10676        checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10677                  TheCall->getSourceRange(), VariadicDoesNotApply);
10678
10679        return MaybeBindToTemporary(TheCall);
10680      } else {
10681        // We matched a built-in operator. Convert the arguments, then
10682        // break out so that we will build the appropriate built-in
10683        // operator node.
10684        ExprResult ArgsRes0 =
10685          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10686                                    Best->Conversions[0], AA_Passing);
10687        if (ArgsRes0.isInvalid())
10688          return ExprError();
10689        Args[0] = ArgsRes0.take();
10690
10691        ExprResult ArgsRes1 =
10692          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10693                                    Best->Conversions[1], AA_Passing);
10694        if (ArgsRes1.isInvalid())
10695          return ExprError();
10696        Args[1] = ArgsRes1.take();
10697        break;
10698      }
10699    }
10700
10701    case OR_No_Viable_Function: {
10702      // C++ [over.match.oper]p9:
10703      //   If the operator is the operator , [...] and there are no
10704      //   viable functions, then the operator is assumed to be the
10705      //   built-in operator and interpreted according to clause 5.
10706      if (Opc == BO_Comma)
10707        break;
10708
10709      // For class as left operand for assignment or compound assigment
10710      // operator do not fall through to handling in built-in, but report that
10711      // no overloaded assignment operator found
10712      ExprResult Result = ExprError();
10713      if (Args[0]->getType()->isRecordType() &&
10714          Opc >= BO_Assign && Opc <= BO_OrAssign) {
10715        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10716             << BinaryOperator::getOpcodeStr(Opc)
10717             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10718        if (Args[0]->getType()->isIncompleteType()) {
10719          Diag(OpLoc, diag::note_assign_lhs_incomplete)
10720            << Args[0]->getType()
10721            << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10722        }
10723      } else {
10724        // This is an erroneous use of an operator which can be overloaded by
10725        // a non-member function. Check for non-member operators which were
10726        // defined too late to be candidates.
10727        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10728          // FIXME: Recover by calling the found function.
10729          return ExprError();
10730
10731        // No viable function; try to create a built-in operation, which will
10732        // produce an error. Then, show the non-viable candidates.
10733        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10734      }
10735      assert(Result.isInvalid() &&
10736             "C++ binary operator overloading is missing candidates!");
10737      if (Result.isInvalid())
10738        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10739                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
10740      return Result;
10741    }
10742
10743    case OR_Ambiguous:
10744      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10745          << BinaryOperator::getOpcodeStr(Opc)
10746          << Args[0]->getType() << Args[1]->getType()
10747          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10748      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10749                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10750      return ExprError();
10751
10752    case OR_Deleted:
10753      if (isImplicitlyDeleted(Best->Function)) {
10754        CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10755        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10756          << Context.getRecordType(Method->getParent())
10757          << getSpecialMember(Method);
10758
10759        // The user probably meant to call this special member. Just
10760        // explain why it's deleted.
10761        NoteDeletedFunction(Method);
10762        return ExprError();
10763      } else {
10764        Diag(OpLoc, diag::err_ovl_deleted_oper)
10765          << Best->Function->isDeleted()
10766          << BinaryOperator::getOpcodeStr(Opc)
10767          << getDeletedOrUnavailableSuffix(Best->Function)
10768          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10769      }
10770      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10771                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10772      return ExprError();
10773  }
10774
10775  // We matched a built-in operator; build it.
10776  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10777}
10778
10779ExprResult
10780Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10781                                         SourceLocation RLoc,
10782                                         Expr *Base, Expr *Idx) {
10783  Expr *Args[2] = { Base, Idx };
10784  DeclarationName OpName =
10785      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10786
10787  // If either side is type-dependent, create an appropriate dependent
10788  // expression.
10789  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10790
10791    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10792    // CHECKME: no 'operator' keyword?
10793    DeclarationNameInfo OpNameInfo(OpName, LLoc);
10794    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10795    UnresolvedLookupExpr *Fn
10796      = UnresolvedLookupExpr::Create(Context, NamingClass,
10797                                     NestedNameSpecifierLoc(), OpNameInfo,
10798                                     /*ADL*/ true, /*Overloaded*/ false,
10799                                     UnresolvedSetIterator(),
10800                                     UnresolvedSetIterator());
10801    // Can't add any actual overloads yet
10802
10803    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10804                                                   Args,
10805                                                   Context.DependentTy,
10806                                                   VK_RValue,
10807                                                   RLoc, false));
10808  }
10809
10810  // Handle placeholders on both operands.
10811  if (checkPlaceholderForOverload(*this, Args[0]))
10812    return ExprError();
10813  if (checkPlaceholderForOverload(*this, Args[1]))
10814    return ExprError();
10815
10816  // Build an empty overload set.
10817  OverloadCandidateSet CandidateSet(LLoc);
10818
10819  // Subscript can only be overloaded as a member function.
10820
10821  // Add operator candidates that are member functions.
10822  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10823
10824  // Add builtin operator candidates.
10825  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10826
10827  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10828
10829  // Perform overload resolution.
10830  OverloadCandidateSet::iterator Best;
10831  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10832    case OR_Success: {
10833      // We found a built-in operator or an overloaded operator.
10834      FunctionDecl *FnDecl = Best->Function;
10835
10836      if (FnDecl) {
10837        // We matched an overloaded operator. Build a call to that
10838        // operator.
10839
10840        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10841
10842        // Convert the arguments.
10843        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10844        ExprResult Arg0 =
10845          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10846                                              Best->FoundDecl, Method);
10847        if (Arg0.isInvalid())
10848          return ExprError();
10849        Args[0] = Arg0.take();
10850
10851        // Convert the arguments.
10852        ExprResult InputInit
10853          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10854                                                      Context,
10855                                                      FnDecl->getParamDecl(0)),
10856                                      SourceLocation(),
10857                                      Owned(Args[1]));
10858        if (InputInit.isInvalid())
10859          return ExprError();
10860
10861        Args[1] = InputInit.takeAs<Expr>();
10862
10863        // Determine the result type
10864        QualType ResultTy = FnDecl->getResultType();
10865        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10866        ResultTy = ResultTy.getNonLValueExprType(Context);
10867
10868        // Build the actual expression node.
10869        DeclarationNameInfo OpLocInfo(OpName, LLoc);
10870        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10871        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10872                                                  Best->FoundDecl,
10873                                                  HadMultipleCandidates,
10874                                                  OpLocInfo.getLoc(),
10875                                                  OpLocInfo.getInfo());
10876        if (FnExpr.isInvalid())
10877          return ExprError();
10878
10879        CXXOperatorCallExpr *TheCall =
10880          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10881                                            FnExpr.take(), Args,
10882                                            ResultTy, VK, RLoc,
10883                                            false);
10884
10885        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10886                                FnDecl))
10887          return ExprError();
10888
10889        return MaybeBindToTemporary(TheCall);
10890      } else {
10891        // We matched a built-in operator. Convert the arguments, then
10892        // break out so that we will build the appropriate built-in
10893        // operator node.
10894        ExprResult ArgsRes0 =
10895          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10896                                    Best->Conversions[0], AA_Passing);
10897        if (ArgsRes0.isInvalid())
10898          return ExprError();
10899        Args[0] = ArgsRes0.take();
10900
10901        ExprResult ArgsRes1 =
10902          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10903                                    Best->Conversions[1], AA_Passing);
10904        if (ArgsRes1.isInvalid())
10905          return ExprError();
10906        Args[1] = ArgsRes1.take();
10907
10908        break;
10909      }
10910    }
10911
10912    case OR_No_Viable_Function: {
10913      if (CandidateSet.empty())
10914        Diag(LLoc, diag::err_ovl_no_oper)
10915          << Args[0]->getType() << /*subscript*/ 0
10916          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10917      else
10918        Diag(LLoc, diag::err_ovl_no_viable_subscript)
10919          << Args[0]->getType()
10920          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10921      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10922                                  "[]", LLoc);
10923      return ExprError();
10924    }
10925
10926    case OR_Ambiguous:
10927      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10928          << "[]"
10929          << Args[0]->getType() << Args[1]->getType()
10930          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10931      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10932                                  "[]", LLoc);
10933      return ExprError();
10934
10935    case OR_Deleted:
10936      Diag(LLoc, diag::err_ovl_deleted_oper)
10937        << Best->Function->isDeleted() << "[]"
10938        << getDeletedOrUnavailableSuffix(Best->Function)
10939        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10940      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10941                                  "[]", LLoc);
10942      return ExprError();
10943    }
10944
10945  // We matched a built-in operator; build it.
10946  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10947}
10948
10949/// BuildCallToMemberFunction - Build a call to a member
10950/// function. MemExpr is the expression that refers to the member
10951/// function (and includes the object parameter), Args/NumArgs are the
10952/// arguments to the function call (not including the object
10953/// parameter). The caller needs to validate that the member
10954/// expression refers to a non-static member function or an overloaded
10955/// member function.
10956ExprResult
10957Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10958                                SourceLocation LParenLoc,
10959                                MultiExprArg Args,
10960                                SourceLocation RParenLoc) {
10961  assert(MemExprE->getType() == Context.BoundMemberTy ||
10962         MemExprE->getType() == Context.OverloadTy);
10963
10964  // Dig out the member expression. This holds both the object
10965  // argument and the member function we're referring to.
10966  Expr *NakedMemExpr = MemExprE->IgnoreParens();
10967
10968  // Determine whether this is a call to a pointer-to-member function.
10969  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10970    assert(op->getType() == Context.BoundMemberTy);
10971    assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10972
10973    QualType fnType =
10974      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10975
10976    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10977    QualType resultType = proto->getCallResultType(Context);
10978    ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10979
10980    // Check that the object type isn't more qualified than the
10981    // member function we're calling.
10982    Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10983
10984    QualType objectType = op->getLHS()->getType();
10985    if (op->getOpcode() == BO_PtrMemI)
10986      objectType = objectType->castAs<PointerType>()->getPointeeType();
10987    Qualifiers objectQuals = objectType.getQualifiers();
10988
10989    Qualifiers difference = objectQuals - funcQuals;
10990    difference.removeObjCGCAttr();
10991    difference.removeAddressSpace();
10992    if (difference) {
10993      std::string qualsString = difference.getAsString();
10994      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10995        << fnType.getUnqualifiedType()
10996        << qualsString
10997        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10998    }
10999
11000    CXXMemberCallExpr *call
11001      = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11002                                        resultType, valueKind, RParenLoc);
11003
11004    if (CheckCallReturnType(proto->getResultType(),
11005                            op->getRHS()->getLocStart(),
11006                            call, 0))
11007      return ExprError();
11008
11009    if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
11010      return ExprError();
11011
11012    if (CheckOtherCall(call, proto))
11013      return ExprError();
11014
11015    return MaybeBindToTemporary(call);
11016  }
11017
11018  UnbridgedCastsSet UnbridgedCasts;
11019  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11020    return ExprError();
11021
11022  MemberExpr *MemExpr;
11023  CXXMethodDecl *Method = 0;
11024  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
11025  NestedNameSpecifier *Qualifier = 0;
11026  if (isa<MemberExpr>(NakedMemExpr)) {
11027    MemExpr = cast<MemberExpr>(NakedMemExpr);
11028    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11029    FoundDecl = MemExpr->getFoundDecl();
11030    Qualifier = MemExpr->getQualifier();
11031    UnbridgedCasts.restore();
11032  } else {
11033    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11034    Qualifier = UnresExpr->getQualifier();
11035
11036    QualType ObjectType = UnresExpr->getBaseType();
11037    Expr::Classification ObjectClassification
11038      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11039                            : UnresExpr->getBase()->Classify(Context);
11040
11041    // Add overload candidates
11042    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
11043
11044    // FIXME: avoid copy.
11045    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11046    if (UnresExpr->hasExplicitTemplateArgs()) {
11047      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11048      TemplateArgs = &TemplateArgsBuffer;
11049    }
11050
11051    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11052           E = UnresExpr->decls_end(); I != E; ++I) {
11053
11054      NamedDecl *Func = *I;
11055      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11056      if (isa<UsingShadowDecl>(Func))
11057        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11058
11059
11060      // Microsoft supports direct constructor calls.
11061      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11062        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11063                             Args, CandidateSet);
11064      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11065        // If explicit template arguments were provided, we can't call a
11066        // non-template member function.
11067        if (TemplateArgs)
11068          continue;
11069
11070        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11071                           ObjectClassification, Args, CandidateSet,
11072                           /*SuppressUserConversions=*/false);
11073      } else {
11074        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11075                                   I.getPair(), ActingDC, TemplateArgs,
11076                                   ObjectType,  ObjectClassification,
11077                                   Args, CandidateSet,
11078                                   /*SuppressUsedConversions=*/false);
11079      }
11080    }
11081
11082    DeclarationName DeclName = UnresExpr->getMemberName();
11083
11084    UnbridgedCasts.restore();
11085
11086    OverloadCandidateSet::iterator Best;
11087    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11088                                            Best)) {
11089    case OR_Success:
11090      Method = cast<CXXMethodDecl>(Best->Function);
11091      FoundDecl = Best->FoundDecl;
11092      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11093      if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11094        return ExprError();
11095      // If FoundDecl is different from Method (such as if one is a template
11096      // and the other a specialization), make sure DiagnoseUseOfDecl is
11097      // called on both.
11098      // FIXME: This would be more comprehensively addressed by modifying
11099      // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11100      // being used.
11101      if (Method != FoundDecl.getDecl() &&
11102                      DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11103        return ExprError();
11104      break;
11105
11106    case OR_No_Viable_Function:
11107      Diag(UnresExpr->getMemberLoc(),
11108           diag::err_ovl_no_viable_member_function_in_call)
11109        << DeclName << MemExprE->getSourceRange();
11110      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11111      // FIXME: Leaking incoming expressions!
11112      return ExprError();
11113
11114    case OR_Ambiguous:
11115      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11116        << DeclName << MemExprE->getSourceRange();
11117      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11118      // FIXME: Leaking incoming expressions!
11119      return ExprError();
11120
11121    case OR_Deleted:
11122      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11123        << Best->Function->isDeleted()
11124        << DeclName
11125        << getDeletedOrUnavailableSuffix(Best->Function)
11126        << MemExprE->getSourceRange();
11127      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11128      // FIXME: Leaking incoming expressions!
11129      return ExprError();
11130    }
11131
11132    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11133
11134    // If overload resolution picked a static member, build a
11135    // non-member call based on that function.
11136    if (Method->isStatic()) {
11137      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11138                                   RParenLoc);
11139    }
11140
11141    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11142  }
11143
11144  QualType ResultType = Method->getResultType();
11145  ExprValueKind VK = Expr::getValueKindForType(ResultType);
11146  ResultType = ResultType.getNonLValueExprType(Context);
11147
11148  assert(Method && "Member call to something that isn't a method?");
11149  CXXMemberCallExpr *TheCall =
11150    new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11151                                    ResultType, VK, RParenLoc);
11152
11153  // Check for a valid return type.
11154  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
11155                          TheCall, Method))
11156    return ExprError();
11157
11158  // Convert the object argument (for a non-static member function call).
11159  // We only need to do this if there was actually an overload; otherwise
11160  // it was done at lookup.
11161  if (!Method->isStatic()) {
11162    ExprResult ObjectArg =
11163      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11164                                          FoundDecl, Method);
11165    if (ObjectArg.isInvalid())
11166      return ExprError();
11167    MemExpr->setBase(ObjectArg.take());
11168  }
11169
11170  // Convert the rest of the arguments
11171  const FunctionProtoType *Proto =
11172    Method->getType()->getAs<FunctionProtoType>();
11173  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11174                              RParenLoc))
11175    return ExprError();
11176
11177  DiagnoseSentinelCalls(Method, LParenLoc, Args);
11178
11179  if (CheckFunctionCall(Method, TheCall, Proto))
11180    return ExprError();
11181
11182  if ((isa<CXXConstructorDecl>(CurContext) ||
11183       isa<CXXDestructorDecl>(CurContext)) &&
11184      TheCall->getMethodDecl()->isPure()) {
11185    const CXXMethodDecl *MD = TheCall->getMethodDecl();
11186
11187    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11188      Diag(MemExpr->getLocStart(),
11189           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11190        << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11191        << MD->getParent()->getDeclName();
11192
11193      Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11194    }
11195  }
11196  return MaybeBindToTemporary(TheCall);
11197}
11198
11199/// BuildCallToObjectOfClassType - Build a call to an object of class
11200/// type (C++ [over.call.object]), which can end up invoking an
11201/// overloaded function call operator (@c operator()) or performing a
11202/// user-defined conversion on the object argument.
11203ExprResult
11204Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11205                                   SourceLocation LParenLoc,
11206                                   MultiExprArg Args,
11207                                   SourceLocation RParenLoc) {
11208  if (checkPlaceholderForOverload(*this, Obj))
11209    return ExprError();
11210  ExprResult Object = Owned(Obj);
11211
11212  UnbridgedCastsSet UnbridgedCasts;
11213  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11214    return ExprError();
11215
11216  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11217  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11218
11219  // C++ [over.call.object]p1:
11220  //  If the primary-expression E in the function call syntax
11221  //  evaluates to a class object of type "cv T", then the set of
11222  //  candidate functions includes at least the function call
11223  //  operators of T. The function call operators of T are obtained by
11224  //  ordinary lookup of the name operator() in the context of
11225  //  (E).operator().
11226  OverloadCandidateSet CandidateSet(LParenLoc);
11227  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11228
11229  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11230                          diag::err_incomplete_object_call, Object.get()))
11231    return true;
11232
11233  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11234  LookupQualifiedName(R, Record->getDecl());
11235  R.suppressDiagnostics();
11236
11237  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11238       Oper != OperEnd; ++Oper) {
11239    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11240                       Object.get()->Classify(Context),
11241                       Args, CandidateSet,
11242                       /*SuppressUserConversions=*/ false);
11243  }
11244
11245  // C++ [over.call.object]p2:
11246  //   In addition, for each (non-explicit in C++0x) conversion function
11247  //   declared in T of the form
11248  //
11249  //        operator conversion-type-id () cv-qualifier;
11250  //
11251  //   where cv-qualifier is the same cv-qualification as, or a
11252  //   greater cv-qualification than, cv, and where conversion-type-id
11253  //   denotes the type "pointer to function of (P1,...,Pn) returning
11254  //   R", or the type "reference to pointer to function of
11255  //   (P1,...,Pn) returning R", or the type "reference to function
11256  //   of (P1,...,Pn) returning R", a surrogate call function [...]
11257  //   is also considered as a candidate function. Similarly,
11258  //   surrogate call functions are added to the set of candidate
11259  //   functions for each conversion function declared in an
11260  //   accessible base class provided the function is not hidden
11261  //   within T by another intervening declaration.
11262  std::pair<CXXRecordDecl::conversion_iterator,
11263            CXXRecordDecl::conversion_iterator> Conversions
11264    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11265  for (CXXRecordDecl::conversion_iterator
11266         I = Conversions.first, E = Conversions.second; I != E; ++I) {
11267    NamedDecl *D = *I;
11268    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11269    if (isa<UsingShadowDecl>(D))
11270      D = cast<UsingShadowDecl>(D)->getTargetDecl();
11271
11272    // Skip over templated conversion functions; they aren't
11273    // surrogates.
11274    if (isa<FunctionTemplateDecl>(D))
11275      continue;
11276
11277    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11278    if (!Conv->isExplicit()) {
11279      // Strip the reference type (if any) and then the pointer type (if
11280      // any) to get down to what might be a function type.
11281      QualType ConvType = Conv->getConversionType().getNonReferenceType();
11282      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11283        ConvType = ConvPtrType->getPointeeType();
11284
11285      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11286      {
11287        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11288                              Object.get(), Args, CandidateSet);
11289      }
11290    }
11291  }
11292
11293  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11294
11295  // Perform overload resolution.
11296  OverloadCandidateSet::iterator Best;
11297  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11298                             Best)) {
11299  case OR_Success:
11300    // Overload resolution succeeded; we'll build the appropriate call
11301    // below.
11302    break;
11303
11304  case OR_No_Viable_Function:
11305    if (CandidateSet.empty())
11306      Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11307        << Object.get()->getType() << /*call*/ 1
11308        << Object.get()->getSourceRange();
11309    else
11310      Diag(Object.get()->getLocStart(),
11311           diag::err_ovl_no_viable_object_call)
11312        << Object.get()->getType() << Object.get()->getSourceRange();
11313    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11314    break;
11315
11316  case OR_Ambiguous:
11317    Diag(Object.get()->getLocStart(),
11318         diag::err_ovl_ambiguous_object_call)
11319      << Object.get()->getType() << Object.get()->getSourceRange();
11320    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11321    break;
11322
11323  case OR_Deleted:
11324    Diag(Object.get()->getLocStart(),
11325         diag::err_ovl_deleted_object_call)
11326      << Best->Function->isDeleted()
11327      << Object.get()->getType()
11328      << getDeletedOrUnavailableSuffix(Best->Function)
11329      << Object.get()->getSourceRange();
11330    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11331    break;
11332  }
11333
11334  if (Best == CandidateSet.end())
11335    return true;
11336
11337  UnbridgedCasts.restore();
11338
11339  if (Best->Function == 0) {
11340    // Since there is no function declaration, this is one of the
11341    // surrogate candidates. Dig out the conversion function.
11342    CXXConversionDecl *Conv
11343      = cast<CXXConversionDecl>(
11344                         Best->Conversions[0].UserDefined.ConversionFunction);
11345
11346    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11347    if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11348      return ExprError();
11349    assert(Conv == Best->FoundDecl.getDecl() &&
11350             "Found Decl & conversion-to-functionptr should be same, right?!");
11351    // We selected one of the surrogate functions that converts the
11352    // object parameter to a function pointer. Perform the conversion
11353    // on the object argument, then let ActOnCallExpr finish the job.
11354
11355    // Create an implicit member expr to refer to the conversion operator.
11356    // and then call it.
11357    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11358                                             Conv, HadMultipleCandidates);
11359    if (Call.isInvalid())
11360      return ExprError();
11361    // Record usage of conversion in an implicit cast.
11362    Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11363                                          CK_UserDefinedConversion,
11364                                          Call.get(), 0, VK_RValue));
11365
11366    return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11367  }
11368
11369  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11370
11371  // We found an overloaded operator(). Build a CXXOperatorCallExpr
11372  // that calls this method, using Object for the implicit object
11373  // parameter and passing along the remaining arguments.
11374  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11375
11376  // An error diagnostic has already been printed when parsing the declaration.
11377  if (Method->isInvalidDecl())
11378    return ExprError();
11379
11380  const FunctionProtoType *Proto =
11381    Method->getType()->getAs<FunctionProtoType>();
11382
11383  unsigned NumArgsInProto = Proto->getNumArgs();
11384  unsigned NumArgsToCheck = Args.size();
11385
11386  // Build the full argument list for the method call (the
11387  // implicit object parameter is placed at the beginning of the
11388  // list).
11389  Expr **MethodArgs;
11390  if (Args.size() < NumArgsInProto) {
11391    NumArgsToCheck = NumArgsInProto;
11392    MethodArgs = new Expr*[NumArgsInProto + 1];
11393  } else {
11394    MethodArgs = new Expr*[Args.size() + 1];
11395  }
11396  MethodArgs[0] = Object.get();
11397  for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
11398    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
11399
11400  DeclarationNameInfo OpLocInfo(
11401               Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11402  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11403  ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11404                                           HadMultipleCandidates,
11405                                           OpLocInfo.getLoc(),
11406                                           OpLocInfo.getInfo());
11407  if (NewFn.isInvalid())
11408    return true;
11409
11410  // Once we've built TheCall, all of the expressions are properly
11411  // owned.
11412  QualType ResultTy = Method->getResultType();
11413  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11414  ResultTy = ResultTy.getNonLValueExprType(Context);
11415
11416  CXXOperatorCallExpr *TheCall =
11417    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11418                                      llvm::makeArrayRef(MethodArgs, Args.size()+1),
11419                                      ResultTy, VK, RParenLoc, false);
11420  delete [] MethodArgs;
11421
11422  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11423                          Method))
11424    return true;
11425
11426  // We may have default arguments. If so, we need to allocate more
11427  // slots in the call for them.
11428  if (Args.size() < NumArgsInProto)
11429    TheCall->setNumArgs(Context, NumArgsInProto + 1);
11430  else if (Args.size() > NumArgsInProto)
11431    NumArgsToCheck = NumArgsInProto;
11432
11433  bool IsError = false;
11434
11435  // Initialize the implicit object parameter.
11436  ExprResult ObjRes =
11437    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11438                                        Best->FoundDecl, Method);
11439  if (ObjRes.isInvalid())
11440    IsError = true;
11441  else
11442    Object = ObjRes;
11443  TheCall->setArg(0, Object.take());
11444
11445  // Check the argument types.
11446  for (unsigned i = 0; i != NumArgsToCheck; i++) {
11447    Expr *Arg;
11448    if (i < Args.size()) {
11449      Arg = Args[i];
11450
11451      // Pass the argument.
11452
11453      ExprResult InputInit
11454        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11455                                                    Context,
11456                                                    Method->getParamDecl(i)),
11457                                    SourceLocation(), Arg);
11458
11459      IsError |= InputInit.isInvalid();
11460      Arg = InputInit.takeAs<Expr>();
11461    } else {
11462      ExprResult DefArg
11463        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11464      if (DefArg.isInvalid()) {
11465        IsError = true;
11466        break;
11467      }
11468
11469      Arg = DefArg.takeAs<Expr>();
11470    }
11471
11472    TheCall->setArg(i + 1, Arg);
11473  }
11474
11475  // If this is a variadic call, handle args passed through "...".
11476  if (Proto->isVariadic()) {
11477    // Promote the arguments (C99 6.5.2.2p7).
11478    for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
11479      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11480      IsError |= Arg.isInvalid();
11481      TheCall->setArg(i + 1, Arg.take());
11482    }
11483  }
11484
11485  if (IsError) return true;
11486
11487  DiagnoseSentinelCalls(Method, LParenLoc, Args);
11488
11489  if (CheckFunctionCall(Method, TheCall, Proto))
11490    return true;
11491
11492  return MaybeBindToTemporary(TheCall);
11493}
11494
11495/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11496///  (if one exists), where @c Base is an expression of class type and
11497/// @c Member is the name of the member we're trying to find.
11498ExprResult
11499Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11500                               bool *NoArrowOperatorFound) {
11501  assert(Base->getType()->isRecordType() &&
11502         "left-hand side must have class type");
11503
11504  if (checkPlaceholderForOverload(*this, Base))
11505    return ExprError();
11506
11507  SourceLocation Loc = Base->getExprLoc();
11508
11509  // C++ [over.ref]p1:
11510  //
11511  //   [...] An expression x->m is interpreted as (x.operator->())->m
11512  //   for a class object x of type T if T::operator->() exists and if
11513  //   the operator is selected as the best match function by the
11514  //   overload resolution mechanism (13.3).
11515  DeclarationName OpName =
11516    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11517  OverloadCandidateSet CandidateSet(Loc);
11518  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11519
11520  if (RequireCompleteType(Loc, Base->getType(),
11521                          diag::err_typecheck_incomplete_tag, Base))
11522    return ExprError();
11523
11524  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11525  LookupQualifiedName(R, BaseRecord->getDecl());
11526  R.suppressDiagnostics();
11527
11528  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11529       Oper != OperEnd; ++Oper) {
11530    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11531                       None, CandidateSet, /*SuppressUserConversions=*/false);
11532  }
11533
11534  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11535
11536  // Perform overload resolution.
11537  OverloadCandidateSet::iterator Best;
11538  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11539  case OR_Success:
11540    // Overload resolution succeeded; we'll build the call below.
11541    break;
11542
11543  case OR_No_Viable_Function:
11544    if (CandidateSet.empty()) {
11545      QualType BaseType = Base->getType();
11546      if (NoArrowOperatorFound) {
11547        // Report this specific error to the caller instead of emitting a
11548        // diagnostic, as requested.
11549        *NoArrowOperatorFound = true;
11550        return ExprError();
11551      }
11552      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11553        << BaseType << Base->getSourceRange();
11554      if (BaseType->isRecordType() && !BaseType->isPointerType()) {
11555        Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
11556          << FixItHint::CreateReplacement(OpLoc, ".");
11557      }
11558    } else
11559      Diag(OpLoc, diag::err_ovl_no_viable_oper)
11560        << "operator->" << Base->getSourceRange();
11561    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11562    return ExprError();
11563
11564  case OR_Ambiguous:
11565    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11566      << "->" << Base->getType() << Base->getSourceRange();
11567    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11568    return ExprError();
11569
11570  case OR_Deleted:
11571    Diag(OpLoc,  diag::err_ovl_deleted_oper)
11572      << Best->Function->isDeleted()
11573      << "->"
11574      << getDeletedOrUnavailableSuffix(Best->Function)
11575      << Base->getSourceRange();
11576    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11577    return ExprError();
11578  }
11579
11580  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11581
11582  // Convert the object parameter.
11583  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11584  ExprResult BaseResult =
11585    PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11586                                        Best->FoundDecl, Method);
11587  if (BaseResult.isInvalid())
11588    return ExprError();
11589  Base = BaseResult.take();
11590
11591  // Build the operator call.
11592  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11593                                            HadMultipleCandidates, OpLoc);
11594  if (FnExpr.isInvalid())
11595    return ExprError();
11596
11597  QualType ResultTy = Method->getResultType();
11598  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11599  ResultTy = ResultTy.getNonLValueExprType(Context);
11600  CXXOperatorCallExpr *TheCall =
11601    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11602                                      Base, ResultTy, VK, OpLoc, false);
11603
11604  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11605                          Method))
11606          return ExprError();
11607
11608  return MaybeBindToTemporary(TheCall);
11609}
11610
11611/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11612/// a literal operator described by the provided lookup results.
11613ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11614                                          DeclarationNameInfo &SuffixInfo,
11615                                          ArrayRef<Expr*> Args,
11616                                          SourceLocation LitEndLoc,
11617                                       TemplateArgumentListInfo *TemplateArgs) {
11618  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11619
11620  OverloadCandidateSet CandidateSet(UDSuffixLoc);
11621  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11622                        TemplateArgs);
11623
11624  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11625
11626  // Perform overload resolution. This will usually be trivial, but might need
11627  // to perform substitutions for a literal operator template.
11628  OverloadCandidateSet::iterator Best;
11629  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11630  case OR_Success:
11631  case OR_Deleted:
11632    break;
11633
11634  case OR_No_Viable_Function:
11635    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11636      << R.getLookupName();
11637    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11638    return ExprError();
11639
11640  case OR_Ambiguous:
11641    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11642    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11643    return ExprError();
11644  }
11645
11646  FunctionDecl *FD = Best->Function;
11647  ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11648                                        HadMultipleCandidates,
11649                                        SuffixInfo.getLoc(),
11650                                        SuffixInfo.getInfo());
11651  if (Fn.isInvalid())
11652    return true;
11653
11654  // Check the argument types. This should almost always be a no-op, except
11655  // that array-to-pointer decay is applied to string literals.
11656  Expr *ConvArgs[2];
11657  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
11658    ExprResult InputInit = PerformCopyInitialization(
11659      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11660      SourceLocation(), Args[ArgIdx]);
11661    if (InputInit.isInvalid())
11662      return true;
11663    ConvArgs[ArgIdx] = InputInit.take();
11664  }
11665
11666  QualType ResultTy = FD->getResultType();
11667  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11668  ResultTy = ResultTy.getNonLValueExprType(Context);
11669
11670  UserDefinedLiteral *UDL =
11671    new (Context) UserDefinedLiteral(Context, Fn.take(),
11672                                     llvm::makeArrayRef(ConvArgs, Args.size()),
11673                                     ResultTy, VK, LitEndLoc, UDSuffixLoc);
11674
11675  if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11676    return ExprError();
11677
11678  if (CheckFunctionCall(FD, UDL, NULL))
11679    return ExprError();
11680
11681  return MaybeBindToTemporary(UDL);
11682}
11683
11684/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11685/// given LookupResult is non-empty, it is assumed to describe a member which
11686/// will be invoked. Otherwise, the function will be found via argument
11687/// dependent lookup.
11688/// CallExpr is set to a valid expression and FRS_Success returned on success,
11689/// otherwise CallExpr is set to ExprError() and some non-success value
11690/// is returned.
11691Sema::ForRangeStatus
11692Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11693                                SourceLocation RangeLoc, VarDecl *Decl,
11694                                BeginEndFunction BEF,
11695                                const DeclarationNameInfo &NameInfo,
11696                                LookupResult &MemberLookup,
11697                                OverloadCandidateSet *CandidateSet,
11698                                Expr *Range, ExprResult *CallExpr) {
11699  CandidateSet->clear();
11700  if (!MemberLookup.empty()) {
11701    ExprResult MemberRef =
11702        BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11703                                 /*IsPtr=*/false, CXXScopeSpec(),
11704                                 /*TemplateKWLoc=*/SourceLocation(),
11705                                 /*FirstQualifierInScope=*/0,
11706                                 MemberLookup,
11707                                 /*TemplateArgs=*/0);
11708    if (MemberRef.isInvalid()) {
11709      *CallExpr = ExprError();
11710      Diag(Range->getLocStart(), diag::note_in_for_range)
11711          << RangeLoc << BEF << Range->getType();
11712      return FRS_DiagnosticIssued;
11713    }
11714    *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
11715    if (CallExpr->isInvalid()) {
11716      *CallExpr = ExprError();
11717      Diag(Range->getLocStart(), diag::note_in_for_range)
11718          << RangeLoc << BEF << Range->getType();
11719      return FRS_DiagnosticIssued;
11720    }
11721  } else {
11722    UnresolvedSet<0> FoundNames;
11723    UnresolvedLookupExpr *Fn =
11724      UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11725                                   NestedNameSpecifierLoc(), NameInfo,
11726                                   /*NeedsADL=*/true, /*Overloaded=*/false,
11727                                   FoundNames.begin(), FoundNames.end());
11728
11729    bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
11730                                                    CandidateSet, CallExpr);
11731    if (CandidateSet->empty() || CandidateSetError) {
11732      *CallExpr = ExprError();
11733      return FRS_NoViableFunction;
11734    }
11735    OverloadCandidateSet::iterator Best;
11736    OverloadingResult OverloadResult =
11737        CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11738
11739    if (OverloadResult == OR_No_Viable_Function) {
11740      *CallExpr = ExprError();
11741      return FRS_NoViableFunction;
11742    }
11743    *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
11744                                         Loc, 0, CandidateSet, &Best,
11745                                         OverloadResult,
11746                                         /*AllowTypoCorrection=*/false);
11747    if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11748      *CallExpr = ExprError();
11749      Diag(Range->getLocStart(), diag::note_in_for_range)
11750          << RangeLoc << BEF << Range->getType();
11751      return FRS_DiagnosticIssued;
11752    }
11753  }
11754  return FRS_Success;
11755}
11756
11757
11758/// FixOverloadedFunctionReference - E is an expression that refers to
11759/// a C++ overloaded function (possibly with some parentheses and
11760/// perhaps a '&' around it). We have resolved the overloaded function
11761/// to the function declaration Fn, so patch up the expression E to
11762/// refer (possibly indirectly) to Fn. Returns the new expr.
11763Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11764                                           FunctionDecl *Fn) {
11765  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11766    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11767                                                   Found, Fn);
11768    if (SubExpr == PE->getSubExpr())
11769      return PE;
11770
11771    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11772  }
11773
11774  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11775    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11776                                                   Found, Fn);
11777    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11778                               SubExpr->getType()) &&
11779           "Implicit cast type cannot be determined from overload");
11780    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11781    if (SubExpr == ICE->getSubExpr())
11782      return ICE;
11783
11784    return ImplicitCastExpr::Create(Context, ICE->getType(),
11785                                    ICE->getCastKind(),
11786                                    SubExpr, 0,
11787                                    ICE->getValueKind());
11788  }
11789
11790  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11791    assert(UnOp->getOpcode() == UO_AddrOf &&
11792           "Can only take the address of an overloaded function");
11793    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11794      if (Method->isStatic()) {
11795        // Do nothing: static member functions aren't any different
11796        // from non-member functions.
11797      } else {
11798        // Fix the sub expression, which really has to be an
11799        // UnresolvedLookupExpr holding an overloaded member function
11800        // or template.
11801        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11802                                                       Found, Fn);
11803        if (SubExpr == UnOp->getSubExpr())
11804          return UnOp;
11805
11806        assert(isa<DeclRefExpr>(SubExpr)
11807               && "fixed to something other than a decl ref");
11808        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11809               && "fixed to a member ref with no nested name qualifier");
11810
11811        // We have taken the address of a pointer to member
11812        // function. Perform the computation here so that we get the
11813        // appropriate pointer to member type.
11814        QualType ClassType
11815          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11816        QualType MemPtrType
11817          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11818
11819        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11820                                           VK_RValue, OK_Ordinary,
11821                                           UnOp->getOperatorLoc());
11822      }
11823    }
11824    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11825                                                   Found, Fn);
11826    if (SubExpr == UnOp->getSubExpr())
11827      return UnOp;
11828
11829    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11830                                     Context.getPointerType(SubExpr->getType()),
11831                                       VK_RValue, OK_Ordinary,
11832                                       UnOp->getOperatorLoc());
11833  }
11834
11835  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11836    // FIXME: avoid copy.
11837    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11838    if (ULE->hasExplicitTemplateArgs()) {
11839      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11840      TemplateArgs = &TemplateArgsBuffer;
11841    }
11842
11843    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11844                                           ULE->getQualifierLoc(),
11845                                           ULE->getTemplateKeywordLoc(),
11846                                           Fn,
11847                                           /*enclosing*/ false, // FIXME?
11848                                           ULE->getNameLoc(),
11849                                           Fn->getType(),
11850                                           VK_LValue,
11851                                           Found.getDecl(),
11852                                           TemplateArgs);
11853    MarkDeclRefReferenced(DRE);
11854    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11855    return DRE;
11856  }
11857
11858  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11859    // FIXME: avoid copy.
11860    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11861    if (MemExpr->hasExplicitTemplateArgs()) {
11862      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11863      TemplateArgs = &TemplateArgsBuffer;
11864    }
11865
11866    Expr *Base;
11867
11868    // If we're filling in a static method where we used to have an
11869    // implicit member access, rewrite to a simple decl ref.
11870    if (MemExpr->isImplicitAccess()) {
11871      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11872        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11873                                               MemExpr->getQualifierLoc(),
11874                                               MemExpr->getTemplateKeywordLoc(),
11875                                               Fn,
11876                                               /*enclosing*/ false,
11877                                               MemExpr->getMemberLoc(),
11878                                               Fn->getType(),
11879                                               VK_LValue,
11880                                               Found.getDecl(),
11881                                               TemplateArgs);
11882        MarkDeclRefReferenced(DRE);
11883        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11884        return DRE;
11885      } else {
11886        SourceLocation Loc = MemExpr->getMemberLoc();
11887        if (MemExpr->getQualifier())
11888          Loc = MemExpr->getQualifierLoc().getBeginLoc();
11889        CheckCXXThisCapture(Loc);
11890        Base = new (Context) CXXThisExpr(Loc,
11891                                         MemExpr->getBaseType(),
11892                                         /*isImplicit=*/true);
11893      }
11894    } else
11895      Base = MemExpr->getBase();
11896
11897    ExprValueKind valueKind;
11898    QualType type;
11899    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11900      valueKind = VK_LValue;
11901      type = Fn->getType();
11902    } else {
11903      valueKind = VK_RValue;
11904      type = Context.BoundMemberTy;
11905    }
11906
11907    MemberExpr *ME = MemberExpr::Create(Context, Base,
11908                                        MemExpr->isArrow(),
11909                                        MemExpr->getQualifierLoc(),
11910                                        MemExpr->getTemplateKeywordLoc(),
11911                                        Fn,
11912                                        Found,
11913                                        MemExpr->getMemberNameInfo(),
11914                                        TemplateArgs,
11915                                        type, valueKind, OK_Ordinary);
11916    ME->setHadMultipleCandidates(true);
11917    MarkMemberReferenced(ME);
11918    return ME;
11919  }
11920
11921  llvm_unreachable("Invalid reference to overloaded function");
11922}
11923
11924ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11925                                                DeclAccessPair Found,
11926                                                FunctionDecl *Fn) {
11927  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11928}
11929
11930} // end namespace clang
11931