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