SemaOverload.cpp revision d2fdd4256a2efc41365ccdd27a210d1d99a1fe3a
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Overload.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/TypeOrdering.h"
22#include "clang/Basic/Diagnostic.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallString.h"
34#include <algorithm>
35
36namespace clang {
37using namespace sema;
38
39/// A convenience routine for creating a decayed reference to a function.
40static ExprResult
41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42                      bool HadMultipleCandidates,
43                      SourceLocation Loc = SourceLocation(),
44                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
45  DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
46                                                 VK_LValue, Loc, LocInfo);
47  if (HadMultipleCandidates)
48    DRE->setHadMultipleCandidates(true);
49
50  S.MarkDeclRefReferenced(DRE);
51  S.DiagnoseUseOfDecl(FoundDecl, Loc);
52
53  ExprResult E = S.Owned(DRE);
54  E = S.DefaultFunctionArrayConversion(E.take());
55  if (E.isInvalid())
56    return ExprError();
57  return E;
58}
59
60static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
61                                 bool InOverloadResolution,
62                                 StandardConversionSequence &SCS,
63                                 bool CStyle,
64                                 bool AllowObjCWritebackConversion);
65
66static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
67                                                 QualType &ToType,
68                                                 bool InOverloadResolution,
69                                                 StandardConversionSequence &SCS,
70                                                 bool CStyle);
71static OverloadingResult
72IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
73                        UserDefinedConversionSequence& User,
74                        OverloadCandidateSet& Conversions,
75                        bool AllowExplicit);
76
77
78static ImplicitConversionSequence::CompareKind
79CompareStandardConversionSequences(Sema &S,
80                                   const StandardConversionSequence& SCS1,
81                                   const StandardConversionSequence& SCS2);
82
83static ImplicitConversionSequence::CompareKind
84CompareQualificationConversions(Sema &S,
85                                const StandardConversionSequence& SCS1,
86                                const StandardConversionSequence& SCS2);
87
88static ImplicitConversionSequence::CompareKind
89CompareDerivedToBaseConversions(Sema &S,
90                                const StandardConversionSequence& SCS1,
91                                const StandardConversionSequence& SCS2);
92
93
94
95/// GetConversionCategory - Retrieve the implicit conversion
96/// category corresponding to the given implicit conversion kind.
97ImplicitConversionCategory
98GetConversionCategory(ImplicitConversionKind Kind) {
99  static const ImplicitConversionCategory
100    Category[(int)ICK_Num_Conversion_Kinds] = {
101    ICC_Identity,
102    ICC_Lvalue_Transformation,
103    ICC_Lvalue_Transformation,
104    ICC_Lvalue_Transformation,
105    ICC_Identity,
106    ICC_Qualification_Adjustment,
107    ICC_Promotion,
108    ICC_Promotion,
109    ICC_Promotion,
110    ICC_Conversion,
111    ICC_Conversion,
112    ICC_Conversion,
113    ICC_Conversion,
114    ICC_Conversion,
115    ICC_Conversion,
116    ICC_Conversion,
117    ICC_Conversion,
118    ICC_Conversion,
119    ICC_Conversion,
120    ICC_Conversion,
121    ICC_Conversion,
122    ICC_Conversion
123  };
124  return Category[(int)Kind];
125}
126
127/// GetConversionRank - Retrieve the implicit conversion rank
128/// corresponding to the given implicit conversion kind.
129ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
130  static const ImplicitConversionRank
131    Rank[(int)ICK_Num_Conversion_Kinds] = {
132    ICR_Exact_Match,
133    ICR_Exact_Match,
134    ICR_Exact_Match,
135    ICR_Exact_Match,
136    ICR_Exact_Match,
137    ICR_Exact_Match,
138    ICR_Promotion,
139    ICR_Promotion,
140    ICR_Promotion,
141    ICR_Conversion,
142    ICR_Conversion,
143    ICR_Conversion,
144    ICR_Conversion,
145    ICR_Conversion,
146    ICR_Conversion,
147    ICR_Conversion,
148    ICR_Conversion,
149    ICR_Conversion,
150    ICR_Conversion,
151    ICR_Conversion,
152    ICR_Complex_Real_Conversion,
153    ICR_Conversion,
154    ICR_Conversion,
155    ICR_Writeback_Conversion
156  };
157  return Rank[(int)Kind];
158}
159
160/// GetImplicitConversionName - Return the name of this kind of
161/// implicit conversion.
162const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
163  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
164    "No conversion",
165    "Lvalue-to-rvalue",
166    "Array-to-pointer",
167    "Function-to-pointer",
168    "Noreturn adjustment",
169    "Qualification",
170    "Integral promotion",
171    "Floating point promotion",
172    "Complex promotion",
173    "Integral conversion",
174    "Floating conversion",
175    "Complex conversion",
176    "Floating-integral conversion",
177    "Pointer conversion",
178    "Pointer-to-member conversion",
179    "Boolean conversion",
180    "Compatible-types conversion",
181    "Derived-to-base conversion",
182    "Vector conversion",
183    "Vector splat",
184    "Complex-real conversion",
185    "Block Pointer conversion",
186    "Transparent Union Conversion"
187    "Writeback conversion"
188  };
189  return Name[Kind];
190}
191
192/// StandardConversionSequence - Set the standard conversion
193/// sequence to the identity conversion.
194void StandardConversionSequence::setAsIdentityConversion() {
195  First = ICK_Identity;
196  Second = ICK_Identity;
197  Third = ICK_Identity;
198  DeprecatedStringLiteralToCharPtr = false;
199  QualificationIncludesObjCLifetime = false;
200  ReferenceBinding = false;
201  DirectBinding = false;
202  IsLvalueReference = true;
203  BindsToFunctionLvalue = false;
204  BindsToRvalue = false;
205  BindsImplicitObjectArgumentWithoutRefQualifier = false;
206  ObjCLifetimeConversionBinding = false;
207  CopyConstructor = 0;
208}
209
210/// getRank - Retrieve the rank of this standard conversion sequence
211/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
212/// implicit conversions.
213ImplicitConversionRank StandardConversionSequence::getRank() const {
214  ImplicitConversionRank Rank = ICR_Exact_Match;
215  if  (GetConversionRank(First) > Rank)
216    Rank = GetConversionRank(First);
217  if  (GetConversionRank(Second) > Rank)
218    Rank = GetConversionRank(Second);
219  if  (GetConversionRank(Third) > Rank)
220    Rank = GetConversionRank(Third);
221  return Rank;
222}
223
224/// isPointerConversionToBool - Determines whether this conversion is
225/// a conversion of a pointer or pointer-to-member to bool. This is
226/// used as part of the ranking of standard conversion sequences
227/// (C++ 13.3.3.2p4).
228bool StandardConversionSequence::isPointerConversionToBool() const {
229  // Note that FromType has not necessarily been transformed by the
230  // array-to-pointer or function-to-pointer implicit conversions, so
231  // check for their presence as well as checking whether FromType is
232  // a pointer.
233  if (getToType(1)->isBooleanType() &&
234      (getFromType()->isPointerType() ||
235       getFromType()->isObjCObjectPointerType() ||
236       getFromType()->isBlockPointerType() ||
237       getFromType()->isNullPtrType() ||
238       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
239    return true;
240
241  return false;
242}
243
244/// isPointerConversionToVoidPointer - Determines whether this
245/// conversion is a conversion of a pointer to a void pointer. This is
246/// used as part of the ranking of standard conversion sequences (C++
247/// 13.3.3.2p4).
248bool
249StandardConversionSequence::
250isPointerConversionToVoidPointer(ASTContext& Context) const {
251  QualType FromType = getFromType();
252  QualType ToType = getToType(1);
253
254  // Note that FromType has not necessarily been transformed by the
255  // array-to-pointer implicit conversion, so check for its presence
256  // and redo the conversion to get a pointer.
257  if (First == ICK_Array_To_Pointer)
258    FromType = Context.getArrayDecayedType(FromType);
259
260  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
261    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
262      return ToPtrType->getPointeeType()->isVoidType();
263
264  return false;
265}
266
267/// Skip any implicit casts which could be either part of a narrowing conversion
268/// or after one in an implicit conversion.
269static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
270  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
271    switch (ICE->getCastKind()) {
272    case CK_NoOp:
273    case CK_IntegralCast:
274    case CK_IntegralToBoolean:
275    case CK_IntegralToFloating:
276    case CK_FloatingToIntegral:
277    case CK_FloatingToBoolean:
278    case CK_FloatingCast:
279      Converted = ICE->getSubExpr();
280      continue;
281
282    default:
283      return Converted;
284    }
285  }
286
287  return Converted;
288}
289
290/// Check if this standard conversion sequence represents a narrowing
291/// conversion, according to C++11 [dcl.init.list]p7.
292///
293/// \param Ctx  The AST context.
294/// \param Converted  The result of applying this standard conversion sequence.
295/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
296///        value of the expression prior to the narrowing conversion.
297/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
298///        type of the expression prior to the narrowing conversion.
299NarrowingKind
300StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
301                                             const Expr *Converted,
302                                             APValue &ConstantValue,
303                                             QualType &ConstantType) const {
304  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
305
306  // C++11 [dcl.init.list]p7:
307  //   A narrowing conversion is an implicit conversion ...
308  QualType FromType = getToType(0);
309  QualType ToType = getToType(1);
310  switch (Second) {
311  // -- from a floating-point type to an integer type, or
312  //
313  // -- from an integer type or unscoped enumeration type to a floating-point
314  //    type, except where the source is a constant expression and the actual
315  //    value after conversion will fit into the target type and will produce
316  //    the original value when converted back to the original type, or
317  case ICK_Floating_Integral:
318    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
319      return NK_Type_Narrowing;
320    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
321      llvm::APSInt IntConstantValue;
322      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
323      if (Initializer &&
324          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
325        // Convert the integer to the floating type.
326        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
327        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
328                                llvm::APFloat::rmNearestTiesToEven);
329        // And back.
330        llvm::APSInt ConvertedValue = IntConstantValue;
331        bool ignored;
332        Result.convertToInteger(ConvertedValue,
333                                llvm::APFloat::rmTowardZero, &ignored);
334        // If the resulting value is different, this was a narrowing conversion.
335        if (IntConstantValue != ConvertedValue) {
336          ConstantValue = APValue(IntConstantValue);
337          ConstantType = Initializer->getType();
338          return NK_Constant_Narrowing;
339        }
340      } else {
341        // Variables are always narrowings.
342        return NK_Variable_Narrowing;
343      }
344    }
345    return NK_Not_Narrowing;
346
347  // -- from long double to double or float, or from double to float, except
348  //    where the source is a constant expression and the actual value after
349  //    conversion is within the range of values that can be represented (even
350  //    if it cannot be represented exactly), or
351  case ICK_Floating_Conversion:
352    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
353        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
354      // FromType is larger than ToType.
355      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
356      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
357        // Constant!
358        assert(ConstantValue.isFloat());
359        llvm::APFloat FloatVal = ConstantValue.getFloat();
360        // Convert the source value into the target type.
361        bool ignored;
362        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
363          Ctx.getFloatTypeSemantics(ToType),
364          llvm::APFloat::rmNearestTiesToEven, &ignored);
365        // If there was no overflow, the source value is within the range of
366        // values that can be represented.
367        if (ConvertStatus & llvm::APFloat::opOverflow) {
368          ConstantType = Initializer->getType();
369          return NK_Constant_Narrowing;
370        }
371      } else {
372        return NK_Variable_Narrowing;
373      }
374    }
375    return NK_Not_Narrowing;
376
377  // -- from an integer type or unscoped enumeration type to an integer type
378  //    that cannot represent all the values of the original type, except where
379  //    the source is a constant expression and the actual value after
380  //    conversion will fit into the target type and will produce the original
381  //    value when converted back to the original type.
382  case ICK_Boolean_Conversion:  // Bools are integers too.
383    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
384      // Boolean conversions can be from pointers and pointers to members
385      // [conv.bool], and those aren't considered narrowing conversions.
386      return NK_Not_Narrowing;
387    }  // Otherwise, fall through to the integral case.
388  case ICK_Integral_Conversion: {
389    assert(FromType->isIntegralOrUnscopedEnumerationType());
390    assert(ToType->isIntegralOrUnscopedEnumerationType());
391    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
392    const unsigned FromWidth = Ctx.getIntWidth(FromType);
393    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
394    const unsigned ToWidth = Ctx.getIntWidth(ToType);
395
396    if (FromWidth > ToWidth ||
397        (FromWidth == ToWidth && FromSigned != ToSigned) ||
398        (FromSigned && !ToSigned)) {
399      // Not all values of FromType can be represented in ToType.
400      llvm::APSInt InitializerValue;
401      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
402      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
403        // Such conversions on variables are always narrowing.
404        return NK_Variable_Narrowing;
405      }
406      bool Narrowing = false;
407      if (FromWidth < ToWidth) {
408        // Negative -> unsigned is narrowing. Otherwise, more bits is never
409        // narrowing.
410        if (InitializerValue.isSigned() && InitializerValue.isNegative())
411          Narrowing = true;
412      } else {
413        // Add a bit to the InitializerValue so we don't have to worry about
414        // signed vs. unsigned comparisons.
415        InitializerValue = InitializerValue.extend(
416          InitializerValue.getBitWidth() + 1);
417        // Convert the initializer to and from the target width and signed-ness.
418        llvm::APSInt ConvertedValue = InitializerValue;
419        ConvertedValue = ConvertedValue.trunc(ToWidth);
420        ConvertedValue.setIsSigned(ToSigned);
421        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
422        ConvertedValue.setIsSigned(InitializerValue.isSigned());
423        // If the result is different, this was a narrowing conversion.
424        if (ConvertedValue != InitializerValue)
425          Narrowing = true;
426      }
427      if (Narrowing) {
428        ConstantType = Initializer->getType();
429        ConstantValue = APValue(InitializerValue);
430        return NK_Constant_Narrowing;
431      }
432    }
433    return NK_Not_Narrowing;
434  }
435
436  default:
437    // Other kinds of conversions are not narrowings.
438    return NK_Not_Narrowing;
439  }
440}
441
442/// DebugPrint - Print this standard conversion sequence to standard
443/// error. Useful for debugging overloading issues.
444void StandardConversionSequence::DebugPrint() const {
445  raw_ostream &OS = llvm::errs();
446  bool PrintedSomething = false;
447  if (First != ICK_Identity) {
448    OS << GetImplicitConversionName(First);
449    PrintedSomething = true;
450  }
451
452  if (Second != ICK_Identity) {
453    if (PrintedSomething) {
454      OS << " -> ";
455    }
456    OS << GetImplicitConversionName(Second);
457
458    if (CopyConstructor) {
459      OS << " (by copy constructor)";
460    } else if (DirectBinding) {
461      OS << " (direct reference binding)";
462    } else if (ReferenceBinding) {
463      OS << " (reference binding)";
464    }
465    PrintedSomething = true;
466  }
467
468  if (Third != ICK_Identity) {
469    if (PrintedSomething) {
470      OS << " -> ";
471    }
472    OS << GetImplicitConversionName(Third);
473    PrintedSomething = true;
474  }
475
476  if (!PrintedSomething) {
477    OS << "No conversions required";
478  }
479}
480
481/// DebugPrint - Print this user-defined conversion sequence to standard
482/// error. Useful for debugging overloading issues.
483void UserDefinedConversionSequence::DebugPrint() const {
484  raw_ostream &OS = llvm::errs();
485  if (Before.First || Before.Second || Before.Third) {
486    Before.DebugPrint();
487    OS << " -> ";
488  }
489  if (ConversionFunction)
490    OS << '\'' << *ConversionFunction << '\'';
491  else
492    OS << "aggregate initialization";
493  if (After.First || After.Second || After.Third) {
494    OS << " -> ";
495    After.DebugPrint();
496  }
497}
498
499/// DebugPrint - Print this implicit conversion sequence to standard
500/// error. Useful for debugging overloading issues.
501void ImplicitConversionSequence::DebugPrint() const {
502  raw_ostream &OS = llvm::errs();
503  switch (ConversionKind) {
504  case StandardConversion:
505    OS << "Standard conversion: ";
506    Standard.DebugPrint();
507    break;
508  case UserDefinedConversion:
509    OS << "User-defined conversion: ";
510    UserDefined.DebugPrint();
511    break;
512  case EllipsisConversion:
513    OS << "Ellipsis conversion";
514    break;
515  case AmbiguousConversion:
516    OS << "Ambiguous conversion";
517    break;
518  case BadConversion:
519    OS << "Bad conversion";
520    break;
521  }
522
523  OS << "\n";
524}
525
526void AmbiguousConversionSequence::construct() {
527  new (&conversions()) ConversionSet();
528}
529
530void AmbiguousConversionSequence::destruct() {
531  conversions().~ConversionSet();
532}
533
534void
535AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
536  FromTypePtr = O.FromTypePtr;
537  ToTypePtr = O.ToTypePtr;
538  new (&conversions()) ConversionSet(O.conversions());
539}
540
541namespace {
542  // Structure used by OverloadCandidate::DeductionFailureInfo to store
543  // template argument information.
544  struct DFIArguments {
545    TemplateArgument FirstArg;
546    TemplateArgument SecondArg;
547  };
548  // Structure used by OverloadCandidate::DeductionFailureInfo to store
549  // template parameter and template argument information.
550  struct DFIParamWithArguments : DFIArguments {
551    TemplateParameter Param;
552  };
553}
554
555/// \brief Convert from Sema's representation of template deduction information
556/// to the form used in overload-candidate information.
557OverloadCandidate::DeductionFailureInfo
558static MakeDeductionFailureInfo(ASTContext &Context,
559                                Sema::TemplateDeductionResult TDK,
560                                TemplateDeductionInfo &Info) {
561  OverloadCandidate::DeductionFailureInfo Result;
562  Result.Result = static_cast<unsigned>(TDK);
563  Result.HasDiagnostic = false;
564  Result.Data = 0;
565  switch (TDK) {
566  case Sema::TDK_Success:
567  case Sema::TDK_Invalid:
568  case Sema::TDK_InstantiationDepth:
569  case Sema::TDK_TooManyArguments:
570  case Sema::TDK_TooFewArguments:
571    break;
572
573  case Sema::TDK_Incomplete:
574  case Sema::TDK_InvalidExplicitArguments:
575    Result.Data = Info.Param.getOpaqueValue();
576    break;
577
578  case Sema::TDK_NonDeducedMismatch: {
579    // FIXME: Should allocate from normal heap so that we can free this later.
580    DFIArguments *Saved = new (Context) DFIArguments;
581    Saved->FirstArg = Info.FirstArg;
582    Saved->SecondArg = Info.SecondArg;
583    Result.Data = Saved;
584    break;
585  }
586
587  case Sema::TDK_Inconsistent:
588  case Sema::TDK_Underqualified: {
589    // FIXME: Should allocate from normal heap so that we can free this later.
590    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
591    Saved->Param = Info.Param;
592    Saved->FirstArg = Info.FirstArg;
593    Saved->SecondArg = Info.SecondArg;
594    Result.Data = Saved;
595    break;
596  }
597
598  case Sema::TDK_SubstitutionFailure:
599    Result.Data = Info.take();
600    if (Info.hasSFINAEDiagnostic()) {
601      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
602          SourceLocation(), PartialDiagnostic::NullDiagnostic());
603      Info.takeSFINAEDiagnostic(*Diag);
604      Result.HasDiagnostic = true;
605    }
606    break;
607
608  case Sema::TDK_FailedOverloadResolution:
609    Result.Data = Info.Expression;
610    break;
611
612  case Sema::TDK_MiscellaneousDeductionFailure:
613    break;
614  }
615
616  return Result;
617}
618
619void OverloadCandidate::DeductionFailureInfo::Destroy() {
620  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
621  case Sema::TDK_Success:
622  case Sema::TDK_Invalid:
623  case Sema::TDK_InstantiationDepth:
624  case Sema::TDK_Incomplete:
625  case Sema::TDK_TooManyArguments:
626  case Sema::TDK_TooFewArguments:
627  case Sema::TDK_InvalidExplicitArguments:
628  case Sema::TDK_FailedOverloadResolution:
629    break;
630
631  case Sema::TDK_Inconsistent:
632  case Sema::TDK_Underqualified:
633  case Sema::TDK_NonDeducedMismatch:
634    // FIXME: Destroy the data?
635    Data = 0;
636    break;
637
638  case Sema::TDK_SubstitutionFailure:
639    // FIXME: Destroy the template argument list?
640    Data = 0;
641    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
642      Diag->~PartialDiagnosticAt();
643      HasDiagnostic = false;
644    }
645    break;
646
647  // Unhandled
648  case Sema::TDK_MiscellaneousDeductionFailure:
649    break;
650  }
651}
652
653PartialDiagnosticAt *
654OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
655  if (HasDiagnostic)
656    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
657  return 0;
658}
659
660TemplateParameter
661OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
662  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
663  case Sema::TDK_Success:
664  case Sema::TDK_Invalid:
665  case Sema::TDK_InstantiationDepth:
666  case Sema::TDK_TooManyArguments:
667  case Sema::TDK_TooFewArguments:
668  case Sema::TDK_SubstitutionFailure:
669  case Sema::TDK_NonDeducedMismatch:
670  case Sema::TDK_FailedOverloadResolution:
671    return TemplateParameter();
672
673  case Sema::TDK_Incomplete:
674  case Sema::TDK_InvalidExplicitArguments:
675    return TemplateParameter::getFromOpaqueValue(Data);
676
677  case Sema::TDK_Inconsistent:
678  case Sema::TDK_Underqualified:
679    return static_cast<DFIParamWithArguments*>(Data)->Param;
680
681  // Unhandled
682  case Sema::TDK_MiscellaneousDeductionFailure:
683    break;
684  }
685
686  return TemplateParameter();
687}
688
689TemplateArgumentList *
690OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
691  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
692  case Sema::TDK_Success:
693  case Sema::TDK_Invalid:
694  case Sema::TDK_InstantiationDepth:
695  case Sema::TDK_TooManyArguments:
696  case Sema::TDK_TooFewArguments:
697  case Sema::TDK_Incomplete:
698  case Sema::TDK_InvalidExplicitArguments:
699  case Sema::TDK_Inconsistent:
700  case Sema::TDK_Underqualified:
701  case Sema::TDK_NonDeducedMismatch:
702  case Sema::TDK_FailedOverloadResolution:
703    return 0;
704
705  case Sema::TDK_SubstitutionFailure:
706    return static_cast<TemplateArgumentList*>(Data);
707
708  // Unhandled
709  case Sema::TDK_MiscellaneousDeductionFailure:
710    break;
711  }
712
713  return 0;
714}
715
716const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
717  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
718  case Sema::TDK_Success:
719  case Sema::TDK_Invalid:
720  case Sema::TDK_InstantiationDepth:
721  case Sema::TDK_Incomplete:
722  case Sema::TDK_TooManyArguments:
723  case Sema::TDK_TooFewArguments:
724  case Sema::TDK_InvalidExplicitArguments:
725  case Sema::TDK_SubstitutionFailure:
726  case Sema::TDK_FailedOverloadResolution:
727    return 0;
728
729  case Sema::TDK_Inconsistent:
730  case Sema::TDK_Underqualified:
731  case Sema::TDK_NonDeducedMismatch:
732    return &static_cast<DFIArguments*>(Data)->FirstArg;
733
734  // Unhandled
735  case Sema::TDK_MiscellaneousDeductionFailure:
736    break;
737  }
738
739  return 0;
740}
741
742const TemplateArgument *
743OverloadCandidate::DeductionFailureInfo::getSecondArg() {
744  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745  case Sema::TDK_Success:
746  case Sema::TDK_Invalid:
747  case Sema::TDK_InstantiationDepth:
748  case Sema::TDK_Incomplete:
749  case Sema::TDK_TooManyArguments:
750  case Sema::TDK_TooFewArguments:
751  case Sema::TDK_InvalidExplicitArguments:
752  case Sema::TDK_SubstitutionFailure:
753  case Sema::TDK_FailedOverloadResolution:
754    return 0;
755
756  case Sema::TDK_Inconsistent:
757  case Sema::TDK_Underqualified:
758  case Sema::TDK_NonDeducedMismatch:
759    return &static_cast<DFIArguments*>(Data)->SecondArg;
760
761  // Unhandled
762  case Sema::TDK_MiscellaneousDeductionFailure:
763    break;
764  }
765
766  return 0;
767}
768
769Expr *
770OverloadCandidate::DeductionFailureInfo::getExpr() {
771  if (static_cast<Sema::TemplateDeductionResult>(Result) ==
772        Sema::TDK_FailedOverloadResolution)
773    return static_cast<Expr*>(Data);
774
775  return 0;
776}
777
778void OverloadCandidateSet::destroyCandidates() {
779  for (iterator i = begin(), e = end(); i != e; ++i) {
780    for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
781      i->Conversions[ii].~ImplicitConversionSequence();
782    if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
783      i->DeductionFailure.Destroy();
784  }
785}
786
787void OverloadCandidateSet::clear() {
788  destroyCandidates();
789  NumInlineSequences = 0;
790  Candidates.clear();
791  Functions.clear();
792}
793
794namespace {
795  class UnbridgedCastsSet {
796    struct Entry {
797      Expr **Addr;
798      Expr *Saved;
799    };
800    SmallVector<Entry, 2> Entries;
801
802  public:
803    void save(Sema &S, Expr *&E) {
804      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
805      Entry entry = { &E, E };
806      Entries.push_back(entry);
807      E = S.stripARCUnbridgedCast(E);
808    }
809
810    void restore() {
811      for (SmallVectorImpl<Entry>::iterator
812             i = Entries.begin(), e = Entries.end(); i != e; ++i)
813        *i->Addr = i->Saved;
814    }
815  };
816}
817
818/// checkPlaceholderForOverload - Do any interesting placeholder-like
819/// preprocessing on the given expression.
820///
821/// \param unbridgedCasts a collection to which to add unbridged casts;
822///   without this, they will be immediately diagnosed as errors
823///
824/// Return true on unrecoverable error.
825static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
826                                        UnbridgedCastsSet *unbridgedCasts = 0) {
827  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
828    // We can't handle overloaded expressions here because overload
829    // resolution might reasonably tweak them.
830    if (placeholder->getKind() == BuiltinType::Overload) return false;
831
832    // If the context potentially accepts unbridged ARC casts, strip
833    // the unbridged cast and add it to the collection for later restoration.
834    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
835        unbridgedCasts) {
836      unbridgedCasts->save(S, E);
837      return false;
838    }
839
840    // Go ahead and check everything else.
841    ExprResult result = S.CheckPlaceholderExpr(E);
842    if (result.isInvalid())
843      return true;
844
845    E = result.take();
846    return false;
847  }
848
849  // Nothing to do.
850  return false;
851}
852
853/// checkArgPlaceholdersForOverload - Check a set of call operands for
854/// placeholders.
855static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
856                                            unsigned numArgs,
857                                            UnbridgedCastsSet &unbridged) {
858  for (unsigned i = 0; i != numArgs; ++i)
859    if (checkPlaceholderForOverload(S, args[i], &unbridged))
860      return true;
861
862  return false;
863}
864
865// IsOverload - Determine whether the given New declaration is an
866// overload of the declarations in Old. This routine returns false if
867// New and Old cannot be overloaded, e.g., if New has the same
868// signature as some function in Old (C++ 1.3.10) or if the Old
869// declarations aren't functions (or function templates) at all. When
870// it does return false, MatchedDecl will point to the decl that New
871// cannot be overloaded with.  This decl may be a UsingShadowDecl on
872// top of the underlying declaration.
873//
874// Example: Given the following input:
875//
876//   void f(int, float); // #1
877//   void f(int, int); // #2
878//   int f(int, int); // #3
879//
880// When we process #1, there is no previous declaration of "f",
881// so IsOverload will not be used.
882//
883// When we process #2, Old contains only the FunctionDecl for #1.  By
884// comparing the parameter types, we see that #1 and #2 are overloaded
885// (since they have different signatures), so this routine returns
886// false; MatchedDecl is unchanged.
887//
888// When we process #3, Old is an overload set containing #1 and #2. We
889// compare the signatures of #3 to #1 (they're overloaded, so we do
890// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
891// identical (return types of functions are not part of the
892// signature), IsOverload returns false and MatchedDecl will be set to
893// point to the FunctionDecl for #2.
894//
895// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
896// into a class by a using declaration.  The rules for whether to hide
897// shadow declarations ignore some properties which otherwise figure
898// into a function template's signature.
899Sema::OverloadKind
900Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
901                    NamedDecl *&Match, bool NewIsUsingDecl) {
902  for (LookupResult::iterator I = Old.begin(), E = Old.end();
903         I != E; ++I) {
904    NamedDecl *OldD = *I;
905
906    bool OldIsUsingDecl = false;
907    if (isa<UsingShadowDecl>(OldD)) {
908      OldIsUsingDecl = true;
909
910      // We can always introduce two using declarations into the same
911      // context, even if they have identical signatures.
912      if (NewIsUsingDecl) continue;
913
914      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
915    }
916
917    // If either declaration was introduced by a using declaration,
918    // we'll need to use slightly different rules for matching.
919    // Essentially, these rules are the normal rules, except that
920    // function templates hide function templates with different
921    // return types or template parameter lists.
922    bool UseMemberUsingDeclRules =
923      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
924
925    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
926      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
927        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
928          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
929          continue;
930        }
931
932        Match = *I;
933        return Ovl_Match;
934      }
935    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
936      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
937        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939          continue;
940        }
941
942        Match = *I;
943        return Ovl_Match;
944      }
945    } else if (isa<UsingDecl>(OldD)) {
946      // We can overload with these, which can show up when doing
947      // redeclaration checks for UsingDecls.
948      assert(Old.getLookupKind() == LookupUsingDeclName);
949    } else if (isa<TagDecl>(OldD)) {
950      // We can always overload with tags by hiding them.
951    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
952      // Optimistically assume that an unresolved using decl will
953      // overload; if it doesn't, we'll have to diagnose during
954      // template instantiation.
955    } else {
956      // (C++ 13p1):
957      //   Only function declarations can be overloaded; object and type
958      //   declarations cannot be overloaded.
959      Match = *I;
960      return Ovl_NonFunction;
961    }
962  }
963
964  return Ovl_Overload;
965}
966
967static bool canBeOverloaded(const FunctionDecl &D) {
968  if (D.getAttr<OverloadableAttr>())
969    return true;
970  if (D.isExternC())
971    return false;
972
973  // Main cannot be overloaded (basic.start.main).
974  if (D.isMain())
975    return false;
976
977  return true;
978}
979
980bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
981                      bool UseUsingDeclRules) {
982  // If both of the functions are extern "C", then they are not
983  // overloads.
984  if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
985    return false;
986
987  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
988  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
989
990  // C++ [temp.fct]p2:
991  //   A function template can be overloaded with other function templates
992  //   and with normal (non-template) functions.
993  if ((OldTemplate == 0) != (NewTemplate == 0))
994    return true;
995
996  // Is the function New an overload of the function Old?
997  QualType OldQType = Context.getCanonicalType(Old->getType());
998  QualType NewQType = Context.getCanonicalType(New->getType());
999
1000  // Compare the signatures (C++ 1.3.10) of the two functions to
1001  // determine whether they are overloads. If we find any mismatch
1002  // in the signature, they are overloads.
1003
1004  // If either of these functions is a K&R-style function (no
1005  // prototype), then we consider them to have matching signatures.
1006  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1007      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1008    return false;
1009
1010  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1011  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
1012
1013  // The signature of a function includes the types of its
1014  // parameters (C++ 1.3.10), which includes the presence or absence
1015  // of the ellipsis; see C++ DR 357).
1016  if (OldQType != NewQType &&
1017      (OldType->getNumArgs() != NewType->getNumArgs() ||
1018       OldType->isVariadic() != NewType->isVariadic() ||
1019       !FunctionArgTypesAreEqual(OldType, NewType)))
1020    return true;
1021
1022  // C++ [temp.over.link]p4:
1023  //   The signature of a function template consists of its function
1024  //   signature, its return type and its template parameter list. The names
1025  //   of the template parameters are significant only for establishing the
1026  //   relationship between the template parameters and the rest of the
1027  //   signature.
1028  //
1029  // We check the return type and template parameter lists for function
1030  // templates first; the remaining checks follow.
1031  //
1032  // However, we don't consider either of these when deciding whether
1033  // a member introduced by a shadow declaration is hidden.
1034  if (!UseUsingDeclRules && NewTemplate &&
1035      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1036                                       OldTemplate->getTemplateParameters(),
1037                                       false, TPL_TemplateMatch) ||
1038       OldType->getResultType() != NewType->getResultType()))
1039    return true;
1040
1041  // If the function is a class member, its signature includes the
1042  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1043  //
1044  // As part of this, also check whether one of the member functions
1045  // is static, in which case they are not overloads (C++
1046  // 13.1p2). While not part of the definition of the signature,
1047  // this check is important to determine whether these functions
1048  // can be overloaded.
1049  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1050  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1051  if (OldMethod && NewMethod &&
1052      !OldMethod->isStatic() && !NewMethod->isStatic()) {
1053    if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1054      if (!UseUsingDeclRules &&
1055          (OldMethod->getRefQualifier() == RQ_None ||
1056           NewMethod->getRefQualifier() == RQ_None)) {
1057        // C++0x [over.load]p2:
1058        //   - Member function declarations with the same name and the same
1059        //     parameter-type-list as well as member function template
1060        //     declarations with the same name, the same parameter-type-list, and
1061        //     the same template parameter lists cannot be overloaded if any of
1062        //     them, but not all, have a ref-qualifier (8.3.5).
1063        Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1064          << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1065        Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1066      }
1067      return true;
1068    }
1069
1070    // We may not have applied the implicit const for a constexpr member
1071    // function yet (because we haven't yet resolved whether this is a static
1072    // or non-static member function). Add it now, on the assumption that this
1073    // is a redeclaration of OldMethod.
1074    unsigned NewQuals = NewMethod->getTypeQualifiers();
1075    if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
1076      NewQuals |= Qualifiers::Const;
1077    if (OldMethod->getTypeQualifiers() != NewQuals)
1078      return true;
1079  }
1080
1081  // The signatures match; this is not an overload.
1082  return false;
1083}
1084
1085/// \brief Checks availability of the function depending on the current
1086/// function context. Inside an unavailable function, unavailability is ignored.
1087///
1088/// \returns true if \arg FD is unavailable and current context is inside
1089/// an available function, false otherwise.
1090bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1091  return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1092}
1093
1094/// \brief Tries a user-defined conversion from From to ToType.
1095///
1096/// Produces an implicit conversion sequence for when a standard conversion
1097/// is not an option. See TryImplicitConversion for more information.
1098static ImplicitConversionSequence
1099TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1100                         bool SuppressUserConversions,
1101                         bool AllowExplicit,
1102                         bool InOverloadResolution,
1103                         bool CStyle,
1104                         bool AllowObjCWritebackConversion) {
1105  ImplicitConversionSequence ICS;
1106
1107  if (SuppressUserConversions) {
1108    // We're not in the case above, so there is no conversion that
1109    // we can perform.
1110    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1111    return ICS;
1112  }
1113
1114  // Attempt user-defined conversion.
1115  OverloadCandidateSet Conversions(From->getExprLoc());
1116  OverloadingResult UserDefResult
1117    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1118                              AllowExplicit);
1119
1120  if (UserDefResult == OR_Success) {
1121    ICS.setUserDefined();
1122    // C++ [over.ics.user]p4:
1123    //   A conversion of an expression of class type to the same class
1124    //   type is given Exact Match rank, and a conversion of an
1125    //   expression of class type to a base class of that type is
1126    //   given Conversion rank, in spite of the fact that a copy
1127    //   constructor (i.e., a user-defined conversion function) is
1128    //   called for those cases.
1129    if (CXXConstructorDecl *Constructor
1130          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1131      QualType FromCanon
1132        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1133      QualType ToCanon
1134        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1135      if (Constructor->isCopyConstructor() &&
1136          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1137        // Turn this into a "standard" conversion sequence, so that it
1138        // gets ranked with standard conversion sequences.
1139        ICS.setStandard();
1140        ICS.Standard.setAsIdentityConversion();
1141        ICS.Standard.setFromType(From->getType());
1142        ICS.Standard.setAllToTypes(ToType);
1143        ICS.Standard.CopyConstructor = Constructor;
1144        if (ToCanon != FromCanon)
1145          ICS.Standard.Second = ICK_Derived_To_Base;
1146      }
1147    }
1148
1149    // C++ [over.best.ics]p4:
1150    //   However, when considering the argument of a user-defined
1151    //   conversion function that is a candidate by 13.3.1.3 when
1152    //   invoked for the copying of the temporary in the second step
1153    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1154    //   13.3.1.6 in all cases, only standard conversion sequences and
1155    //   ellipsis conversion sequences are allowed.
1156    if (SuppressUserConversions && ICS.isUserDefined()) {
1157      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1158    }
1159  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1160    ICS.setAmbiguous();
1161    ICS.Ambiguous.setFromType(From->getType());
1162    ICS.Ambiguous.setToType(ToType);
1163    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1164         Cand != Conversions.end(); ++Cand)
1165      if (Cand->Viable)
1166        ICS.Ambiguous.addConversion(Cand->Function);
1167  } else {
1168    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1169  }
1170
1171  return ICS;
1172}
1173
1174/// TryImplicitConversion - Attempt to perform an implicit conversion
1175/// from the given expression (Expr) to the given type (ToType). This
1176/// function returns an implicit conversion sequence that can be used
1177/// to perform the initialization. Given
1178///
1179///   void f(float f);
1180///   void g(int i) { f(i); }
1181///
1182/// this routine would produce an implicit conversion sequence to
1183/// describe the initialization of f from i, which will be a standard
1184/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1185/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1186//
1187/// Note that this routine only determines how the conversion can be
1188/// performed; it does not actually perform the conversion. As such,
1189/// it will not produce any diagnostics if no conversion is available,
1190/// but will instead return an implicit conversion sequence of kind
1191/// "BadConversion".
1192///
1193/// If @p SuppressUserConversions, then user-defined conversions are
1194/// not permitted.
1195/// If @p AllowExplicit, then explicit user-defined conversions are
1196/// permitted.
1197///
1198/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1199/// writeback conversion, which allows __autoreleasing id* parameters to
1200/// be initialized with __strong id* or __weak id* arguments.
1201static ImplicitConversionSequence
1202TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1203                      bool SuppressUserConversions,
1204                      bool AllowExplicit,
1205                      bool InOverloadResolution,
1206                      bool CStyle,
1207                      bool AllowObjCWritebackConversion) {
1208  ImplicitConversionSequence ICS;
1209  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1210                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1211    ICS.setStandard();
1212    return ICS;
1213  }
1214
1215  if (!S.getLangOpts().CPlusPlus) {
1216    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1217    return ICS;
1218  }
1219
1220  // C++ [over.ics.user]p4:
1221  //   A conversion of an expression of class type to the same class
1222  //   type is given Exact Match rank, and a conversion of an
1223  //   expression of class type to a base class of that type is
1224  //   given Conversion rank, in spite of the fact that a copy/move
1225  //   constructor (i.e., a user-defined conversion function) is
1226  //   called for those cases.
1227  QualType FromType = From->getType();
1228  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1229      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1230       S.IsDerivedFrom(FromType, ToType))) {
1231    ICS.setStandard();
1232    ICS.Standard.setAsIdentityConversion();
1233    ICS.Standard.setFromType(FromType);
1234    ICS.Standard.setAllToTypes(ToType);
1235
1236    // We don't actually check at this point whether there is a valid
1237    // copy/move constructor, since overloading just assumes that it
1238    // exists. When we actually perform initialization, we'll find the
1239    // appropriate constructor to copy the returned object, if needed.
1240    ICS.Standard.CopyConstructor = 0;
1241
1242    // Determine whether this is considered a derived-to-base conversion.
1243    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1244      ICS.Standard.Second = ICK_Derived_To_Base;
1245
1246    return ICS;
1247  }
1248
1249  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1250                                  AllowExplicit, InOverloadResolution, CStyle,
1251                                  AllowObjCWritebackConversion);
1252}
1253
1254ImplicitConversionSequence
1255Sema::TryImplicitConversion(Expr *From, QualType ToType,
1256                            bool SuppressUserConversions,
1257                            bool AllowExplicit,
1258                            bool InOverloadResolution,
1259                            bool CStyle,
1260                            bool AllowObjCWritebackConversion) {
1261  return clang::TryImplicitConversion(*this, From, ToType,
1262                                      SuppressUserConversions, AllowExplicit,
1263                                      InOverloadResolution, CStyle,
1264                                      AllowObjCWritebackConversion);
1265}
1266
1267/// PerformImplicitConversion - Perform an implicit conversion of the
1268/// expression From to the type ToType. Returns the
1269/// converted expression. Flavor is the kind of conversion we're
1270/// performing, used in the error message. If @p AllowExplicit,
1271/// explicit user-defined conversions are permitted.
1272ExprResult
1273Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1274                                AssignmentAction Action, bool AllowExplicit) {
1275  ImplicitConversionSequence ICS;
1276  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1277}
1278
1279ExprResult
1280Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1281                                AssignmentAction Action, bool AllowExplicit,
1282                                ImplicitConversionSequence& ICS) {
1283  if (checkPlaceholderForOverload(*this, From))
1284    return ExprError();
1285
1286  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1287  bool AllowObjCWritebackConversion
1288    = getLangOpts().ObjCAutoRefCount &&
1289      (Action == AA_Passing || Action == AA_Sending);
1290
1291  ICS = clang::TryImplicitConversion(*this, From, ToType,
1292                                     /*SuppressUserConversions=*/false,
1293                                     AllowExplicit,
1294                                     /*InOverloadResolution=*/false,
1295                                     /*CStyle=*/false,
1296                                     AllowObjCWritebackConversion);
1297  return PerformImplicitConversion(From, ToType, ICS, Action);
1298}
1299
1300/// \brief Determine whether the conversion from FromType to ToType is a valid
1301/// conversion that strips "noreturn" off the nested function type.
1302bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1303                                QualType &ResultTy) {
1304  if (Context.hasSameUnqualifiedType(FromType, ToType))
1305    return false;
1306
1307  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1308  // where F adds one of the following at most once:
1309  //   - a pointer
1310  //   - a member pointer
1311  //   - a block pointer
1312  CanQualType CanTo = Context.getCanonicalType(ToType);
1313  CanQualType CanFrom = Context.getCanonicalType(FromType);
1314  Type::TypeClass TyClass = CanTo->getTypeClass();
1315  if (TyClass != CanFrom->getTypeClass()) return false;
1316  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1317    if (TyClass == Type::Pointer) {
1318      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1319      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1320    } else if (TyClass == Type::BlockPointer) {
1321      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1322      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1323    } else if (TyClass == Type::MemberPointer) {
1324      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1325      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1326    } else {
1327      return false;
1328    }
1329
1330    TyClass = CanTo->getTypeClass();
1331    if (TyClass != CanFrom->getTypeClass()) return false;
1332    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1333      return false;
1334  }
1335
1336  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1337  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1338  if (!EInfo.getNoReturn()) return false;
1339
1340  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1341  assert(QualType(FromFn, 0).isCanonical());
1342  if (QualType(FromFn, 0) != CanTo) return false;
1343
1344  ResultTy = ToType;
1345  return true;
1346}
1347
1348/// \brief Determine whether the conversion from FromType to ToType is a valid
1349/// vector conversion.
1350///
1351/// \param ICK Will be set to the vector conversion kind, if this is a vector
1352/// conversion.
1353static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1354                               QualType ToType, ImplicitConversionKind &ICK) {
1355  // We need at least one of these types to be a vector type to have a vector
1356  // conversion.
1357  if (!ToType->isVectorType() && !FromType->isVectorType())
1358    return false;
1359
1360  // Identical types require no conversions.
1361  if (Context.hasSameUnqualifiedType(FromType, ToType))
1362    return false;
1363
1364  // There are no conversions between extended vector types, only identity.
1365  if (ToType->isExtVectorType()) {
1366    // There are no conversions between extended vector types other than the
1367    // identity conversion.
1368    if (FromType->isExtVectorType())
1369      return false;
1370
1371    // Vector splat from any arithmetic type to a vector.
1372    if (FromType->isArithmeticType()) {
1373      ICK = ICK_Vector_Splat;
1374      return true;
1375    }
1376  }
1377
1378  // We can perform the conversion between vector types in the following cases:
1379  // 1)vector types are equivalent AltiVec and GCC vector types
1380  // 2)lax vector conversions are permitted and the vector types are of the
1381  //   same size
1382  if (ToType->isVectorType() && FromType->isVectorType()) {
1383    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1384        (Context.getLangOpts().LaxVectorConversions &&
1385         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1386      ICK = ICK_Vector_Conversion;
1387      return true;
1388    }
1389  }
1390
1391  return false;
1392}
1393
1394static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1395                                bool InOverloadResolution,
1396                                StandardConversionSequence &SCS,
1397                                bool CStyle);
1398
1399/// IsStandardConversion - Determines whether there is a standard
1400/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1401/// expression From to the type ToType. Standard conversion sequences
1402/// only consider non-class types; for conversions that involve class
1403/// types, use TryImplicitConversion. If a conversion exists, SCS will
1404/// contain the standard conversion sequence required to perform this
1405/// conversion and this routine will return true. Otherwise, this
1406/// routine will return false and the value of SCS is unspecified.
1407static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1408                                 bool InOverloadResolution,
1409                                 StandardConversionSequence &SCS,
1410                                 bool CStyle,
1411                                 bool AllowObjCWritebackConversion) {
1412  QualType FromType = From->getType();
1413
1414  // Standard conversions (C++ [conv])
1415  SCS.setAsIdentityConversion();
1416  SCS.DeprecatedStringLiteralToCharPtr = false;
1417  SCS.IncompatibleObjC = false;
1418  SCS.setFromType(FromType);
1419  SCS.CopyConstructor = 0;
1420
1421  // There are no standard conversions for class types in C++, so
1422  // abort early. When overloading in C, however, we do permit
1423  if (FromType->isRecordType() || ToType->isRecordType()) {
1424    if (S.getLangOpts().CPlusPlus)
1425      return false;
1426
1427    // When we're overloading in C, we allow, as standard conversions,
1428  }
1429
1430  // The first conversion can be an lvalue-to-rvalue conversion,
1431  // array-to-pointer conversion, or function-to-pointer conversion
1432  // (C++ 4p1).
1433
1434  if (FromType == S.Context.OverloadTy) {
1435    DeclAccessPair AccessPair;
1436    if (FunctionDecl *Fn
1437          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1438                                                 AccessPair)) {
1439      // We were able to resolve the address of the overloaded function,
1440      // so we can convert to the type of that function.
1441      FromType = Fn->getType();
1442
1443      // we can sometimes resolve &foo<int> regardless of ToType, so check
1444      // if the type matches (identity) or we are converting to bool
1445      if (!S.Context.hasSameUnqualifiedType(
1446                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1447        QualType resultTy;
1448        // if the function type matches except for [[noreturn]], it's ok
1449        if (!S.IsNoReturnConversion(FromType,
1450              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1451          // otherwise, only a boolean conversion is standard
1452          if (!ToType->isBooleanType())
1453            return false;
1454      }
1455
1456      // Check if the "from" expression is taking the address of an overloaded
1457      // function and recompute the FromType accordingly. Take advantage of the
1458      // fact that non-static member functions *must* have such an address-of
1459      // expression.
1460      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1461      if (Method && !Method->isStatic()) {
1462        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1463               "Non-unary operator on non-static member address");
1464        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1465               == UO_AddrOf &&
1466               "Non-address-of operator on non-static member address");
1467        const Type *ClassType
1468          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1469        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1470      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1471        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1472               UO_AddrOf &&
1473               "Non-address-of operator for overloaded function expression");
1474        FromType = S.Context.getPointerType(FromType);
1475      }
1476
1477      // Check that we've computed the proper type after overload resolution.
1478      assert(S.Context.hasSameType(
1479        FromType,
1480        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1481    } else {
1482      return false;
1483    }
1484  }
1485  // Lvalue-to-rvalue conversion (C++11 4.1):
1486  //   A glvalue (3.10) of a non-function, non-array type T can
1487  //   be converted to a prvalue.
1488  bool argIsLValue = From->isGLValue();
1489  if (argIsLValue &&
1490      !FromType->isFunctionType() && !FromType->isArrayType() &&
1491      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1492    SCS.First = ICK_Lvalue_To_Rvalue;
1493
1494    // C11 6.3.2.1p2:
1495    //   ... if the lvalue has atomic type, the value has the non-atomic version
1496    //   of the type of the lvalue ...
1497    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1498      FromType = Atomic->getValueType();
1499
1500    // If T is a non-class type, the type of the rvalue is the
1501    // cv-unqualified version of T. Otherwise, the type of the rvalue
1502    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1503    // just strip the qualifiers because they don't matter.
1504    FromType = FromType.getUnqualifiedType();
1505  } else if (FromType->isArrayType()) {
1506    // Array-to-pointer conversion (C++ 4.2)
1507    SCS.First = ICK_Array_To_Pointer;
1508
1509    // An lvalue or rvalue of type "array of N T" or "array of unknown
1510    // bound of T" can be converted to an rvalue of type "pointer to
1511    // T" (C++ 4.2p1).
1512    FromType = S.Context.getArrayDecayedType(FromType);
1513
1514    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1515      // This conversion is deprecated. (C++ D.4).
1516      SCS.DeprecatedStringLiteralToCharPtr = true;
1517
1518      // For the purpose of ranking in overload resolution
1519      // (13.3.3.1.1), this conversion is considered an
1520      // array-to-pointer conversion followed by a qualification
1521      // conversion (4.4). (C++ 4.2p2)
1522      SCS.Second = ICK_Identity;
1523      SCS.Third = ICK_Qualification;
1524      SCS.QualificationIncludesObjCLifetime = false;
1525      SCS.setAllToTypes(FromType);
1526      return true;
1527    }
1528  } else if (FromType->isFunctionType() && argIsLValue) {
1529    // Function-to-pointer conversion (C++ 4.3).
1530    SCS.First = ICK_Function_To_Pointer;
1531
1532    // An lvalue of function type T can be converted to an rvalue of
1533    // type "pointer to T." The result is a pointer to the
1534    // function. (C++ 4.3p1).
1535    FromType = S.Context.getPointerType(FromType);
1536  } else {
1537    // We don't require any conversions for the first step.
1538    SCS.First = ICK_Identity;
1539  }
1540  SCS.setToType(0, FromType);
1541
1542  // The second conversion can be an integral promotion, floating
1543  // point promotion, integral conversion, floating point conversion,
1544  // floating-integral conversion, pointer conversion,
1545  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1546  // For overloading in C, this can also be a "compatible-type"
1547  // conversion.
1548  bool IncompatibleObjC = false;
1549  ImplicitConversionKind SecondICK = ICK_Identity;
1550  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1551    // The unqualified versions of the types are the same: there's no
1552    // conversion to do.
1553    SCS.Second = ICK_Identity;
1554  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1555    // Integral promotion (C++ 4.5).
1556    SCS.Second = ICK_Integral_Promotion;
1557    FromType = ToType.getUnqualifiedType();
1558  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1559    // Floating point promotion (C++ 4.6).
1560    SCS.Second = ICK_Floating_Promotion;
1561    FromType = ToType.getUnqualifiedType();
1562  } else if (S.IsComplexPromotion(FromType, ToType)) {
1563    // Complex promotion (Clang extension)
1564    SCS.Second = ICK_Complex_Promotion;
1565    FromType = ToType.getUnqualifiedType();
1566  } else if (ToType->isBooleanType() &&
1567             (FromType->isArithmeticType() ||
1568              FromType->isAnyPointerType() ||
1569              FromType->isBlockPointerType() ||
1570              FromType->isMemberPointerType() ||
1571              FromType->isNullPtrType())) {
1572    // Boolean conversions (C++ 4.12).
1573    SCS.Second = ICK_Boolean_Conversion;
1574    FromType = S.Context.BoolTy;
1575  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1576             ToType->isIntegralType(S.Context)) {
1577    // Integral conversions (C++ 4.7).
1578    SCS.Second = ICK_Integral_Conversion;
1579    FromType = ToType.getUnqualifiedType();
1580  } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1581    // Complex conversions (C99 6.3.1.6)
1582    SCS.Second = ICK_Complex_Conversion;
1583    FromType = ToType.getUnqualifiedType();
1584  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1585             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1586    // Complex-real conversions (C99 6.3.1.7)
1587    SCS.Second = ICK_Complex_Real;
1588    FromType = ToType.getUnqualifiedType();
1589  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1590    // Floating point conversions (C++ 4.8).
1591    SCS.Second = ICK_Floating_Conversion;
1592    FromType = ToType.getUnqualifiedType();
1593  } else if ((FromType->isRealFloatingType() &&
1594              ToType->isIntegralType(S.Context)) ||
1595             (FromType->isIntegralOrUnscopedEnumerationType() &&
1596              ToType->isRealFloatingType())) {
1597    // Floating-integral conversions (C++ 4.9).
1598    SCS.Second = ICK_Floating_Integral;
1599    FromType = ToType.getUnqualifiedType();
1600  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1601    SCS.Second = ICK_Block_Pointer_Conversion;
1602  } else if (AllowObjCWritebackConversion &&
1603             S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1604    SCS.Second = ICK_Writeback_Conversion;
1605  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1606                                   FromType, IncompatibleObjC)) {
1607    // Pointer conversions (C++ 4.10).
1608    SCS.Second = ICK_Pointer_Conversion;
1609    SCS.IncompatibleObjC = IncompatibleObjC;
1610    FromType = FromType.getUnqualifiedType();
1611  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1612                                         InOverloadResolution, FromType)) {
1613    // Pointer to member conversions (4.11).
1614    SCS.Second = ICK_Pointer_Member;
1615  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1616    SCS.Second = SecondICK;
1617    FromType = ToType.getUnqualifiedType();
1618  } else if (!S.getLangOpts().CPlusPlus &&
1619             S.Context.typesAreCompatible(ToType, FromType)) {
1620    // Compatible conversions (Clang extension for C function overloading)
1621    SCS.Second = ICK_Compatible_Conversion;
1622    FromType = ToType.getUnqualifiedType();
1623  } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1624    // Treat a conversion that strips "noreturn" as an identity conversion.
1625    SCS.Second = ICK_NoReturn_Adjustment;
1626  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1627                                             InOverloadResolution,
1628                                             SCS, CStyle)) {
1629    SCS.Second = ICK_TransparentUnionConversion;
1630    FromType = ToType;
1631  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1632                                 CStyle)) {
1633    // tryAtomicConversion has updated the standard conversion sequence
1634    // appropriately.
1635    return true;
1636  } else if (ToType->isEventT() &&
1637             From->isIntegerConstantExpr(S.getASTContext()) &&
1638             (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1639    SCS.Second = ICK_Zero_Event_Conversion;
1640    FromType = ToType;
1641  } else {
1642    // No second conversion required.
1643    SCS.Second = ICK_Identity;
1644  }
1645  SCS.setToType(1, FromType);
1646
1647  QualType CanonFrom;
1648  QualType CanonTo;
1649  // The third conversion can be a qualification conversion (C++ 4p1).
1650  bool ObjCLifetimeConversion;
1651  if (S.IsQualificationConversion(FromType, ToType, CStyle,
1652                                  ObjCLifetimeConversion)) {
1653    SCS.Third = ICK_Qualification;
1654    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1655    FromType = ToType;
1656    CanonFrom = S.Context.getCanonicalType(FromType);
1657    CanonTo = S.Context.getCanonicalType(ToType);
1658  } else {
1659    // No conversion required
1660    SCS.Third = ICK_Identity;
1661
1662    // C++ [over.best.ics]p6:
1663    //   [...] Any difference in top-level cv-qualification is
1664    //   subsumed by the initialization itself and does not constitute
1665    //   a conversion. [...]
1666    CanonFrom = S.Context.getCanonicalType(FromType);
1667    CanonTo = S.Context.getCanonicalType(ToType);
1668    if (CanonFrom.getLocalUnqualifiedType()
1669                                       == CanonTo.getLocalUnqualifiedType() &&
1670        (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1671         || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1672         || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime()
1673         || (CanonFrom->isSamplerT() &&
1674           CanonFrom.getAddressSpace() != CanonTo.getAddressSpace()))) {
1675      FromType = ToType;
1676      CanonFrom = CanonTo;
1677    }
1678  }
1679  SCS.setToType(2, FromType);
1680
1681  // If we have not converted the argument type to the parameter type,
1682  // this is a bad conversion sequence.
1683  if (CanonFrom != CanonTo)
1684    return false;
1685
1686  return true;
1687}
1688
1689static bool
1690IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1691                                     QualType &ToType,
1692                                     bool InOverloadResolution,
1693                                     StandardConversionSequence &SCS,
1694                                     bool CStyle) {
1695
1696  const RecordType *UT = ToType->getAsUnionType();
1697  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1698    return false;
1699  // The field to initialize within the transparent union.
1700  RecordDecl *UD = UT->getDecl();
1701  // It's compatible if the expression matches any of the fields.
1702  for (RecordDecl::field_iterator it = UD->field_begin(),
1703       itend = UD->field_end();
1704       it != itend; ++it) {
1705    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1706                             CStyle, /*ObjCWritebackConversion=*/false)) {
1707      ToType = it->getType();
1708      return true;
1709    }
1710  }
1711  return false;
1712}
1713
1714/// IsIntegralPromotion - Determines whether the conversion from the
1715/// expression From (whose potentially-adjusted type is FromType) to
1716/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1717/// sets PromotedType to the promoted type.
1718bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1719  const BuiltinType *To = ToType->getAs<BuiltinType>();
1720  // All integers are built-in.
1721  if (!To) {
1722    return false;
1723  }
1724
1725  // An rvalue of type char, signed char, unsigned char, short int, or
1726  // unsigned short int can be converted to an rvalue of type int if
1727  // int can represent all the values of the source type; otherwise,
1728  // the source rvalue can be converted to an rvalue of type unsigned
1729  // int (C++ 4.5p1).
1730  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1731      !FromType->isEnumeralType()) {
1732    if (// We can promote any signed, promotable integer type to an int
1733        (FromType->isSignedIntegerType() ||
1734         // We can promote any unsigned integer type whose size is
1735         // less than int to an int.
1736         (!FromType->isSignedIntegerType() &&
1737          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1738      return To->getKind() == BuiltinType::Int;
1739    }
1740
1741    return To->getKind() == BuiltinType::UInt;
1742  }
1743
1744  // C++11 [conv.prom]p3:
1745  //   A prvalue of an unscoped enumeration type whose underlying type is not
1746  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1747  //   following types that can represent all the values of the enumeration
1748  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1749  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1750  //   long long int. If none of the types in that list can represent all the
1751  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1752  //   type can be converted to an rvalue a prvalue of the extended integer type
1753  //   with lowest integer conversion rank (4.13) greater than the rank of long
1754  //   long in which all the values of the enumeration can be represented. If
1755  //   there are two such extended types, the signed one is chosen.
1756  // C++11 [conv.prom]p4:
1757  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1758  //   can be converted to a prvalue of its underlying type. Moreover, if
1759  //   integral promotion can be applied to its underlying type, a prvalue of an
1760  //   unscoped enumeration type whose underlying type is fixed can also be
1761  //   converted to a prvalue of the promoted underlying type.
1762  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1763    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1764    // provided for a scoped enumeration.
1765    if (FromEnumType->getDecl()->isScoped())
1766      return false;
1767
1768    // We can perform an integral promotion to the underlying type of the enum,
1769    // even if that's not the promoted type.
1770    if (FromEnumType->getDecl()->isFixed()) {
1771      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1772      return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1773             IsIntegralPromotion(From, Underlying, ToType);
1774    }
1775
1776    // We have already pre-calculated the promotion type, so this is trivial.
1777    if (ToType->isIntegerType() &&
1778        !RequireCompleteType(From->getLocStart(), FromType, 0))
1779      return Context.hasSameUnqualifiedType(ToType,
1780                                FromEnumType->getDecl()->getPromotionType());
1781  }
1782
1783  // C++0x [conv.prom]p2:
1784  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1785  //   to an rvalue a prvalue of the first of the following types that can
1786  //   represent all the values of its underlying type: int, unsigned int,
1787  //   long int, unsigned long int, long long int, or unsigned long long int.
1788  //   If none of the types in that list can represent all the values of its
1789  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1790  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1791  //   type.
1792  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1793      ToType->isIntegerType()) {
1794    // Determine whether the type we're converting from is signed or
1795    // unsigned.
1796    bool FromIsSigned = FromType->isSignedIntegerType();
1797    uint64_t FromSize = Context.getTypeSize(FromType);
1798
1799    // The types we'll try to promote to, in the appropriate
1800    // order. Try each of these types.
1801    QualType PromoteTypes[6] = {
1802      Context.IntTy, Context.UnsignedIntTy,
1803      Context.LongTy, Context.UnsignedLongTy ,
1804      Context.LongLongTy, Context.UnsignedLongLongTy
1805    };
1806    for (int Idx = 0; Idx < 6; ++Idx) {
1807      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1808      if (FromSize < ToSize ||
1809          (FromSize == ToSize &&
1810           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1811        // We found the type that we can promote to. If this is the
1812        // type we wanted, we have a promotion. Otherwise, no
1813        // promotion.
1814        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1815      }
1816    }
1817  }
1818
1819  // An rvalue for an integral bit-field (9.6) can be converted to an
1820  // rvalue of type int if int can represent all the values of the
1821  // bit-field; otherwise, it can be converted to unsigned int if
1822  // unsigned int can represent all the values of the bit-field. If
1823  // the bit-field is larger yet, no integral promotion applies to
1824  // it. If the bit-field has an enumerated type, it is treated as any
1825  // other value of that type for promotion purposes (C++ 4.5p3).
1826  // FIXME: We should delay checking of bit-fields until we actually perform the
1827  // conversion.
1828  using llvm::APSInt;
1829  if (From)
1830    if (FieldDecl *MemberDecl = From->getBitField()) {
1831      APSInt BitWidth;
1832      if (FromType->isIntegralType(Context) &&
1833          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1834        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1835        ToSize = Context.getTypeSize(ToType);
1836
1837        // Are we promoting to an int from a bitfield that fits in an int?
1838        if (BitWidth < ToSize ||
1839            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1840          return To->getKind() == BuiltinType::Int;
1841        }
1842
1843        // Are we promoting to an unsigned int from an unsigned bitfield
1844        // that fits into an unsigned int?
1845        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1846          return To->getKind() == BuiltinType::UInt;
1847        }
1848
1849        return false;
1850      }
1851    }
1852
1853  // An rvalue of type bool can be converted to an rvalue of type int,
1854  // with false becoming zero and true becoming one (C++ 4.5p4).
1855  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1856    return true;
1857  }
1858
1859  return false;
1860}
1861
1862/// IsFloatingPointPromotion - Determines whether the conversion from
1863/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1864/// returns true and sets PromotedType to the promoted type.
1865bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1866  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1867    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1868      /// An rvalue of type float can be converted to an rvalue of type
1869      /// double. (C++ 4.6p1).
1870      if (FromBuiltin->getKind() == BuiltinType::Float &&
1871          ToBuiltin->getKind() == BuiltinType::Double)
1872        return true;
1873
1874      // C99 6.3.1.5p1:
1875      //   When a float is promoted to double or long double, or a
1876      //   double is promoted to long double [...].
1877      if (!getLangOpts().CPlusPlus &&
1878          (FromBuiltin->getKind() == BuiltinType::Float ||
1879           FromBuiltin->getKind() == BuiltinType::Double) &&
1880          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1881        return true;
1882
1883      // Half can be promoted to float.
1884      if (!getLangOpts().NativeHalfType &&
1885           FromBuiltin->getKind() == BuiltinType::Half &&
1886          ToBuiltin->getKind() == BuiltinType::Float)
1887        return true;
1888    }
1889
1890  return false;
1891}
1892
1893/// \brief Determine if a conversion is a complex promotion.
1894///
1895/// A complex promotion is defined as a complex -> complex conversion
1896/// where the conversion between the underlying real types is a
1897/// floating-point or integral promotion.
1898bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1899  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1900  if (!FromComplex)
1901    return false;
1902
1903  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1904  if (!ToComplex)
1905    return false;
1906
1907  return IsFloatingPointPromotion(FromComplex->getElementType(),
1908                                  ToComplex->getElementType()) ||
1909    IsIntegralPromotion(0, FromComplex->getElementType(),
1910                        ToComplex->getElementType());
1911}
1912
1913/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1914/// the pointer type FromPtr to a pointer to type ToPointee, with the
1915/// same type qualifiers as FromPtr has on its pointee type. ToType,
1916/// if non-empty, will be a pointer to ToType that may or may not have
1917/// the right set of qualifiers on its pointee.
1918///
1919static QualType
1920BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1921                                   QualType ToPointee, QualType ToType,
1922                                   ASTContext &Context,
1923                                   bool StripObjCLifetime = false) {
1924  assert((FromPtr->getTypeClass() == Type::Pointer ||
1925          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1926         "Invalid similarly-qualified pointer type");
1927
1928  /// Conversions to 'id' subsume cv-qualifier conversions.
1929  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1930    return ToType.getUnqualifiedType();
1931
1932  QualType CanonFromPointee
1933    = Context.getCanonicalType(FromPtr->getPointeeType());
1934  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1935  Qualifiers Quals = CanonFromPointee.getQualifiers();
1936
1937  if (StripObjCLifetime)
1938    Quals.removeObjCLifetime();
1939
1940  // Exact qualifier match -> return the pointer type we're converting to.
1941  if (CanonToPointee.getLocalQualifiers() == Quals) {
1942    // ToType is exactly what we need. Return it.
1943    if (!ToType.isNull())
1944      return ToType.getUnqualifiedType();
1945
1946    // Build a pointer to ToPointee. It has the right qualifiers
1947    // already.
1948    if (isa<ObjCObjectPointerType>(ToType))
1949      return Context.getObjCObjectPointerType(ToPointee);
1950    return Context.getPointerType(ToPointee);
1951  }
1952
1953  // Just build a canonical type that has the right qualifiers.
1954  QualType QualifiedCanonToPointee
1955    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1956
1957  if (isa<ObjCObjectPointerType>(ToType))
1958    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1959  return Context.getPointerType(QualifiedCanonToPointee);
1960}
1961
1962static bool isNullPointerConstantForConversion(Expr *Expr,
1963                                               bool InOverloadResolution,
1964                                               ASTContext &Context) {
1965  // Handle value-dependent integral null pointer constants correctly.
1966  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1967  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1968      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1969    return !InOverloadResolution;
1970
1971  return Expr->isNullPointerConstant(Context,
1972                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1973                                        : Expr::NPC_ValueDependentIsNull);
1974}
1975
1976/// IsPointerConversion - Determines whether the conversion of the
1977/// expression From, which has the (possibly adjusted) type FromType,
1978/// can be converted to the type ToType via a pointer conversion (C++
1979/// 4.10). If so, returns true and places the converted type (that
1980/// might differ from ToType in its cv-qualifiers at some level) into
1981/// ConvertedType.
1982///
1983/// This routine also supports conversions to and from block pointers
1984/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1985/// pointers to interfaces. FIXME: Once we've determined the
1986/// appropriate overloading rules for Objective-C, we may want to
1987/// split the Objective-C checks into a different routine; however,
1988/// GCC seems to consider all of these conversions to be pointer
1989/// conversions, so for now they live here. IncompatibleObjC will be
1990/// set if the conversion is an allowed Objective-C conversion that
1991/// should result in a warning.
1992bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1993                               bool InOverloadResolution,
1994                               QualType& ConvertedType,
1995                               bool &IncompatibleObjC) {
1996  IncompatibleObjC = false;
1997  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1998                              IncompatibleObjC))
1999    return true;
2000
2001  // Conversion from a null pointer constant to any Objective-C pointer type.
2002  if (ToType->isObjCObjectPointerType() &&
2003      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2004    ConvertedType = ToType;
2005    return true;
2006  }
2007
2008  // Blocks: Block pointers can be converted to void*.
2009  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2010      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2011    ConvertedType = ToType;
2012    return true;
2013  }
2014  // Blocks: A null pointer constant can be converted to a block
2015  // pointer type.
2016  if (ToType->isBlockPointerType() &&
2017      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2018    ConvertedType = ToType;
2019    return true;
2020  }
2021
2022  // If the left-hand-side is nullptr_t, the right side can be a null
2023  // pointer constant.
2024  if (ToType->isNullPtrType() &&
2025      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2026    ConvertedType = ToType;
2027    return true;
2028  }
2029
2030  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2031  if (!ToTypePtr)
2032    return false;
2033
2034  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2035  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2036    ConvertedType = ToType;
2037    return true;
2038  }
2039
2040  // Beyond this point, both types need to be pointers
2041  // , including objective-c pointers.
2042  QualType ToPointeeType = ToTypePtr->getPointeeType();
2043  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2044      !getLangOpts().ObjCAutoRefCount) {
2045    ConvertedType = BuildSimilarlyQualifiedPointerType(
2046                                      FromType->getAs<ObjCObjectPointerType>(),
2047                                                       ToPointeeType,
2048                                                       ToType, Context);
2049    return true;
2050  }
2051  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2052  if (!FromTypePtr)
2053    return false;
2054
2055  QualType FromPointeeType = FromTypePtr->getPointeeType();
2056
2057  // If the unqualified pointee types are the same, this can't be a
2058  // pointer conversion, so don't do all of the work below.
2059  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2060    return false;
2061
2062  // An rvalue of type "pointer to cv T," where T is an object type,
2063  // can be converted to an rvalue of type "pointer to cv void" (C++
2064  // 4.10p2).
2065  if (FromPointeeType->isIncompleteOrObjectType() &&
2066      ToPointeeType->isVoidType()) {
2067    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2068                                                       ToPointeeType,
2069                                                       ToType, Context,
2070                                                   /*StripObjCLifetime=*/true);
2071    return true;
2072  }
2073
2074  // MSVC allows implicit function to void* type conversion.
2075  if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2076      ToPointeeType->isVoidType()) {
2077    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2078                                                       ToPointeeType,
2079                                                       ToType, Context);
2080    return true;
2081  }
2082
2083  // When we're overloading in C, we allow a special kind of pointer
2084  // conversion for compatible-but-not-identical pointee types.
2085  if (!getLangOpts().CPlusPlus &&
2086      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2087    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2088                                                       ToPointeeType,
2089                                                       ToType, Context);
2090    return true;
2091  }
2092
2093  // C++ [conv.ptr]p3:
2094  //
2095  //   An rvalue of type "pointer to cv D," where D is a class type,
2096  //   can be converted to an rvalue of type "pointer to cv B," where
2097  //   B is a base class (clause 10) of D. If B is an inaccessible
2098  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2099  //   necessitates this conversion is ill-formed. The result of the
2100  //   conversion is a pointer to the base class sub-object of the
2101  //   derived class object. The null pointer value is converted to
2102  //   the null pointer value of the destination type.
2103  //
2104  // Note that we do not check for ambiguity or inaccessibility
2105  // here. That is handled by CheckPointerConversion.
2106  if (getLangOpts().CPlusPlus &&
2107      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2108      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2109      !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2110      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2111    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2112                                                       ToPointeeType,
2113                                                       ToType, Context);
2114    return true;
2115  }
2116
2117  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2118      Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2119    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2120                                                       ToPointeeType,
2121                                                       ToType, Context);
2122    return true;
2123  }
2124
2125  return false;
2126}
2127
2128/// \brief Adopt the given qualifiers for the given type.
2129static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2130  Qualifiers TQs = T.getQualifiers();
2131
2132  // Check whether qualifiers already match.
2133  if (TQs == Qs)
2134    return T;
2135
2136  if (Qs.compatiblyIncludes(TQs))
2137    return Context.getQualifiedType(T, Qs);
2138
2139  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2140}
2141
2142/// isObjCPointerConversion - Determines whether this is an
2143/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2144/// with the same arguments and return values.
2145bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2146                                   QualType& ConvertedType,
2147                                   bool &IncompatibleObjC) {
2148  if (!getLangOpts().ObjC1)
2149    return false;
2150
2151  // The set of qualifiers on the type we're converting from.
2152  Qualifiers FromQualifiers = FromType.getQualifiers();
2153
2154  // First, we handle all conversions on ObjC object pointer types.
2155  const ObjCObjectPointerType* ToObjCPtr =
2156    ToType->getAs<ObjCObjectPointerType>();
2157  const ObjCObjectPointerType *FromObjCPtr =
2158    FromType->getAs<ObjCObjectPointerType>();
2159
2160  if (ToObjCPtr && FromObjCPtr) {
2161    // If the pointee types are the same (ignoring qualifications),
2162    // then this is not a pointer conversion.
2163    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2164                                       FromObjCPtr->getPointeeType()))
2165      return false;
2166
2167    // Check for compatible
2168    // Objective C++: We're able to convert between "id" or "Class" and a
2169    // pointer to any interface (in both directions).
2170    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2171      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2172      return true;
2173    }
2174    // Conversions with Objective-C's id<...>.
2175    if ((FromObjCPtr->isObjCQualifiedIdType() ||
2176         ToObjCPtr->isObjCQualifiedIdType()) &&
2177        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2178                                                  /*compare=*/false)) {
2179      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2180      return true;
2181    }
2182    // Objective C++: We're able to convert from a pointer to an
2183    // interface to a pointer to a different interface.
2184    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2185      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2186      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2187      if (getLangOpts().CPlusPlus && LHS && RHS &&
2188          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2189                                                FromObjCPtr->getPointeeType()))
2190        return false;
2191      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2192                                                   ToObjCPtr->getPointeeType(),
2193                                                         ToType, Context);
2194      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2195      return true;
2196    }
2197
2198    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2199      // Okay: this is some kind of implicit downcast of Objective-C
2200      // interfaces, which is permitted. However, we're going to
2201      // complain about it.
2202      IncompatibleObjC = true;
2203      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2204                                                   ToObjCPtr->getPointeeType(),
2205                                                         ToType, Context);
2206      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2207      return true;
2208    }
2209  }
2210  // Beyond this point, both types need to be C pointers or block pointers.
2211  QualType ToPointeeType;
2212  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2213    ToPointeeType = ToCPtr->getPointeeType();
2214  else if (const BlockPointerType *ToBlockPtr =
2215            ToType->getAs<BlockPointerType>()) {
2216    // Objective C++: We're able to convert from a pointer to any object
2217    // to a block pointer type.
2218    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2219      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2220      return true;
2221    }
2222    ToPointeeType = ToBlockPtr->getPointeeType();
2223  }
2224  else if (FromType->getAs<BlockPointerType>() &&
2225           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2226    // Objective C++: We're able to convert from a block pointer type to a
2227    // pointer to any object.
2228    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2229    return true;
2230  }
2231  else
2232    return false;
2233
2234  QualType FromPointeeType;
2235  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2236    FromPointeeType = FromCPtr->getPointeeType();
2237  else if (const BlockPointerType *FromBlockPtr =
2238           FromType->getAs<BlockPointerType>())
2239    FromPointeeType = FromBlockPtr->getPointeeType();
2240  else
2241    return false;
2242
2243  // If we have pointers to pointers, recursively check whether this
2244  // is an Objective-C conversion.
2245  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2246      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2247                              IncompatibleObjC)) {
2248    // We always complain about this conversion.
2249    IncompatibleObjC = true;
2250    ConvertedType = Context.getPointerType(ConvertedType);
2251    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2252    return true;
2253  }
2254  // Allow conversion of pointee being objective-c pointer to another one;
2255  // as in I* to id.
2256  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2257      ToPointeeType->getAs<ObjCObjectPointerType>() &&
2258      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2259                              IncompatibleObjC)) {
2260
2261    ConvertedType = Context.getPointerType(ConvertedType);
2262    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2263    return true;
2264  }
2265
2266  // If we have pointers to functions or blocks, check whether the only
2267  // differences in the argument and result types are in Objective-C
2268  // pointer conversions. If so, we permit the conversion (but
2269  // complain about it).
2270  const FunctionProtoType *FromFunctionType
2271    = FromPointeeType->getAs<FunctionProtoType>();
2272  const FunctionProtoType *ToFunctionType
2273    = ToPointeeType->getAs<FunctionProtoType>();
2274  if (FromFunctionType && ToFunctionType) {
2275    // If the function types are exactly the same, this isn't an
2276    // Objective-C pointer conversion.
2277    if (Context.getCanonicalType(FromPointeeType)
2278          == Context.getCanonicalType(ToPointeeType))
2279      return false;
2280
2281    // Perform the quick checks that will tell us whether these
2282    // function types are obviously different.
2283    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2284        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2285        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2286      return false;
2287
2288    bool HasObjCConversion = false;
2289    if (Context.getCanonicalType(FromFunctionType->getResultType())
2290          == Context.getCanonicalType(ToFunctionType->getResultType())) {
2291      // Okay, the types match exactly. Nothing to do.
2292    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2293                                       ToFunctionType->getResultType(),
2294                                       ConvertedType, IncompatibleObjC)) {
2295      // Okay, we have an Objective-C pointer conversion.
2296      HasObjCConversion = true;
2297    } else {
2298      // Function types are too different. Abort.
2299      return false;
2300    }
2301
2302    // Check argument types.
2303    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2304         ArgIdx != NumArgs; ++ArgIdx) {
2305      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2306      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2307      if (Context.getCanonicalType(FromArgType)
2308            == Context.getCanonicalType(ToArgType)) {
2309        // Okay, the types match exactly. Nothing to do.
2310      } else if (isObjCPointerConversion(FromArgType, ToArgType,
2311                                         ConvertedType, IncompatibleObjC)) {
2312        // Okay, we have an Objective-C pointer conversion.
2313        HasObjCConversion = true;
2314      } else {
2315        // Argument types are too different. Abort.
2316        return false;
2317      }
2318    }
2319
2320    if (HasObjCConversion) {
2321      // We had an Objective-C conversion. Allow this pointer
2322      // conversion, but complain about it.
2323      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2324      IncompatibleObjC = true;
2325      return true;
2326    }
2327  }
2328
2329  return false;
2330}
2331
2332/// \brief Determine whether this is an Objective-C writeback conversion,
2333/// used for parameter passing when performing automatic reference counting.
2334///
2335/// \param FromType The type we're converting form.
2336///
2337/// \param ToType The type we're converting to.
2338///
2339/// \param ConvertedType The type that will be produced after applying
2340/// this conversion.
2341bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2342                                     QualType &ConvertedType) {
2343  if (!getLangOpts().ObjCAutoRefCount ||
2344      Context.hasSameUnqualifiedType(FromType, ToType))
2345    return false;
2346
2347  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2348  QualType ToPointee;
2349  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2350    ToPointee = ToPointer->getPointeeType();
2351  else
2352    return false;
2353
2354  Qualifiers ToQuals = ToPointee.getQualifiers();
2355  if (!ToPointee->isObjCLifetimeType() ||
2356      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2357      !ToQuals.withoutObjCLifetime().empty())
2358    return false;
2359
2360  // Argument must be a pointer to __strong to __weak.
2361  QualType FromPointee;
2362  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2363    FromPointee = FromPointer->getPointeeType();
2364  else
2365    return false;
2366
2367  Qualifiers FromQuals = FromPointee.getQualifiers();
2368  if (!FromPointee->isObjCLifetimeType() ||
2369      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2370       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2371    return false;
2372
2373  // Make sure that we have compatible qualifiers.
2374  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2375  if (!ToQuals.compatiblyIncludes(FromQuals))
2376    return false;
2377
2378  // Remove qualifiers from the pointee type we're converting from; they
2379  // aren't used in the compatibility check belong, and we'll be adding back
2380  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2381  FromPointee = FromPointee.getUnqualifiedType();
2382
2383  // The unqualified form of the pointee types must be compatible.
2384  ToPointee = ToPointee.getUnqualifiedType();
2385  bool IncompatibleObjC;
2386  if (Context.typesAreCompatible(FromPointee, ToPointee))
2387    FromPointee = ToPointee;
2388  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2389                                    IncompatibleObjC))
2390    return false;
2391
2392  /// \brief Construct the type we're converting to, which is a pointer to
2393  /// __autoreleasing pointee.
2394  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2395  ConvertedType = Context.getPointerType(FromPointee);
2396  return true;
2397}
2398
2399bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2400                                    QualType& ConvertedType) {
2401  QualType ToPointeeType;
2402  if (const BlockPointerType *ToBlockPtr =
2403        ToType->getAs<BlockPointerType>())
2404    ToPointeeType = ToBlockPtr->getPointeeType();
2405  else
2406    return false;
2407
2408  QualType FromPointeeType;
2409  if (const BlockPointerType *FromBlockPtr =
2410      FromType->getAs<BlockPointerType>())
2411    FromPointeeType = FromBlockPtr->getPointeeType();
2412  else
2413    return false;
2414  // We have pointer to blocks, check whether the only
2415  // differences in the argument and result types are in Objective-C
2416  // pointer conversions. If so, we permit the conversion.
2417
2418  const FunctionProtoType *FromFunctionType
2419    = FromPointeeType->getAs<FunctionProtoType>();
2420  const FunctionProtoType *ToFunctionType
2421    = ToPointeeType->getAs<FunctionProtoType>();
2422
2423  if (!FromFunctionType || !ToFunctionType)
2424    return false;
2425
2426  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2427    return true;
2428
2429  // Perform the quick checks that will tell us whether these
2430  // function types are obviously different.
2431  if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2432      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2433    return false;
2434
2435  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2436  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2437  if (FromEInfo != ToEInfo)
2438    return false;
2439
2440  bool IncompatibleObjC = false;
2441  if (Context.hasSameType(FromFunctionType->getResultType(),
2442                          ToFunctionType->getResultType())) {
2443    // Okay, the types match exactly. Nothing to do.
2444  } else {
2445    QualType RHS = FromFunctionType->getResultType();
2446    QualType LHS = ToFunctionType->getResultType();
2447    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2448        !RHS.hasQualifiers() && LHS.hasQualifiers())
2449       LHS = LHS.getUnqualifiedType();
2450
2451     if (Context.hasSameType(RHS,LHS)) {
2452       // OK exact match.
2453     } else if (isObjCPointerConversion(RHS, LHS,
2454                                        ConvertedType, IncompatibleObjC)) {
2455     if (IncompatibleObjC)
2456       return false;
2457     // Okay, we have an Objective-C pointer conversion.
2458     }
2459     else
2460       return false;
2461   }
2462
2463   // Check argument types.
2464   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2465        ArgIdx != NumArgs; ++ArgIdx) {
2466     IncompatibleObjC = false;
2467     QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2468     QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2469     if (Context.hasSameType(FromArgType, ToArgType)) {
2470       // Okay, the types match exactly. Nothing to do.
2471     } else if (isObjCPointerConversion(ToArgType, FromArgType,
2472                                        ConvertedType, IncompatibleObjC)) {
2473       if (IncompatibleObjC)
2474         return false;
2475       // Okay, we have an Objective-C pointer conversion.
2476     } else
2477       // Argument types are too different. Abort.
2478       return false;
2479   }
2480   if (LangOpts.ObjCAutoRefCount &&
2481       !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2482                                                    ToFunctionType))
2483     return false;
2484
2485   ConvertedType = ToType;
2486   return true;
2487}
2488
2489enum {
2490  ft_default,
2491  ft_different_class,
2492  ft_parameter_arity,
2493  ft_parameter_mismatch,
2494  ft_return_type,
2495  ft_qualifer_mismatch
2496};
2497
2498/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2499/// function types.  Catches different number of parameter, mismatch in
2500/// parameter types, and different return types.
2501void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2502                                      QualType FromType, QualType ToType) {
2503  // If either type is not valid, include no extra info.
2504  if (FromType.isNull() || ToType.isNull()) {
2505    PDiag << ft_default;
2506    return;
2507  }
2508
2509  // Get the function type from the pointers.
2510  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2511    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2512                            *ToMember = ToType->getAs<MemberPointerType>();
2513    if (FromMember->getClass() != ToMember->getClass()) {
2514      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2515            << QualType(FromMember->getClass(), 0);
2516      return;
2517    }
2518    FromType = FromMember->getPointeeType();
2519    ToType = ToMember->getPointeeType();
2520  }
2521
2522  if (FromType->isPointerType())
2523    FromType = FromType->getPointeeType();
2524  if (ToType->isPointerType())
2525    ToType = ToType->getPointeeType();
2526
2527  // Remove references.
2528  FromType = FromType.getNonReferenceType();
2529  ToType = ToType.getNonReferenceType();
2530
2531  // Don't print extra info for non-specialized template functions.
2532  if (FromType->isInstantiationDependentType() &&
2533      !FromType->getAs<TemplateSpecializationType>()) {
2534    PDiag << ft_default;
2535    return;
2536  }
2537
2538  // No extra info for same types.
2539  if (Context.hasSameType(FromType, ToType)) {
2540    PDiag << ft_default;
2541    return;
2542  }
2543
2544  const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2545                          *ToFunction = ToType->getAs<FunctionProtoType>();
2546
2547  // Both types need to be function types.
2548  if (!FromFunction || !ToFunction) {
2549    PDiag << ft_default;
2550    return;
2551  }
2552
2553  if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2554    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2555          << FromFunction->getNumArgs();
2556    return;
2557  }
2558
2559  // Handle different parameter types.
2560  unsigned ArgPos;
2561  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2562    PDiag << ft_parameter_mismatch << ArgPos + 1
2563          << ToFunction->getArgType(ArgPos)
2564          << FromFunction->getArgType(ArgPos);
2565    return;
2566  }
2567
2568  // Handle different return type.
2569  if (!Context.hasSameType(FromFunction->getResultType(),
2570                           ToFunction->getResultType())) {
2571    PDiag << ft_return_type << ToFunction->getResultType()
2572          << FromFunction->getResultType();
2573    return;
2574  }
2575
2576  unsigned FromQuals = FromFunction->getTypeQuals(),
2577           ToQuals = ToFunction->getTypeQuals();
2578  if (FromQuals != ToQuals) {
2579    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2580    return;
2581  }
2582
2583  // Unable to find a difference, so add no extra info.
2584  PDiag << ft_default;
2585}
2586
2587/// FunctionArgTypesAreEqual - This routine checks two function proto types
2588/// for equality of their argument types. Caller has already checked that
2589/// they have same number of arguments. This routine assumes that Objective-C
2590/// pointer types which only differ in their protocol qualifiers are equal.
2591/// If the parameters are different, ArgPos will have the parameter index
2592/// of the first different parameter.
2593bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2594                                    const FunctionProtoType *NewType,
2595                                    unsigned *ArgPos) {
2596  if (!getLangOpts().ObjC1) {
2597    for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2598         N = NewType->arg_type_begin(),
2599         E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2600      if (!Context.hasSameType(*O, *N)) {
2601        if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2602        return false;
2603      }
2604    }
2605    return true;
2606  }
2607
2608  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2609       N = NewType->arg_type_begin(),
2610       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2611    QualType ToType = (*O);
2612    QualType FromType = (*N);
2613    if (!Context.hasSameType(ToType, FromType)) {
2614      if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2615        if (const PointerType *PTFr = FromType->getAs<PointerType>())
2616          if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2617               PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2618              (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2619               PTFr->getPointeeType()->isObjCQualifiedClassType()))
2620            continue;
2621      }
2622      else if (const ObjCObjectPointerType *PTTo =
2623                 ToType->getAs<ObjCObjectPointerType>()) {
2624        if (const ObjCObjectPointerType *PTFr =
2625              FromType->getAs<ObjCObjectPointerType>())
2626          if (Context.hasSameUnqualifiedType(
2627                PTTo->getObjectType()->getBaseType(),
2628                PTFr->getObjectType()->getBaseType()))
2629            continue;
2630      }
2631      if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2632      return false;
2633    }
2634  }
2635  return true;
2636}
2637
2638/// CheckPointerConversion - Check the pointer conversion from the
2639/// expression From to the type ToType. This routine checks for
2640/// ambiguous or inaccessible derived-to-base pointer
2641/// conversions for which IsPointerConversion has already returned
2642/// true. It returns true and produces a diagnostic if there was an
2643/// error, or returns false otherwise.
2644bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2645                                  CastKind &Kind,
2646                                  CXXCastPath& BasePath,
2647                                  bool IgnoreBaseAccess) {
2648  QualType FromType = From->getType();
2649  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2650
2651  Kind = CK_BitCast;
2652
2653  if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2654      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2655      Expr::NPCK_ZeroExpression) {
2656    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2657      DiagRuntimeBehavior(From->getExprLoc(), From,
2658                          PDiag(diag::warn_impcast_bool_to_null_pointer)
2659                            << ToType << From->getSourceRange());
2660    else if (!isUnevaluatedContext())
2661      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2662        << ToType << From->getSourceRange();
2663  }
2664  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2665    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2666      QualType FromPointeeType = FromPtrType->getPointeeType(),
2667               ToPointeeType   = ToPtrType->getPointeeType();
2668
2669      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2670          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2671        // We must have a derived-to-base conversion. Check an
2672        // ambiguous or inaccessible conversion.
2673        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2674                                         From->getExprLoc(),
2675                                         From->getSourceRange(), &BasePath,
2676                                         IgnoreBaseAccess))
2677          return true;
2678
2679        // The conversion was successful.
2680        Kind = CK_DerivedToBase;
2681      }
2682    }
2683  } else if (const ObjCObjectPointerType *ToPtrType =
2684               ToType->getAs<ObjCObjectPointerType>()) {
2685    if (const ObjCObjectPointerType *FromPtrType =
2686          FromType->getAs<ObjCObjectPointerType>()) {
2687      // Objective-C++ conversions are always okay.
2688      // FIXME: We should have a different class of conversions for the
2689      // Objective-C++ implicit conversions.
2690      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2691        return false;
2692    } else if (FromType->isBlockPointerType()) {
2693      Kind = CK_BlockPointerToObjCPointerCast;
2694    } else {
2695      Kind = CK_CPointerToObjCPointerCast;
2696    }
2697  } else if (ToType->isBlockPointerType()) {
2698    if (!FromType->isBlockPointerType())
2699      Kind = CK_AnyPointerToBlockPointerCast;
2700  }
2701
2702  // We shouldn't fall into this case unless it's valid for other
2703  // reasons.
2704  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2705    Kind = CK_NullToPointer;
2706
2707  return false;
2708}
2709
2710/// IsMemberPointerConversion - Determines whether the conversion of the
2711/// expression From, which has the (possibly adjusted) type FromType, can be
2712/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2713/// If so, returns true and places the converted type (that might differ from
2714/// ToType in its cv-qualifiers at some level) into ConvertedType.
2715bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2716                                     QualType ToType,
2717                                     bool InOverloadResolution,
2718                                     QualType &ConvertedType) {
2719  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2720  if (!ToTypePtr)
2721    return false;
2722
2723  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2724  if (From->isNullPointerConstant(Context,
2725                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2726                                        : Expr::NPC_ValueDependentIsNull)) {
2727    ConvertedType = ToType;
2728    return true;
2729  }
2730
2731  // Otherwise, both types have to be member pointers.
2732  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2733  if (!FromTypePtr)
2734    return false;
2735
2736  // A pointer to member of B can be converted to a pointer to member of D,
2737  // where D is derived from B (C++ 4.11p2).
2738  QualType FromClass(FromTypePtr->getClass(), 0);
2739  QualType ToClass(ToTypePtr->getClass(), 0);
2740
2741  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2742      !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2743      IsDerivedFrom(ToClass, FromClass)) {
2744    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2745                                                 ToClass.getTypePtr());
2746    return true;
2747  }
2748
2749  return false;
2750}
2751
2752/// CheckMemberPointerConversion - Check the member pointer conversion from the
2753/// expression From to the type ToType. This routine checks for ambiguous or
2754/// virtual or inaccessible base-to-derived member pointer conversions
2755/// for which IsMemberPointerConversion has already returned true. It returns
2756/// true and produces a diagnostic if there was an error, or returns false
2757/// otherwise.
2758bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2759                                        CastKind &Kind,
2760                                        CXXCastPath &BasePath,
2761                                        bool IgnoreBaseAccess) {
2762  QualType FromType = From->getType();
2763  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2764  if (!FromPtrType) {
2765    // This must be a null pointer to member pointer conversion
2766    assert(From->isNullPointerConstant(Context,
2767                                       Expr::NPC_ValueDependentIsNull) &&
2768           "Expr must be null pointer constant!");
2769    Kind = CK_NullToMemberPointer;
2770    return false;
2771  }
2772
2773  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2774  assert(ToPtrType && "No member pointer cast has a target type "
2775                      "that is not a member pointer.");
2776
2777  QualType FromClass = QualType(FromPtrType->getClass(), 0);
2778  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2779
2780  // FIXME: What about dependent types?
2781  assert(FromClass->isRecordType() && "Pointer into non-class.");
2782  assert(ToClass->isRecordType() && "Pointer into non-class.");
2783
2784  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2785                     /*DetectVirtual=*/true);
2786  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2787  assert(DerivationOkay &&
2788         "Should not have been called if derivation isn't OK.");
2789  (void)DerivationOkay;
2790
2791  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2792                                  getUnqualifiedType())) {
2793    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2794    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2795      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2796    return true;
2797  }
2798
2799  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2800    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2801      << FromClass << ToClass << QualType(VBase, 0)
2802      << From->getSourceRange();
2803    return true;
2804  }
2805
2806  if (!IgnoreBaseAccess)
2807    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2808                         Paths.front(),
2809                         diag::err_downcast_from_inaccessible_base);
2810
2811  // Must be a base to derived member conversion.
2812  BuildBasePathArray(Paths, BasePath);
2813  Kind = CK_BaseToDerivedMemberPointer;
2814  return false;
2815}
2816
2817/// IsQualificationConversion - Determines whether the conversion from
2818/// an rvalue of type FromType to ToType is a qualification conversion
2819/// (C++ 4.4).
2820///
2821/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2822/// when the qualification conversion involves a change in the Objective-C
2823/// object lifetime.
2824bool
2825Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2826                                bool CStyle, bool &ObjCLifetimeConversion) {
2827  FromType = Context.getCanonicalType(FromType);
2828  ToType = Context.getCanonicalType(ToType);
2829  ObjCLifetimeConversion = false;
2830
2831  // If FromType and ToType are the same type, this is not a
2832  // qualification conversion.
2833  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2834    return false;
2835
2836  // (C++ 4.4p4):
2837  //   A conversion can add cv-qualifiers at levels other than the first
2838  //   in multi-level pointers, subject to the following rules: [...]
2839  bool PreviousToQualsIncludeConst = true;
2840  bool UnwrappedAnyPointer = false;
2841  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2842    // Within each iteration of the loop, we check the qualifiers to
2843    // determine if this still looks like a qualification
2844    // conversion. Then, if all is well, we unwrap one more level of
2845    // pointers or pointers-to-members and do it all again
2846    // until there are no more pointers or pointers-to-members left to
2847    // unwrap.
2848    UnwrappedAnyPointer = true;
2849
2850    Qualifiers FromQuals = FromType.getQualifiers();
2851    Qualifiers ToQuals = ToType.getQualifiers();
2852
2853    // Objective-C ARC:
2854    //   Check Objective-C lifetime conversions.
2855    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2856        UnwrappedAnyPointer) {
2857      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2858        ObjCLifetimeConversion = true;
2859        FromQuals.removeObjCLifetime();
2860        ToQuals.removeObjCLifetime();
2861      } else {
2862        // Qualification conversions cannot cast between different
2863        // Objective-C lifetime qualifiers.
2864        return false;
2865      }
2866    }
2867
2868    // Allow addition/removal of GC attributes but not changing GC attributes.
2869    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2870        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2871      FromQuals.removeObjCGCAttr();
2872      ToQuals.removeObjCGCAttr();
2873    }
2874
2875    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2876    //      2,j, and similarly for volatile.
2877    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2878      return false;
2879
2880    //   -- if the cv 1,j and cv 2,j are different, then const is in
2881    //      every cv for 0 < k < j.
2882    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2883        && !PreviousToQualsIncludeConst)
2884      return false;
2885
2886    // Keep track of whether all prior cv-qualifiers in the "to" type
2887    // include const.
2888    PreviousToQualsIncludeConst
2889      = PreviousToQualsIncludeConst && ToQuals.hasConst();
2890  }
2891
2892  // We are left with FromType and ToType being the pointee types
2893  // after unwrapping the original FromType and ToType the same number
2894  // of types. If we unwrapped any pointers, and if FromType and
2895  // ToType have the same unqualified type (since we checked
2896  // qualifiers above), then this is a qualification conversion.
2897  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2898}
2899
2900/// \brief - Determine whether this is a conversion from a scalar type to an
2901/// atomic type.
2902///
2903/// If successful, updates \c SCS's second and third steps in the conversion
2904/// sequence to finish the conversion.
2905static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2906                                bool InOverloadResolution,
2907                                StandardConversionSequence &SCS,
2908                                bool CStyle) {
2909  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2910  if (!ToAtomic)
2911    return false;
2912
2913  StandardConversionSequence InnerSCS;
2914  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2915                            InOverloadResolution, InnerSCS,
2916                            CStyle, /*AllowObjCWritebackConversion=*/false))
2917    return false;
2918
2919  SCS.Second = InnerSCS.Second;
2920  SCS.setToType(1, InnerSCS.getToType(1));
2921  SCS.Third = InnerSCS.Third;
2922  SCS.QualificationIncludesObjCLifetime
2923    = InnerSCS.QualificationIncludesObjCLifetime;
2924  SCS.setToType(2, InnerSCS.getToType(2));
2925  return true;
2926}
2927
2928static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2929                                              CXXConstructorDecl *Constructor,
2930                                              QualType Type) {
2931  const FunctionProtoType *CtorType =
2932      Constructor->getType()->getAs<FunctionProtoType>();
2933  if (CtorType->getNumArgs() > 0) {
2934    QualType FirstArg = CtorType->getArgType(0);
2935    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2936      return true;
2937  }
2938  return false;
2939}
2940
2941static OverloadingResult
2942IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2943                                       CXXRecordDecl *To,
2944                                       UserDefinedConversionSequence &User,
2945                                       OverloadCandidateSet &CandidateSet,
2946                                       bool AllowExplicit) {
2947  DeclContext::lookup_result R = S.LookupConstructors(To);
2948  for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2949       Con != ConEnd; ++Con) {
2950    NamedDecl *D = *Con;
2951    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2952
2953    // Find the constructor (which may be a template).
2954    CXXConstructorDecl *Constructor = 0;
2955    FunctionTemplateDecl *ConstructorTmpl
2956      = dyn_cast<FunctionTemplateDecl>(D);
2957    if (ConstructorTmpl)
2958      Constructor
2959        = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2960    else
2961      Constructor = cast<CXXConstructorDecl>(D);
2962
2963    bool Usable = !Constructor->isInvalidDecl() &&
2964                  S.isInitListConstructor(Constructor) &&
2965                  (AllowExplicit || !Constructor->isExplicit());
2966    if (Usable) {
2967      // If the first argument is (a reference to) the target type,
2968      // suppress conversions.
2969      bool SuppressUserConversions =
2970          isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2971      if (ConstructorTmpl)
2972        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2973                                       /*ExplicitArgs*/ 0,
2974                                       From, CandidateSet,
2975                                       SuppressUserConversions);
2976      else
2977        S.AddOverloadCandidate(Constructor, FoundDecl,
2978                               From, CandidateSet,
2979                               SuppressUserConversions);
2980    }
2981  }
2982
2983  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2984
2985  OverloadCandidateSet::iterator Best;
2986  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2987  case OR_Success: {
2988    // Record the standard conversion we used and the conversion function.
2989    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2990    QualType ThisType = Constructor->getThisType(S.Context);
2991    // Initializer lists don't have conversions as such.
2992    User.Before.setAsIdentityConversion();
2993    User.HadMultipleCandidates = HadMultipleCandidates;
2994    User.ConversionFunction = Constructor;
2995    User.FoundConversionFunction = Best->FoundDecl;
2996    User.After.setAsIdentityConversion();
2997    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2998    User.After.setAllToTypes(ToType);
2999    return OR_Success;
3000  }
3001
3002  case OR_No_Viable_Function:
3003    return OR_No_Viable_Function;
3004  case OR_Deleted:
3005    return OR_Deleted;
3006  case OR_Ambiguous:
3007    return OR_Ambiguous;
3008  }
3009
3010  llvm_unreachable("Invalid OverloadResult!");
3011}
3012
3013/// Determines whether there is a user-defined conversion sequence
3014/// (C++ [over.ics.user]) that converts expression From to the type
3015/// ToType. If such a conversion exists, User will contain the
3016/// user-defined conversion sequence that performs such a conversion
3017/// and this routine will return true. Otherwise, this routine returns
3018/// false and User is unspecified.
3019///
3020/// \param AllowExplicit  true if the conversion should consider C++0x
3021/// "explicit" conversion functions as well as non-explicit conversion
3022/// functions (C++0x [class.conv.fct]p2).
3023static OverloadingResult
3024IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3025                        UserDefinedConversionSequence &User,
3026                        OverloadCandidateSet &CandidateSet,
3027                        bool AllowExplicit) {
3028  // Whether we will only visit constructors.
3029  bool ConstructorsOnly = false;
3030
3031  // If the type we are conversion to is a class type, enumerate its
3032  // constructors.
3033  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3034    // C++ [over.match.ctor]p1:
3035    //   When objects of class type are direct-initialized (8.5), or
3036    //   copy-initialized from an expression of the same or a
3037    //   derived class type (8.5), overload resolution selects the
3038    //   constructor. [...] For copy-initialization, the candidate
3039    //   functions are all the converting constructors (12.3.1) of
3040    //   that class. The argument list is the expression-list within
3041    //   the parentheses of the initializer.
3042    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3043        (From->getType()->getAs<RecordType>() &&
3044         S.IsDerivedFrom(From->getType(), ToType)))
3045      ConstructorsOnly = true;
3046
3047    S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3048    // RequireCompleteType may have returned true due to some invalid decl
3049    // during template instantiation, but ToType may be complete enough now
3050    // to try to recover.
3051    if (ToType->isIncompleteType()) {
3052      // We're not going to find any constructors.
3053    } else if (CXXRecordDecl *ToRecordDecl
3054                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3055
3056      Expr **Args = &From;
3057      unsigned NumArgs = 1;
3058      bool ListInitializing = false;
3059      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3060        // But first, see if there is an init-list-contructor that will work.
3061        OverloadingResult Result = IsInitializerListConstructorConversion(
3062            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3063        if (Result != OR_No_Viable_Function)
3064          return Result;
3065        // Never mind.
3066        CandidateSet.clear();
3067
3068        // If we're list-initializing, we pass the individual elements as
3069        // arguments, not the entire list.
3070        Args = InitList->getInits();
3071        NumArgs = InitList->getNumInits();
3072        ListInitializing = true;
3073      }
3074
3075      DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3076      for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3077           Con != ConEnd; ++Con) {
3078        NamedDecl *D = *Con;
3079        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3080
3081        // Find the constructor (which may be a template).
3082        CXXConstructorDecl *Constructor = 0;
3083        FunctionTemplateDecl *ConstructorTmpl
3084          = dyn_cast<FunctionTemplateDecl>(D);
3085        if (ConstructorTmpl)
3086          Constructor
3087            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3088        else
3089          Constructor = cast<CXXConstructorDecl>(D);
3090
3091        bool Usable = !Constructor->isInvalidDecl();
3092        if (ListInitializing)
3093          Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3094        else
3095          Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3096        if (Usable) {
3097          bool SuppressUserConversions = !ConstructorsOnly;
3098          if (SuppressUserConversions && ListInitializing) {
3099            SuppressUserConversions = false;
3100            if (NumArgs == 1) {
3101              // If the first argument is (a reference to) the target type,
3102              // suppress conversions.
3103              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3104                                                S.Context, Constructor, ToType);
3105            }
3106          }
3107          if (ConstructorTmpl)
3108            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3109                                           /*ExplicitArgs*/ 0,
3110                                           llvm::makeArrayRef(Args, NumArgs),
3111                                           CandidateSet, SuppressUserConversions);
3112          else
3113            // Allow one user-defined conversion when user specifies a
3114            // From->ToType conversion via an static cast (c-style, etc).
3115            S.AddOverloadCandidate(Constructor, FoundDecl,
3116                                   llvm::makeArrayRef(Args, NumArgs),
3117                                   CandidateSet, SuppressUserConversions);
3118        }
3119      }
3120    }
3121  }
3122
3123  // Enumerate conversion functions, if we're allowed to.
3124  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3125  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3126    // No conversion functions from incomplete types.
3127  } else if (const RecordType *FromRecordType
3128                                   = From->getType()->getAs<RecordType>()) {
3129    if (CXXRecordDecl *FromRecordDecl
3130         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3131      // Add all of the conversion functions as candidates.
3132      std::pair<CXXRecordDecl::conversion_iterator,
3133                CXXRecordDecl::conversion_iterator>
3134        Conversions = FromRecordDecl->getVisibleConversionFunctions();
3135      for (CXXRecordDecl::conversion_iterator
3136             I = Conversions.first, E = Conversions.second; I != E; ++I) {
3137        DeclAccessPair FoundDecl = I.getPair();
3138        NamedDecl *D = FoundDecl.getDecl();
3139        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3140        if (isa<UsingShadowDecl>(D))
3141          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3142
3143        CXXConversionDecl *Conv;
3144        FunctionTemplateDecl *ConvTemplate;
3145        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3146          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3147        else
3148          Conv = cast<CXXConversionDecl>(D);
3149
3150        if (AllowExplicit || !Conv->isExplicit()) {
3151          if (ConvTemplate)
3152            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3153                                             ActingContext, From, ToType,
3154                                             CandidateSet);
3155          else
3156            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3157                                     From, ToType, CandidateSet);
3158        }
3159      }
3160    }
3161  }
3162
3163  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3164
3165  OverloadCandidateSet::iterator Best;
3166  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3167  case OR_Success:
3168    // Record the standard conversion we used and the conversion function.
3169    if (CXXConstructorDecl *Constructor
3170          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3171      // C++ [over.ics.user]p1:
3172      //   If the user-defined conversion is specified by a
3173      //   constructor (12.3.1), the initial standard conversion
3174      //   sequence converts the source type to the type required by
3175      //   the argument of the constructor.
3176      //
3177      QualType ThisType = Constructor->getThisType(S.Context);
3178      if (isa<InitListExpr>(From)) {
3179        // Initializer lists don't have conversions as such.
3180        User.Before.setAsIdentityConversion();
3181      } else {
3182        if (Best->Conversions[0].isEllipsis())
3183          User.EllipsisConversion = true;
3184        else {
3185          User.Before = Best->Conversions[0].Standard;
3186          User.EllipsisConversion = false;
3187        }
3188      }
3189      User.HadMultipleCandidates = HadMultipleCandidates;
3190      User.ConversionFunction = Constructor;
3191      User.FoundConversionFunction = Best->FoundDecl;
3192      User.After.setAsIdentityConversion();
3193      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3194      User.After.setAllToTypes(ToType);
3195      return OR_Success;
3196    }
3197    if (CXXConversionDecl *Conversion
3198                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3199      // C++ [over.ics.user]p1:
3200      //
3201      //   [...] If the user-defined conversion is specified by a
3202      //   conversion function (12.3.2), the initial standard
3203      //   conversion sequence converts the source type to the
3204      //   implicit object parameter of the conversion function.
3205      User.Before = Best->Conversions[0].Standard;
3206      User.HadMultipleCandidates = HadMultipleCandidates;
3207      User.ConversionFunction = Conversion;
3208      User.FoundConversionFunction = Best->FoundDecl;
3209      User.EllipsisConversion = false;
3210
3211      // C++ [over.ics.user]p2:
3212      //   The second standard conversion sequence converts the
3213      //   result of the user-defined conversion to the target type
3214      //   for the sequence. Since an implicit conversion sequence
3215      //   is an initialization, the special rules for
3216      //   initialization by user-defined conversion apply when
3217      //   selecting the best user-defined conversion for a
3218      //   user-defined conversion sequence (see 13.3.3 and
3219      //   13.3.3.1).
3220      User.After = Best->FinalConversion;
3221      return OR_Success;
3222    }
3223    llvm_unreachable("Not a constructor or conversion function?");
3224
3225  case OR_No_Viable_Function:
3226    return OR_No_Viable_Function;
3227  case OR_Deleted:
3228    // No conversion here! We're done.
3229    return OR_Deleted;
3230
3231  case OR_Ambiguous:
3232    return OR_Ambiguous;
3233  }
3234
3235  llvm_unreachable("Invalid OverloadResult!");
3236}
3237
3238bool
3239Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3240  ImplicitConversionSequence ICS;
3241  OverloadCandidateSet CandidateSet(From->getExprLoc());
3242  OverloadingResult OvResult =
3243    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3244                            CandidateSet, false);
3245  if (OvResult == OR_Ambiguous)
3246    Diag(From->getLocStart(),
3247         diag::err_typecheck_ambiguous_condition)
3248          << From->getType() << ToType << From->getSourceRange();
3249  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3250    Diag(From->getLocStart(),
3251         diag::err_typecheck_nonviable_condition)
3252    << From->getType() << ToType << From->getSourceRange();
3253  else
3254    return false;
3255  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3256  return true;
3257}
3258
3259/// \brief Compare the user-defined conversion functions or constructors
3260/// of two user-defined conversion sequences to determine whether any ordering
3261/// is possible.
3262static ImplicitConversionSequence::CompareKind
3263compareConversionFunctions(Sema &S,
3264                           FunctionDecl *Function1,
3265                           FunctionDecl *Function2) {
3266  if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3267    return ImplicitConversionSequence::Indistinguishable;
3268
3269  // Objective-C++:
3270  //   If both conversion functions are implicitly-declared conversions from
3271  //   a lambda closure type to a function pointer and a block pointer,
3272  //   respectively, always prefer the conversion to a function pointer,
3273  //   because the function pointer is more lightweight and is more likely
3274  //   to keep code working.
3275  CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3276  if (!Conv1)
3277    return ImplicitConversionSequence::Indistinguishable;
3278
3279  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3280  if (!Conv2)
3281    return ImplicitConversionSequence::Indistinguishable;
3282
3283  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3284    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3285    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3286    if (Block1 != Block2)
3287      return Block1? ImplicitConversionSequence::Worse
3288                   : ImplicitConversionSequence::Better;
3289  }
3290
3291  return ImplicitConversionSequence::Indistinguishable;
3292}
3293
3294/// CompareImplicitConversionSequences - Compare two implicit
3295/// conversion sequences to determine whether one is better than the
3296/// other or if they are indistinguishable (C++ 13.3.3.2).
3297static ImplicitConversionSequence::CompareKind
3298CompareImplicitConversionSequences(Sema &S,
3299                                   const ImplicitConversionSequence& ICS1,
3300                                   const ImplicitConversionSequence& ICS2)
3301{
3302  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3303  // conversion sequences (as defined in 13.3.3.1)
3304  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3305  //      conversion sequence than a user-defined conversion sequence or
3306  //      an ellipsis conversion sequence, and
3307  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3308  //      conversion sequence than an ellipsis conversion sequence
3309  //      (13.3.3.1.3).
3310  //
3311  // C++0x [over.best.ics]p10:
3312  //   For the purpose of ranking implicit conversion sequences as
3313  //   described in 13.3.3.2, the ambiguous conversion sequence is
3314  //   treated as a user-defined sequence that is indistinguishable
3315  //   from any other user-defined conversion sequence.
3316  if (ICS1.getKindRank() < ICS2.getKindRank())
3317    return ImplicitConversionSequence::Better;
3318  if (ICS2.getKindRank() < ICS1.getKindRank())
3319    return ImplicitConversionSequence::Worse;
3320
3321  // The following checks require both conversion sequences to be of
3322  // the same kind.
3323  if (ICS1.getKind() != ICS2.getKind())
3324    return ImplicitConversionSequence::Indistinguishable;
3325
3326  ImplicitConversionSequence::CompareKind Result =
3327      ImplicitConversionSequence::Indistinguishable;
3328
3329  // Two implicit conversion sequences of the same form are
3330  // indistinguishable conversion sequences unless one of the
3331  // following rules apply: (C++ 13.3.3.2p3):
3332  if (ICS1.isStandard())
3333    Result = CompareStandardConversionSequences(S,
3334                                                ICS1.Standard, ICS2.Standard);
3335  else if (ICS1.isUserDefined()) {
3336    // User-defined conversion sequence U1 is a better conversion
3337    // sequence than another user-defined conversion sequence U2 if
3338    // they contain the same user-defined conversion function or
3339    // constructor and if the second standard conversion sequence of
3340    // U1 is better than the second standard conversion sequence of
3341    // U2 (C++ 13.3.3.2p3).
3342    if (ICS1.UserDefined.ConversionFunction ==
3343          ICS2.UserDefined.ConversionFunction)
3344      Result = CompareStandardConversionSequences(S,
3345                                                  ICS1.UserDefined.After,
3346                                                  ICS2.UserDefined.After);
3347    else
3348      Result = compareConversionFunctions(S,
3349                                          ICS1.UserDefined.ConversionFunction,
3350                                          ICS2.UserDefined.ConversionFunction);
3351  }
3352
3353  // List-initialization sequence L1 is a better conversion sequence than
3354  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3355  // for some X and L2 does not.
3356  if (Result == ImplicitConversionSequence::Indistinguishable &&
3357      !ICS1.isBad() &&
3358      ICS1.isListInitializationSequence() &&
3359      ICS2.isListInitializationSequence()) {
3360    if (ICS1.isStdInitializerListElement() &&
3361        !ICS2.isStdInitializerListElement())
3362      return ImplicitConversionSequence::Better;
3363    if (!ICS1.isStdInitializerListElement() &&
3364        ICS2.isStdInitializerListElement())
3365      return ImplicitConversionSequence::Worse;
3366  }
3367
3368  return Result;
3369}
3370
3371static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3372  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3373    Qualifiers Quals;
3374    T1 = Context.getUnqualifiedArrayType(T1, Quals);
3375    T2 = Context.getUnqualifiedArrayType(T2, Quals);
3376  }
3377
3378  return Context.hasSameUnqualifiedType(T1, T2);
3379}
3380
3381// Per 13.3.3.2p3, compare the given standard conversion sequences to
3382// determine if one is a proper subset of the other.
3383static ImplicitConversionSequence::CompareKind
3384compareStandardConversionSubsets(ASTContext &Context,
3385                                 const StandardConversionSequence& SCS1,
3386                                 const StandardConversionSequence& SCS2) {
3387  ImplicitConversionSequence::CompareKind Result
3388    = ImplicitConversionSequence::Indistinguishable;
3389
3390  // the identity conversion sequence is considered to be a subsequence of
3391  // any non-identity conversion sequence
3392  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3393    return ImplicitConversionSequence::Better;
3394  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3395    return ImplicitConversionSequence::Worse;
3396
3397  if (SCS1.Second != SCS2.Second) {
3398    if (SCS1.Second == ICK_Identity)
3399      Result = ImplicitConversionSequence::Better;
3400    else if (SCS2.Second == ICK_Identity)
3401      Result = ImplicitConversionSequence::Worse;
3402    else
3403      return ImplicitConversionSequence::Indistinguishable;
3404  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3405    return ImplicitConversionSequence::Indistinguishable;
3406
3407  if (SCS1.Third == SCS2.Third) {
3408    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3409                             : ImplicitConversionSequence::Indistinguishable;
3410  }
3411
3412  if (SCS1.Third == ICK_Identity)
3413    return Result == ImplicitConversionSequence::Worse
3414             ? ImplicitConversionSequence::Indistinguishable
3415             : ImplicitConversionSequence::Better;
3416
3417  if (SCS2.Third == ICK_Identity)
3418    return Result == ImplicitConversionSequence::Better
3419             ? ImplicitConversionSequence::Indistinguishable
3420             : ImplicitConversionSequence::Worse;
3421
3422  return ImplicitConversionSequence::Indistinguishable;
3423}
3424
3425/// \brief Determine whether one of the given reference bindings is better
3426/// than the other based on what kind of bindings they are.
3427static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3428                                       const StandardConversionSequence &SCS2) {
3429  // C++0x [over.ics.rank]p3b4:
3430  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3431  //      implicit object parameter of a non-static member function declared
3432  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3433  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3434  //      lvalue reference to a function lvalue and S2 binds an rvalue
3435  //      reference*.
3436  //
3437  // FIXME: Rvalue references. We're going rogue with the above edits,
3438  // because the semantics in the current C++0x working paper (N3225 at the
3439  // time of this writing) break the standard definition of std::forward
3440  // and std::reference_wrapper when dealing with references to functions.
3441  // Proposed wording changes submitted to CWG for consideration.
3442  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3443      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3444    return false;
3445
3446  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3447          SCS2.IsLvalueReference) ||
3448         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3449          !SCS2.IsLvalueReference);
3450}
3451
3452/// CompareStandardConversionSequences - Compare two standard
3453/// conversion sequences to determine whether one is better than the
3454/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3455static ImplicitConversionSequence::CompareKind
3456CompareStandardConversionSequences(Sema &S,
3457                                   const StandardConversionSequence& SCS1,
3458                                   const StandardConversionSequence& SCS2)
3459{
3460  // Standard conversion sequence S1 is a better conversion sequence
3461  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3462
3463  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3464  //     sequences in the canonical form defined by 13.3.3.1.1,
3465  //     excluding any Lvalue Transformation; the identity conversion
3466  //     sequence is considered to be a subsequence of any
3467  //     non-identity conversion sequence) or, if not that,
3468  if (ImplicitConversionSequence::CompareKind CK
3469        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3470    return CK;
3471
3472  //  -- the rank of S1 is better than the rank of S2 (by the rules
3473  //     defined below), or, if not that,
3474  ImplicitConversionRank Rank1 = SCS1.getRank();
3475  ImplicitConversionRank Rank2 = SCS2.getRank();
3476  if (Rank1 < Rank2)
3477    return ImplicitConversionSequence::Better;
3478  else if (Rank2 < Rank1)
3479    return ImplicitConversionSequence::Worse;
3480
3481  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3482  // are indistinguishable unless one of the following rules
3483  // applies:
3484
3485  //   A conversion that is not a conversion of a pointer, or
3486  //   pointer to member, to bool is better than another conversion
3487  //   that is such a conversion.
3488  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3489    return SCS2.isPointerConversionToBool()
3490             ? ImplicitConversionSequence::Better
3491             : ImplicitConversionSequence::Worse;
3492
3493  // C++ [over.ics.rank]p4b2:
3494  //
3495  //   If class B is derived directly or indirectly from class A,
3496  //   conversion of B* to A* is better than conversion of B* to
3497  //   void*, and conversion of A* to void* is better than conversion
3498  //   of B* to void*.
3499  bool SCS1ConvertsToVoid
3500    = SCS1.isPointerConversionToVoidPointer(S.Context);
3501  bool SCS2ConvertsToVoid
3502    = SCS2.isPointerConversionToVoidPointer(S.Context);
3503  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3504    // Exactly one of the conversion sequences is a conversion to
3505    // a void pointer; it's the worse conversion.
3506    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3507                              : ImplicitConversionSequence::Worse;
3508  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3509    // Neither conversion sequence converts to a void pointer; compare
3510    // their derived-to-base conversions.
3511    if (ImplicitConversionSequence::CompareKind DerivedCK
3512          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3513      return DerivedCK;
3514  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3515             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3516    // Both conversion sequences are conversions to void
3517    // pointers. Compare the source types to determine if there's an
3518    // inheritance relationship in their sources.
3519    QualType FromType1 = SCS1.getFromType();
3520    QualType FromType2 = SCS2.getFromType();
3521
3522    // Adjust the types we're converting from via the array-to-pointer
3523    // conversion, if we need to.
3524    if (SCS1.First == ICK_Array_To_Pointer)
3525      FromType1 = S.Context.getArrayDecayedType(FromType1);
3526    if (SCS2.First == ICK_Array_To_Pointer)
3527      FromType2 = S.Context.getArrayDecayedType(FromType2);
3528
3529    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3530    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3531
3532    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3533      return ImplicitConversionSequence::Better;
3534    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3535      return ImplicitConversionSequence::Worse;
3536
3537    // Objective-C++: If one interface is more specific than the
3538    // other, it is the better one.
3539    const ObjCObjectPointerType* FromObjCPtr1
3540      = FromType1->getAs<ObjCObjectPointerType>();
3541    const ObjCObjectPointerType* FromObjCPtr2
3542      = FromType2->getAs<ObjCObjectPointerType>();
3543    if (FromObjCPtr1 && FromObjCPtr2) {
3544      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3545                                                          FromObjCPtr2);
3546      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3547                                                           FromObjCPtr1);
3548      if (AssignLeft != AssignRight) {
3549        return AssignLeft? ImplicitConversionSequence::Better
3550                         : ImplicitConversionSequence::Worse;
3551      }
3552    }
3553  }
3554
3555  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3556  // bullet 3).
3557  if (ImplicitConversionSequence::CompareKind QualCK
3558        = CompareQualificationConversions(S, SCS1, SCS2))
3559    return QualCK;
3560
3561  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3562    // Check for a better reference binding based on the kind of bindings.
3563    if (isBetterReferenceBindingKind(SCS1, SCS2))
3564      return ImplicitConversionSequence::Better;
3565    else if (isBetterReferenceBindingKind(SCS2, SCS1))
3566      return ImplicitConversionSequence::Worse;
3567
3568    // C++ [over.ics.rank]p3b4:
3569    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3570    //      which the references refer are the same type except for
3571    //      top-level cv-qualifiers, and the type to which the reference
3572    //      initialized by S2 refers is more cv-qualified than the type
3573    //      to which the reference initialized by S1 refers.
3574    QualType T1 = SCS1.getToType(2);
3575    QualType T2 = SCS2.getToType(2);
3576    T1 = S.Context.getCanonicalType(T1);
3577    T2 = S.Context.getCanonicalType(T2);
3578    Qualifiers T1Quals, T2Quals;
3579    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3580    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3581    if (UnqualT1 == UnqualT2) {
3582      // Objective-C++ ARC: If the references refer to objects with different
3583      // lifetimes, prefer bindings that don't change lifetime.
3584      if (SCS1.ObjCLifetimeConversionBinding !=
3585                                          SCS2.ObjCLifetimeConversionBinding) {
3586        return SCS1.ObjCLifetimeConversionBinding
3587                                           ? ImplicitConversionSequence::Worse
3588                                           : ImplicitConversionSequence::Better;
3589      }
3590
3591      // If the type is an array type, promote the element qualifiers to the
3592      // type for comparison.
3593      if (isa<ArrayType>(T1) && T1Quals)
3594        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3595      if (isa<ArrayType>(T2) && T2Quals)
3596        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3597      if (T2.isMoreQualifiedThan(T1))
3598        return ImplicitConversionSequence::Better;
3599      else if (T1.isMoreQualifiedThan(T2))
3600        return ImplicitConversionSequence::Worse;
3601    }
3602  }
3603
3604  // In Microsoft mode, prefer an integral conversion to a
3605  // floating-to-integral conversion if the integral conversion
3606  // is between types of the same size.
3607  // For example:
3608  // void f(float);
3609  // void f(int);
3610  // int main {
3611  //    long a;
3612  //    f(a);
3613  // }
3614  // Here, MSVC will call f(int) instead of generating a compile error
3615  // as clang will do in standard mode.
3616  if (S.getLangOpts().MicrosoftMode &&
3617      SCS1.Second == ICK_Integral_Conversion &&
3618      SCS2.Second == ICK_Floating_Integral &&
3619      S.Context.getTypeSize(SCS1.getFromType()) ==
3620      S.Context.getTypeSize(SCS1.getToType(2)))
3621    return ImplicitConversionSequence::Better;
3622
3623  return ImplicitConversionSequence::Indistinguishable;
3624}
3625
3626/// CompareQualificationConversions - Compares two standard conversion
3627/// sequences to determine whether they can be ranked based on their
3628/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3629ImplicitConversionSequence::CompareKind
3630CompareQualificationConversions(Sema &S,
3631                                const StandardConversionSequence& SCS1,
3632                                const StandardConversionSequence& SCS2) {
3633  // C++ 13.3.3.2p3:
3634  //  -- S1 and S2 differ only in their qualification conversion and
3635  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3636  //     cv-qualification signature of type T1 is a proper subset of
3637  //     the cv-qualification signature of type T2, and S1 is not the
3638  //     deprecated string literal array-to-pointer conversion (4.2).
3639  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3640      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3641    return ImplicitConversionSequence::Indistinguishable;
3642
3643  // FIXME: the example in the standard doesn't use a qualification
3644  // conversion (!)
3645  QualType T1 = SCS1.getToType(2);
3646  QualType T2 = SCS2.getToType(2);
3647  T1 = S.Context.getCanonicalType(T1);
3648  T2 = S.Context.getCanonicalType(T2);
3649  Qualifiers T1Quals, T2Quals;
3650  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3651  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3652
3653  // If the types are the same, we won't learn anything by unwrapped
3654  // them.
3655  if (UnqualT1 == UnqualT2)
3656    return ImplicitConversionSequence::Indistinguishable;
3657
3658  // If the type is an array type, promote the element qualifiers to the type
3659  // for comparison.
3660  if (isa<ArrayType>(T1) && T1Quals)
3661    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3662  if (isa<ArrayType>(T2) && T2Quals)
3663    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3664
3665  ImplicitConversionSequence::CompareKind Result
3666    = ImplicitConversionSequence::Indistinguishable;
3667
3668  // Objective-C++ ARC:
3669  //   Prefer qualification conversions not involving a change in lifetime
3670  //   to qualification conversions that do not change lifetime.
3671  if (SCS1.QualificationIncludesObjCLifetime !=
3672                                      SCS2.QualificationIncludesObjCLifetime) {
3673    Result = SCS1.QualificationIncludesObjCLifetime
3674               ? ImplicitConversionSequence::Worse
3675               : ImplicitConversionSequence::Better;
3676  }
3677
3678  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3679    // Within each iteration of the loop, we check the qualifiers to
3680    // determine if this still looks like a qualification
3681    // conversion. Then, if all is well, we unwrap one more level of
3682    // pointers or pointers-to-members and do it all again
3683    // until there are no more pointers or pointers-to-members left
3684    // to unwrap. This essentially mimics what
3685    // IsQualificationConversion does, but here we're checking for a
3686    // strict subset of qualifiers.
3687    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3688      // The qualifiers are the same, so this doesn't tell us anything
3689      // about how the sequences rank.
3690      ;
3691    else if (T2.isMoreQualifiedThan(T1)) {
3692      // T1 has fewer qualifiers, so it could be the better sequence.
3693      if (Result == ImplicitConversionSequence::Worse)
3694        // Neither has qualifiers that are a subset of the other's
3695        // qualifiers.
3696        return ImplicitConversionSequence::Indistinguishable;
3697
3698      Result = ImplicitConversionSequence::Better;
3699    } else if (T1.isMoreQualifiedThan(T2)) {
3700      // T2 has fewer qualifiers, so it could be the better sequence.
3701      if (Result == ImplicitConversionSequence::Better)
3702        // Neither has qualifiers that are a subset of the other's
3703        // qualifiers.
3704        return ImplicitConversionSequence::Indistinguishable;
3705
3706      Result = ImplicitConversionSequence::Worse;
3707    } else {
3708      // Qualifiers are disjoint.
3709      return ImplicitConversionSequence::Indistinguishable;
3710    }
3711
3712    // If the types after this point are equivalent, we're done.
3713    if (S.Context.hasSameUnqualifiedType(T1, T2))
3714      break;
3715  }
3716
3717  // Check that the winning standard conversion sequence isn't using
3718  // the deprecated string literal array to pointer conversion.
3719  switch (Result) {
3720  case ImplicitConversionSequence::Better:
3721    if (SCS1.DeprecatedStringLiteralToCharPtr)
3722      Result = ImplicitConversionSequence::Indistinguishable;
3723    break;
3724
3725  case ImplicitConversionSequence::Indistinguishable:
3726    break;
3727
3728  case ImplicitConversionSequence::Worse:
3729    if (SCS2.DeprecatedStringLiteralToCharPtr)
3730      Result = ImplicitConversionSequence::Indistinguishable;
3731    break;
3732  }
3733
3734  return Result;
3735}
3736
3737/// CompareDerivedToBaseConversions - Compares two standard conversion
3738/// sequences to determine whether they can be ranked based on their
3739/// various kinds of derived-to-base conversions (C++
3740/// [over.ics.rank]p4b3).  As part of these checks, we also look at
3741/// conversions between Objective-C interface types.
3742ImplicitConversionSequence::CompareKind
3743CompareDerivedToBaseConversions(Sema &S,
3744                                const StandardConversionSequence& SCS1,
3745                                const StandardConversionSequence& SCS2) {
3746  QualType FromType1 = SCS1.getFromType();
3747  QualType ToType1 = SCS1.getToType(1);
3748  QualType FromType2 = SCS2.getFromType();
3749  QualType ToType2 = SCS2.getToType(1);
3750
3751  // Adjust the types we're converting from via the array-to-pointer
3752  // conversion, if we need to.
3753  if (SCS1.First == ICK_Array_To_Pointer)
3754    FromType1 = S.Context.getArrayDecayedType(FromType1);
3755  if (SCS2.First == ICK_Array_To_Pointer)
3756    FromType2 = S.Context.getArrayDecayedType(FromType2);
3757
3758  // Canonicalize all of the types.
3759  FromType1 = S.Context.getCanonicalType(FromType1);
3760  ToType1 = S.Context.getCanonicalType(ToType1);
3761  FromType2 = S.Context.getCanonicalType(FromType2);
3762  ToType2 = S.Context.getCanonicalType(ToType2);
3763
3764  // C++ [over.ics.rank]p4b3:
3765  //
3766  //   If class B is derived directly or indirectly from class A and
3767  //   class C is derived directly or indirectly from B,
3768  //
3769  // Compare based on pointer conversions.
3770  if (SCS1.Second == ICK_Pointer_Conversion &&
3771      SCS2.Second == ICK_Pointer_Conversion &&
3772      /*FIXME: Remove if Objective-C id conversions get their own rank*/
3773      FromType1->isPointerType() && FromType2->isPointerType() &&
3774      ToType1->isPointerType() && ToType2->isPointerType()) {
3775    QualType FromPointee1
3776      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3777    QualType ToPointee1
3778      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3779    QualType FromPointee2
3780      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3781    QualType ToPointee2
3782      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3783
3784    //   -- conversion of C* to B* is better than conversion of C* to A*,
3785    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3786      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3787        return ImplicitConversionSequence::Better;
3788      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3789        return ImplicitConversionSequence::Worse;
3790    }
3791
3792    //   -- conversion of B* to A* is better than conversion of C* to A*,
3793    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3794      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3795        return ImplicitConversionSequence::Better;
3796      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3797        return ImplicitConversionSequence::Worse;
3798    }
3799  } else if (SCS1.Second == ICK_Pointer_Conversion &&
3800             SCS2.Second == ICK_Pointer_Conversion) {
3801    const ObjCObjectPointerType *FromPtr1
3802      = FromType1->getAs<ObjCObjectPointerType>();
3803    const ObjCObjectPointerType *FromPtr2
3804      = FromType2->getAs<ObjCObjectPointerType>();
3805    const ObjCObjectPointerType *ToPtr1
3806      = ToType1->getAs<ObjCObjectPointerType>();
3807    const ObjCObjectPointerType *ToPtr2
3808      = ToType2->getAs<ObjCObjectPointerType>();
3809
3810    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3811      // Apply the same conversion ranking rules for Objective-C pointer types
3812      // that we do for C++ pointers to class types. However, we employ the
3813      // Objective-C pseudo-subtyping relationship used for assignment of
3814      // Objective-C pointer types.
3815      bool FromAssignLeft
3816        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3817      bool FromAssignRight
3818        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3819      bool ToAssignLeft
3820        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3821      bool ToAssignRight
3822        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3823
3824      // A conversion to an a non-id object pointer type or qualified 'id'
3825      // type is better than a conversion to 'id'.
3826      if (ToPtr1->isObjCIdType() &&
3827          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3828        return ImplicitConversionSequence::Worse;
3829      if (ToPtr2->isObjCIdType() &&
3830          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3831        return ImplicitConversionSequence::Better;
3832
3833      // A conversion to a non-id object pointer type is better than a
3834      // conversion to a qualified 'id' type
3835      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3836        return ImplicitConversionSequence::Worse;
3837      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3838        return ImplicitConversionSequence::Better;
3839
3840      // A conversion to an a non-Class object pointer type or qualified 'Class'
3841      // type is better than a conversion to 'Class'.
3842      if (ToPtr1->isObjCClassType() &&
3843          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3844        return ImplicitConversionSequence::Worse;
3845      if (ToPtr2->isObjCClassType() &&
3846          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3847        return ImplicitConversionSequence::Better;
3848
3849      // A conversion to a non-Class object pointer type is better than a
3850      // conversion to a qualified 'Class' type.
3851      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3852        return ImplicitConversionSequence::Worse;
3853      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3854        return ImplicitConversionSequence::Better;
3855
3856      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3857      if (S.Context.hasSameType(FromType1, FromType2) &&
3858          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3859          (ToAssignLeft != ToAssignRight))
3860        return ToAssignLeft? ImplicitConversionSequence::Worse
3861                           : ImplicitConversionSequence::Better;
3862
3863      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3864      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3865          (FromAssignLeft != FromAssignRight))
3866        return FromAssignLeft? ImplicitConversionSequence::Better
3867        : ImplicitConversionSequence::Worse;
3868    }
3869  }
3870
3871  // Ranking of member-pointer types.
3872  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3873      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3874      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3875    const MemberPointerType * FromMemPointer1 =
3876                                        FromType1->getAs<MemberPointerType>();
3877    const MemberPointerType * ToMemPointer1 =
3878                                          ToType1->getAs<MemberPointerType>();
3879    const MemberPointerType * FromMemPointer2 =
3880                                          FromType2->getAs<MemberPointerType>();
3881    const MemberPointerType * ToMemPointer2 =
3882                                          ToType2->getAs<MemberPointerType>();
3883    const Type *FromPointeeType1 = FromMemPointer1->getClass();
3884    const Type *ToPointeeType1 = ToMemPointer1->getClass();
3885    const Type *FromPointeeType2 = FromMemPointer2->getClass();
3886    const Type *ToPointeeType2 = ToMemPointer2->getClass();
3887    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3888    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3889    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3890    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3891    // conversion of A::* to B::* is better than conversion of A::* to C::*,
3892    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3893      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3894        return ImplicitConversionSequence::Worse;
3895      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3896        return ImplicitConversionSequence::Better;
3897    }
3898    // conversion of B::* to C::* is better than conversion of A::* to C::*
3899    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3900      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3901        return ImplicitConversionSequence::Better;
3902      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3903        return ImplicitConversionSequence::Worse;
3904    }
3905  }
3906
3907  if (SCS1.Second == ICK_Derived_To_Base) {
3908    //   -- conversion of C to B is better than conversion of C to A,
3909    //   -- binding of an expression of type C to a reference of type
3910    //      B& is better than binding an expression of type C to a
3911    //      reference of type A&,
3912    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3913        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3914      if (S.IsDerivedFrom(ToType1, ToType2))
3915        return ImplicitConversionSequence::Better;
3916      else if (S.IsDerivedFrom(ToType2, ToType1))
3917        return ImplicitConversionSequence::Worse;
3918    }
3919
3920    //   -- conversion of B to A is better than conversion of C to A.
3921    //   -- binding of an expression of type B to a reference of type
3922    //      A& is better than binding an expression of type C to a
3923    //      reference of type A&,
3924    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3925        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3926      if (S.IsDerivedFrom(FromType2, FromType1))
3927        return ImplicitConversionSequence::Better;
3928      else if (S.IsDerivedFrom(FromType1, FromType2))
3929        return ImplicitConversionSequence::Worse;
3930    }
3931  }
3932
3933  return ImplicitConversionSequence::Indistinguishable;
3934}
3935
3936/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3937/// determine whether they are reference-related,
3938/// reference-compatible, reference-compatible with added
3939/// qualification, or incompatible, for use in C++ initialization by
3940/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3941/// type, and the first type (T1) is the pointee type of the reference
3942/// type being initialized.
3943Sema::ReferenceCompareResult
3944Sema::CompareReferenceRelationship(SourceLocation Loc,
3945                                   QualType OrigT1, QualType OrigT2,
3946                                   bool &DerivedToBase,
3947                                   bool &ObjCConversion,
3948                                   bool &ObjCLifetimeConversion) {
3949  assert(!OrigT1->isReferenceType() &&
3950    "T1 must be the pointee type of the reference type");
3951  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3952
3953  QualType T1 = Context.getCanonicalType(OrigT1);
3954  QualType T2 = Context.getCanonicalType(OrigT2);
3955  Qualifiers T1Quals, T2Quals;
3956  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3957  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3958
3959  // C++ [dcl.init.ref]p4:
3960  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3961  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3962  //   T1 is a base class of T2.
3963  DerivedToBase = false;
3964  ObjCConversion = false;
3965  ObjCLifetimeConversion = false;
3966  if (UnqualT1 == UnqualT2) {
3967    // Nothing to do.
3968  } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3969           IsDerivedFrom(UnqualT2, UnqualT1))
3970    DerivedToBase = true;
3971  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3972           UnqualT2->isObjCObjectOrInterfaceType() &&
3973           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3974    ObjCConversion = true;
3975  else
3976    return Ref_Incompatible;
3977
3978  // At this point, we know that T1 and T2 are reference-related (at
3979  // least).
3980
3981  // If the type is an array type, promote the element qualifiers to the type
3982  // for comparison.
3983  if (isa<ArrayType>(T1) && T1Quals)
3984    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3985  if (isa<ArrayType>(T2) && T2Quals)
3986    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3987
3988  // C++ [dcl.init.ref]p4:
3989  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3990  //   reference-related to T2 and cv1 is the same cv-qualification
3991  //   as, or greater cv-qualification than, cv2. For purposes of
3992  //   overload resolution, cases for which cv1 is greater
3993  //   cv-qualification than cv2 are identified as
3994  //   reference-compatible with added qualification (see 13.3.3.2).
3995  //
3996  // Note that we also require equivalence of Objective-C GC and address-space
3997  // qualifiers when performing these computations, so that e.g., an int in
3998  // address space 1 is not reference-compatible with an int in address
3999  // space 2.
4000  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4001      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4002    T1Quals.removeObjCLifetime();
4003    T2Quals.removeObjCLifetime();
4004    ObjCLifetimeConversion = true;
4005  }
4006
4007  if (T1Quals == T2Quals)
4008    return Ref_Compatible;
4009  else if (T1Quals.compatiblyIncludes(T2Quals))
4010    return Ref_Compatible_With_Added_Qualification;
4011  else
4012    return Ref_Related;
4013}
4014
4015/// \brief Look for a user-defined conversion to an value reference-compatible
4016///        with DeclType. Return true if something definite is found.
4017static bool
4018FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4019                         QualType DeclType, SourceLocation DeclLoc,
4020                         Expr *Init, QualType T2, bool AllowRvalues,
4021                         bool AllowExplicit) {
4022  assert(T2->isRecordType() && "Can only find conversions of record types.");
4023  CXXRecordDecl *T2RecordDecl
4024    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4025
4026  OverloadCandidateSet CandidateSet(DeclLoc);
4027  std::pair<CXXRecordDecl::conversion_iterator,
4028            CXXRecordDecl::conversion_iterator>
4029    Conversions = T2RecordDecl->getVisibleConversionFunctions();
4030  for (CXXRecordDecl::conversion_iterator
4031         I = Conversions.first, E = Conversions.second; I != E; ++I) {
4032    NamedDecl *D = *I;
4033    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4034    if (isa<UsingShadowDecl>(D))
4035      D = cast<UsingShadowDecl>(D)->getTargetDecl();
4036
4037    FunctionTemplateDecl *ConvTemplate
4038      = dyn_cast<FunctionTemplateDecl>(D);
4039    CXXConversionDecl *Conv;
4040    if (ConvTemplate)
4041      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4042    else
4043      Conv = cast<CXXConversionDecl>(D);
4044
4045    // If this is an explicit conversion, and we're not allowed to consider
4046    // explicit conversions, skip it.
4047    if (!AllowExplicit && Conv->isExplicit())
4048      continue;
4049
4050    if (AllowRvalues) {
4051      bool DerivedToBase = false;
4052      bool ObjCConversion = false;
4053      bool ObjCLifetimeConversion = false;
4054
4055      // If we are initializing an rvalue reference, don't permit conversion
4056      // functions that return lvalues.
4057      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4058        const ReferenceType *RefType
4059          = Conv->getConversionType()->getAs<LValueReferenceType>();
4060        if (RefType && !RefType->getPointeeType()->isFunctionType())
4061          continue;
4062      }
4063
4064      if (!ConvTemplate &&
4065          S.CompareReferenceRelationship(
4066            DeclLoc,
4067            Conv->getConversionType().getNonReferenceType()
4068              .getUnqualifiedType(),
4069            DeclType.getNonReferenceType().getUnqualifiedType(),
4070            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4071          Sema::Ref_Incompatible)
4072        continue;
4073    } else {
4074      // If the conversion function doesn't return a reference type,
4075      // it can't be considered for this conversion. An rvalue reference
4076      // is only acceptable if its referencee is a function type.
4077
4078      const ReferenceType *RefType =
4079        Conv->getConversionType()->getAs<ReferenceType>();
4080      if (!RefType ||
4081          (!RefType->isLValueReferenceType() &&
4082           !RefType->getPointeeType()->isFunctionType()))
4083        continue;
4084    }
4085
4086    if (ConvTemplate)
4087      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4088                                       Init, DeclType, CandidateSet);
4089    else
4090      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4091                               DeclType, CandidateSet);
4092  }
4093
4094  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4095
4096  OverloadCandidateSet::iterator Best;
4097  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4098  case OR_Success:
4099    // C++ [over.ics.ref]p1:
4100    //
4101    //   [...] If the parameter binds directly to the result of
4102    //   applying a conversion function to the argument
4103    //   expression, the implicit conversion sequence is a
4104    //   user-defined conversion sequence (13.3.3.1.2), with the
4105    //   second standard conversion sequence either an identity
4106    //   conversion or, if the conversion function returns an
4107    //   entity of a type that is a derived class of the parameter
4108    //   type, a derived-to-base Conversion.
4109    if (!Best->FinalConversion.DirectBinding)
4110      return false;
4111
4112    ICS.setUserDefined();
4113    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4114    ICS.UserDefined.After = Best->FinalConversion;
4115    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4116    ICS.UserDefined.ConversionFunction = Best->Function;
4117    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4118    ICS.UserDefined.EllipsisConversion = false;
4119    assert(ICS.UserDefined.After.ReferenceBinding &&
4120           ICS.UserDefined.After.DirectBinding &&
4121           "Expected a direct reference binding!");
4122    return true;
4123
4124  case OR_Ambiguous:
4125    ICS.setAmbiguous();
4126    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4127         Cand != CandidateSet.end(); ++Cand)
4128      if (Cand->Viable)
4129        ICS.Ambiguous.addConversion(Cand->Function);
4130    return true;
4131
4132  case OR_No_Viable_Function:
4133  case OR_Deleted:
4134    // There was no suitable conversion, or we found a deleted
4135    // conversion; continue with other checks.
4136    return false;
4137  }
4138
4139  llvm_unreachable("Invalid OverloadResult!");
4140}
4141
4142/// \brief Compute an implicit conversion sequence for reference
4143/// initialization.
4144static ImplicitConversionSequence
4145TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4146                 SourceLocation DeclLoc,
4147                 bool SuppressUserConversions,
4148                 bool AllowExplicit) {
4149  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4150
4151  // Most paths end in a failed conversion.
4152  ImplicitConversionSequence ICS;
4153  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4154
4155  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4156  QualType T2 = Init->getType();
4157
4158  // If the initializer is the address of an overloaded function, try
4159  // to resolve the overloaded function. If all goes well, T2 is the
4160  // type of the resulting function.
4161  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4162    DeclAccessPair Found;
4163    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4164                                                                false, Found))
4165      T2 = Fn->getType();
4166  }
4167
4168  // Compute some basic properties of the types and the initializer.
4169  bool isRValRef = DeclType->isRValueReferenceType();
4170  bool DerivedToBase = false;
4171  bool ObjCConversion = false;
4172  bool ObjCLifetimeConversion = false;
4173  Expr::Classification InitCategory = Init->Classify(S.Context);
4174  Sema::ReferenceCompareResult RefRelationship
4175    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4176                                     ObjCConversion, ObjCLifetimeConversion);
4177
4178
4179  // C++0x [dcl.init.ref]p5:
4180  //   A reference to type "cv1 T1" is initialized by an expression
4181  //   of type "cv2 T2" as follows:
4182
4183  //     -- If reference is an lvalue reference and the initializer expression
4184  if (!isRValRef) {
4185    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4186    //        reference-compatible with "cv2 T2," or
4187    //
4188    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4189    if (InitCategory.isLValue() &&
4190        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4191      // C++ [over.ics.ref]p1:
4192      //   When a parameter of reference type binds directly (8.5.3)
4193      //   to an argument expression, the implicit conversion sequence
4194      //   is the identity conversion, unless the argument expression
4195      //   has a type that is a derived class of the parameter type,
4196      //   in which case the implicit conversion sequence is a
4197      //   derived-to-base Conversion (13.3.3.1).
4198      ICS.setStandard();
4199      ICS.Standard.First = ICK_Identity;
4200      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4201                         : ObjCConversion? ICK_Compatible_Conversion
4202                         : ICK_Identity;
4203      ICS.Standard.Third = ICK_Identity;
4204      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4205      ICS.Standard.setToType(0, T2);
4206      ICS.Standard.setToType(1, T1);
4207      ICS.Standard.setToType(2, T1);
4208      ICS.Standard.ReferenceBinding = true;
4209      ICS.Standard.DirectBinding = true;
4210      ICS.Standard.IsLvalueReference = !isRValRef;
4211      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4212      ICS.Standard.BindsToRvalue = false;
4213      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4214      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4215      ICS.Standard.CopyConstructor = 0;
4216
4217      // Nothing more to do: the inaccessibility/ambiguity check for
4218      // derived-to-base conversions is suppressed when we're
4219      // computing the implicit conversion sequence (C++
4220      // [over.best.ics]p2).
4221      return ICS;
4222    }
4223
4224    //       -- has a class type (i.e., T2 is a class type), where T1 is
4225    //          not reference-related to T2, and can be implicitly
4226    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4227    //          is reference-compatible with "cv3 T3" 92) (this
4228    //          conversion is selected by enumerating the applicable
4229    //          conversion functions (13.3.1.6) and choosing the best
4230    //          one through overload resolution (13.3)),
4231    if (!SuppressUserConversions && T2->isRecordType() &&
4232        !S.RequireCompleteType(DeclLoc, T2, 0) &&
4233        RefRelationship == Sema::Ref_Incompatible) {
4234      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4235                                   Init, T2, /*AllowRvalues=*/false,
4236                                   AllowExplicit))
4237        return ICS;
4238    }
4239  }
4240
4241  //     -- Otherwise, the reference shall be an lvalue reference to a
4242  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4243  //        shall be an rvalue reference.
4244  //
4245  // We actually handle one oddity of C++ [over.ics.ref] at this
4246  // point, which is that, due to p2 (which short-circuits reference
4247  // binding by only attempting a simple conversion for non-direct
4248  // bindings) and p3's strange wording, we allow a const volatile
4249  // reference to bind to an rvalue. Hence the check for the presence
4250  // of "const" rather than checking for "const" being the only
4251  // qualifier.
4252  // This is also the point where rvalue references and lvalue inits no longer
4253  // go together.
4254  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4255    return ICS;
4256
4257  //       -- If the initializer expression
4258  //
4259  //            -- is an xvalue, class prvalue, array prvalue or function
4260  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4261  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4262      (InitCategory.isXValue() ||
4263      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4264      (InitCategory.isLValue() && T2->isFunctionType()))) {
4265    ICS.setStandard();
4266    ICS.Standard.First = ICK_Identity;
4267    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4268                      : ObjCConversion? ICK_Compatible_Conversion
4269                      : ICK_Identity;
4270    ICS.Standard.Third = ICK_Identity;
4271    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4272    ICS.Standard.setToType(0, T2);
4273    ICS.Standard.setToType(1, T1);
4274    ICS.Standard.setToType(2, T1);
4275    ICS.Standard.ReferenceBinding = true;
4276    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4277    // binding unless we're binding to a class prvalue.
4278    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4279    // allow the use of rvalue references in C++98/03 for the benefit of
4280    // standard library implementors; therefore, we need the xvalue check here.
4281    ICS.Standard.DirectBinding =
4282      S.getLangOpts().CPlusPlus11 ||
4283      (InitCategory.isPRValue() && !T2->isRecordType());
4284    ICS.Standard.IsLvalueReference = !isRValRef;
4285    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4286    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4287    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4288    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4289    ICS.Standard.CopyConstructor = 0;
4290    return ICS;
4291  }
4292
4293  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4294  //               reference-related to T2, and can be implicitly converted to
4295  //               an xvalue, class prvalue, or function lvalue of type
4296  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4297  //               "cv3 T3",
4298  //
4299  //          then the reference is bound to the value of the initializer
4300  //          expression in the first case and to the result of the conversion
4301  //          in the second case (or, in either case, to an appropriate base
4302  //          class subobject).
4303  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4304      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4305      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4306                               Init, T2, /*AllowRvalues=*/true,
4307                               AllowExplicit)) {
4308    // In the second case, if the reference is an rvalue reference
4309    // and the second standard conversion sequence of the
4310    // user-defined conversion sequence includes an lvalue-to-rvalue
4311    // conversion, the program is ill-formed.
4312    if (ICS.isUserDefined() && isRValRef &&
4313        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4314      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4315
4316    return ICS;
4317  }
4318
4319  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4320  //          initialized from the initializer expression using the
4321  //          rules for a non-reference copy initialization (8.5). The
4322  //          reference is then bound to the temporary. If T1 is
4323  //          reference-related to T2, cv1 must be the same
4324  //          cv-qualification as, or greater cv-qualification than,
4325  //          cv2; otherwise, the program is ill-formed.
4326  if (RefRelationship == Sema::Ref_Related) {
4327    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4328    // we would be reference-compatible or reference-compatible with
4329    // added qualification. But that wasn't the case, so the reference
4330    // initialization fails.
4331    //
4332    // Note that we only want to check address spaces and cvr-qualifiers here.
4333    // ObjC GC and lifetime qualifiers aren't important.
4334    Qualifiers T1Quals = T1.getQualifiers();
4335    Qualifiers T2Quals = T2.getQualifiers();
4336    T1Quals.removeObjCGCAttr();
4337    T1Quals.removeObjCLifetime();
4338    T2Quals.removeObjCGCAttr();
4339    T2Quals.removeObjCLifetime();
4340    if (!T1Quals.compatiblyIncludes(T2Quals))
4341      return ICS;
4342  }
4343
4344  // If at least one of the types is a class type, the types are not
4345  // related, and we aren't allowed any user conversions, the
4346  // reference binding fails. This case is important for breaking
4347  // recursion, since TryImplicitConversion below will attempt to
4348  // create a temporary through the use of a copy constructor.
4349  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4350      (T1->isRecordType() || T2->isRecordType()))
4351    return ICS;
4352
4353  // If T1 is reference-related to T2 and the reference is an rvalue
4354  // reference, the initializer expression shall not be an lvalue.
4355  if (RefRelationship >= Sema::Ref_Related &&
4356      isRValRef && Init->Classify(S.Context).isLValue())
4357    return ICS;
4358
4359  // C++ [over.ics.ref]p2:
4360  //   When a parameter of reference type is not bound directly to
4361  //   an argument expression, the conversion sequence is the one
4362  //   required to convert the argument expression to the
4363  //   underlying type of the reference according to
4364  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4365  //   to copy-initializing a temporary of the underlying type with
4366  //   the argument expression. Any difference in top-level
4367  //   cv-qualification is subsumed by the initialization itself
4368  //   and does not constitute a conversion.
4369  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4370                              /*AllowExplicit=*/false,
4371                              /*InOverloadResolution=*/false,
4372                              /*CStyle=*/false,
4373                              /*AllowObjCWritebackConversion=*/false);
4374
4375  // Of course, that's still a reference binding.
4376  if (ICS.isStandard()) {
4377    ICS.Standard.ReferenceBinding = true;
4378    ICS.Standard.IsLvalueReference = !isRValRef;
4379    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4380    ICS.Standard.BindsToRvalue = true;
4381    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4382    ICS.Standard.ObjCLifetimeConversionBinding = false;
4383  } else if (ICS.isUserDefined()) {
4384    // Don't allow rvalue references to bind to lvalues.
4385    if (DeclType->isRValueReferenceType()) {
4386      if (const ReferenceType *RefType
4387            = ICS.UserDefined.ConversionFunction->getResultType()
4388                ->getAs<LValueReferenceType>()) {
4389        if (!RefType->getPointeeType()->isFunctionType()) {
4390          ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4391                     DeclType);
4392          return ICS;
4393        }
4394      }
4395    }
4396
4397    ICS.UserDefined.After.ReferenceBinding = true;
4398    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4399    ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4400    ICS.UserDefined.After.BindsToRvalue = true;
4401    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4402    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4403  }
4404
4405  return ICS;
4406}
4407
4408static ImplicitConversionSequence
4409TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4410                      bool SuppressUserConversions,
4411                      bool InOverloadResolution,
4412                      bool AllowObjCWritebackConversion,
4413                      bool AllowExplicit = false);
4414
4415/// TryListConversion - Try to copy-initialize a value of type ToType from the
4416/// initializer list From.
4417static ImplicitConversionSequence
4418TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4419                  bool SuppressUserConversions,
4420                  bool InOverloadResolution,
4421                  bool AllowObjCWritebackConversion) {
4422  // C++11 [over.ics.list]p1:
4423  //   When an argument is an initializer list, it is not an expression and
4424  //   special rules apply for converting it to a parameter type.
4425
4426  ImplicitConversionSequence Result;
4427  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4428  Result.setListInitializationSequence();
4429
4430  // We need a complete type for what follows. Incomplete types can never be
4431  // initialized from init lists.
4432  if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4433    return Result;
4434
4435  // C++11 [over.ics.list]p2:
4436  //   If the parameter type is std::initializer_list<X> or "array of X" and
4437  //   all the elements can be implicitly converted to X, the implicit
4438  //   conversion sequence is the worst conversion necessary to convert an
4439  //   element of the list to X.
4440  bool toStdInitializerList = false;
4441  QualType X;
4442  if (ToType->isArrayType())
4443    X = S.Context.getAsArrayType(ToType)->getElementType();
4444  else
4445    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4446  if (!X.isNull()) {
4447    for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4448      Expr *Init = From->getInit(i);
4449      ImplicitConversionSequence ICS =
4450          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4451                                InOverloadResolution,
4452                                AllowObjCWritebackConversion);
4453      // If a single element isn't convertible, fail.
4454      if (ICS.isBad()) {
4455        Result = ICS;
4456        break;
4457      }
4458      // Otherwise, look for the worst conversion.
4459      if (Result.isBad() ||
4460          CompareImplicitConversionSequences(S, ICS, Result) ==
4461              ImplicitConversionSequence::Worse)
4462        Result = ICS;
4463    }
4464
4465    // For an empty list, we won't have computed any conversion sequence.
4466    // Introduce the identity conversion sequence.
4467    if (From->getNumInits() == 0) {
4468      Result.setStandard();
4469      Result.Standard.setAsIdentityConversion();
4470      Result.Standard.setFromType(ToType);
4471      Result.Standard.setAllToTypes(ToType);
4472    }
4473
4474    Result.setListInitializationSequence();
4475    Result.setStdInitializerListElement(toStdInitializerList);
4476    return Result;
4477  }
4478
4479  // C++11 [over.ics.list]p3:
4480  //   Otherwise, if the parameter is a non-aggregate class X and overload
4481  //   resolution chooses a single best constructor [...] the implicit
4482  //   conversion sequence is a user-defined conversion sequence. If multiple
4483  //   constructors are viable but none is better than the others, the
4484  //   implicit conversion sequence is a user-defined conversion sequence.
4485  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4486    // This function can deal with initializer lists.
4487    Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4488                                      /*AllowExplicit=*/false,
4489                                      InOverloadResolution, /*CStyle=*/false,
4490                                      AllowObjCWritebackConversion);
4491    Result.setListInitializationSequence();
4492    return Result;
4493  }
4494
4495  // C++11 [over.ics.list]p4:
4496  //   Otherwise, if the parameter has an aggregate type which can be
4497  //   initialized from the initializer list [...] the implicit conversion
4498  //   sequence is a user-defined conversion sequence.
4499  if (ToType->isAggregateType()) {
4500    // Type is an aggregate, argument is an init list. At this point it comes
4501    // down to checking whether the initialization works.
4502    // FIXME: Find out whether this parameter is consumed or not.
4503    InitializedEntity Entity =
4504        InitializedEntity::InitializeParameter(S.Context, ToType,
4505                                               /*Consumed=*/false);
4506    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4507      Result.setUserDefined();
4508      Result.UserDefined.Before.setAsIdentityConversion();
4509      // Initializer lists don't have a type.
4510      Result.UserDefined.Before.setFromType(QualType());
4511      Result.UserDefined.Before.setAllToTypes(QualType());
4512
4513      Result.UserDefined.After.setAsIdentityConversion();
4514      Result.UserDefined.After.setFromType(ToType);
4515      Result.UserDefined.After.setAllToTypes(ToType);
4516      Result.UserDefined.ConversionFunction = 0;
4517    }
4518    return Result;
4519  }
4520
4521  // C++11 [over.ics.list]p5:
4522  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4523  if (ToType->isReferenceType()) {
4524    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4525    // mention initializer lists in any way. So we go by what list-
4526    // initialization would do and try to extrapolate from that.
4527
4528    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4529
4530    // If the initializer list has a single element that is reference-related
4531    // to the parameter type, we initialize the reference from that.
4532    if (From->getNumInits() == 1) {
4533      Expr *Init = From->getInit(0);
4534
4535      QualType T2 = Init->getType();
4536
4537      // If the initializer is the address of an overloaded function, try
4538      // to resolve the overloaded function. If all goes well, T2 is the
4539      // type of the resulting function.
4540      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4541        DeclAccessPair Found;
4542        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4543                                   Init, ToType, false, Found))
4544          T2 = Fn->getType();
4545      }
4546
4547      // Compute some basic properties of the types and the initializer.
4548      bool dummy1 = false;
4549      bool dummy2 = false;
4550      bool dummy3 = false;
4551      Sema::ReferenceCompareResult RefRelationship
4552        = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4553                                         dummy2, dummy3);
4554
4555      if (RefRelationship >= Sema::Ref_Related)
4556        return TryReferenceInit(S, Init, ToType,
4557                                /*FIXME:*/From->getLocStart(),
4558                                SuppressUserConversions,
4559                                /*AllowExplicit=*/false);
4560    }
4561
4562    // Otherwise, we bind the reference to a temporary created from the
4563    // initializer list.
4564    Result = TryListConversion(S, From, T1, SuppressUserConversions,
4565                               InOverloadResolution,
4566                               AllowObjCWritebackConversion);
4567    if (Result.isFailure())
4568      return Result;
4569    assert(!Result.isEllipsis() &&
4570           "Sub-initialization cannot result in ellipsis conversion.");
4571
4572    // Can we even bind to a temporary?
4573    if (ToType->isRValueReferenceType() ||
4574        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4575      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4576                                            Result.UserDefined.After;
4577      SCS.ReferenceBinding = true;
4578      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4579      SCS.BindsToRvalue = true;
4580      SCS.BindsToFunctionLvalue = false;
4581      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4582      SCS.ObjCLifetimeConversionBinding = false;
4583    } else
4584      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4585                    From, ToType);
4586    return Result;
4587  }
4588
4589  // C++11 [over.ics.list]p6:
4590  //   Otherwise, if the parameter type is not a class:
4591  if (!ToType->isRecordType()) {
4592    //    - if the initializer list has one element, the implicit conversion
4593    //      sequence is the one required to convert the element to the
4594    //      parameter type.
4595    unsigned NumInits = From->getNumInits();
4596    if (NumInits == 1)
4597      Result = TryCopyInitialization(S, From->getInit(0), ToType,
4598                                     SuppressUserConversions,
4599                                     InOverloadResolution,
4600                                     AllowObjCWritebackConversion);
4601    //    - if the initializer list has no elements, the implicit conversion
4602    //      sequence is the identity conversion.
4603    else if (NumInits == 0) {
4604      Result.setStandard();
4605      Result.Standard.setAsIdentityConversion();
4606      Result.Standard.setFromType(ToType);
4607      Result.Standard.setAllToTypes(ToType);
4608    }
4609    Result.setListInitializationSequence();
4610    return Result;
4611  }
4612
4613  // C++11 [over.ics.list]p7:
4614  //   In all cases other than those enumerated above, no conversion is possible
4615  return Result;
4616}
4617
4618/// TryCopyInitialization - Try to copy-initialize a value of type
4619/// ToType from the expression From. Return the implicit conversion
4620/// sequence required to pass this argument, which may be a bad
4621/// conversion sequence (meaning that the argument cannot be passed to
4622/// a parameter of this type). If @p SuppressUserConversions, then we
4623/// do not permit any user-defined conversion sequences.
4624static ImplicitConversionSequence
4625TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4626                      bool SuppressUserConversions,
4627                      bool InOverloadResolution,
4628                      bool AllowObjCWritebackConversion,
4629                      bool AllowExplicit) {
4630  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4631    return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4632                             InOverloadResolution,AllowObjCWritebackConversion);
4633
4634  if (ToType->isReferenceType())
4635    return TryReferenceInit(S, From, ToType,
4636                            /*FIXME:*/From->getLocStart(),
4637                            SuppressUserConversions,
4638                            AllowExplicit);
4639
4640  return TryImplicitConversion(S, From, ToType,
4641                               SuppressUserConversions,
4642                               /*AllowExplicit=*/false,
4643                               InOverloadResolution,
4644                               /*CStyle=*/false,
4645                               AllowObjCWritebackConversion);
4646}
4647
4648static bool TryCopyInitialization(const CanQualType FromQTy,
4649                                  const CanQualType ToQTy,
4650                                  Sema &S,
4651                                  SourceLocation Loc,
4652                                  ExprValueKind FromVK) {
4653  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4654  ImplicitConversionSequence ICS =
4655    TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4656
4657  return !ICS.isBad();
4658}
4659
4660/// TryObjectArgumentInitialization - Try to initialize the object
4661/// parameter of the given member function (@c Method) from the
4662/// expression @p From.
4663static ImplicitConversionSequence
4664TryObjectArgumentInitialization(Sema &S, QualType FromType,
4665                                Expr::Classification FromClassification,
4666                                CXXMethodDecl *Method,
4667                                CXXRecordDecl *ActingContext) {
4668  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4669  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4670  //                 const volatile object.
4671  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4672    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4673  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4674
4675  // Set up the conversion sequence as a "bad" conversion, to allow us
4676  // to exit early.
4677  ImplicitConversionSequence ICS;
4678
4679  // We need to have an object of class type.
4680  if (const PointerType *PT = FromType->getAs<PointerType>()) {
4681    FromType = PT->getPointeeType();
4682
4683    // When we had a pointer, it's implicitly dereferenced, so we
4684    // better have an lvalue.
4685    assert(FromClassification.isLValue());
4686  }
4687
4688  assert(FromType->isRecordType());
4689
4690  // C++0x [over.match.funcs]p4:
4691  //   For non-static member functions, the type of the implicit object
4692  //   parameter is
4693  //
4694  //     - "lvalue reference to cv X" for functions declared without a
4695  //        ref-qualifier or with the & ref-qualifier
4696  //     - "rvalue reference to cv X" for functions declared with the &&
4697  //        ref-qualifier
4698  //
4699  // where X is the class of which the function is a member and cv is the
4700  // cv-qualification on the member function declaration.
4701  //
4702  // However, when finding an implicit conversion sequence for the argument, we
4703  // are not allowed to create temporaries or perform user-defined conversions
4704  // (C++ [over.match.funcs]p5). We perform a simplified version of
4705  // reference binding here, that allows class rvalues to bind to
4706  // non-constant references.
4707
4708  // First check the qualifiers.
4709  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4710  if (ImplicitParamType.getCVRQualifiers()
4711                                    != FromTypeCanon.getLocalCVRQualifiers() &&
4712      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4713    ICS.setBad(BadConversionSequence::bad_qualifiers,
4714               FromType, ImplicitParamType);
4715    return ICS;
4716  }
4717
4718  // Check that we have either the same type or a derived type. It
4719  // affects the conversion rank.
4720  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4721  ImplicitConversionKind SecondKind;
4722  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4723    SecondKind = ICK_Identity;
4724  } else if (S.IsDerivedFrom(FromType, ClassType))
4725    SecondKind = ICK_Derived_To_Base;
4726  else {
4727    ICS.setBad(BadConversionSequence::unrelated_class,
4728               FromType, ImplicitParamType);
4729    return ICS;
4730  }
4731
4732  // Check the ref-qualifier.
4733  switch (Method->getRefQualifier()) {
4734  case RQ_None:
4735    // Do nothing; we don't care about lvalueness or rvalueness.
4736    break;
4737
4738  case RQ_LValue:
4739    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4740      // non-const lvalue reference cannot bind to an rvalue
4741      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4742                 ImplicitParamType);
4743      return ICS;
4744    }
4745    break;
4746
4747  case RQ_RValue:
4748    if (!FromClassification.isRValue()) {
4749      // rvalue reference cannot bind to an lvalue
4750      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4751                 ImplicitParamType);
4752      return ICS;
4753    }
4754    break;
4755  }
4756
4757  // Success. Mark this as a reference binding.
4758  ICS.setStandard();
4759  ICS.Standard.setAsIdentityConversion();
4760  ICS.Standard.Second = SecondKind;
4761  ICS.Standard.setFromType(FromType);
4762  ICS.Standard.setAllToTypes(ImplicitParamType);
4763  ICS.Standard.ReferenceBinding = true;
4764  ICS.Standard.DirectBinding = true;
4765  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4766  ICS.Standard.BindsToFunctionLvalue = false;
4767  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4768  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4769    = (Method->getRefQualifier() == RQ_None);
4770  return ICS;
4771}
4772
4773/// PerformObjectArgumentInitialization - Perform initialization of
4774/// the implicit object parameter for the given Method with the given
4775/// expression.
4776ExprResult
4777Sema::PerformObjectArgumentInitialization(Expr *From,
4778                                          NestedNameSpecifier *Qualifier,
4779                                          NamedDecl *FoundDecl,
4780                                          CXXMethodDecl *Method) {
4781  QualType FromRecordType, DestType;
4782  QualType ImplicitParamRecordType  =
4783    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4784
4785  Expr::Classification FromClassification;
4786  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4787    FromRecordType = PT->getPointeeType();
4788    DestType = Method->getThisType(Context);
4789    FromClassification = Expr::Classification::makeSimpleLValue();
4790  } else {
4791    FromRecordType = From->getType();
4792    DestType = ImplicitParamRecordType;
4793    FromClassification = From->Classify(Context);
4794  }
4795
4796  // Note that we always use the true parent context when performing
4797  // the actual argument initialization.
4798  ImplicitConversionSequence ICS
4799    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4800                                      Method, Method->getParent());
4801  if (ICS.isBad()) {
4802    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4803      Qualifiers FromQs = FromRecordType.getQualifiers();
4804      Qualifiers ToQs = DestType.getQualifiers();
4805      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4806      if (CVR) {
4807        Diag(From->getLocStart(),
4808             diag::err_member_function_call_bad_cvr)
4809          << Method->getDeclName() << FromRecordType << (CVR - 1)
4810          << From->getSourceRange();
4811        Diag(Method->getLocation(), diag::note_previous_decl)
4812          << Method->getDeclName();
4813        return ExprError();
4814      }
4815    }
4816
4817    return Diag(From->getLocStart(),
4818                diag::err_implicit_object_parameter_init)
4819       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4820  }
4821
4822  if (ICS.Standard.Second == ICK_Derived_To_Base) {
4823    ExprResult FromRes =
4824      PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4825    if (FromRes.isInvalid())
4826      return ExprError();
4827    From = FromRes.take();
4828  }
4829
4830  if (!Context.hasSameType(From->getType(), DestType))
4831    From = ImpCastExprToType(From, DestType, CK_NoOp,
4832                             From->getValueKind()).take();
4833  return Owned(From);
4834}
4835
4836/// TryContextuallyConvertToBool - Attempt to contextually convert the
4837/// expression From to bool (C++0x [conv]p3).
4838static ImplicitConversionSequence
4839TryContextuallyConvertToBool(Sema &S, Expr *From) {
4840  // FIXME: This is pretty broken.
4841  return TryImplicitConversion(S, From, S.Context.BoolTy,
4842                               // FIXME: Are these flags correct?
4843                               /*SuppressUserConversions=*/false,
4844                               /*AllowExplicit=*/true,
4845                               /*InOverloadResolution=*/false,
4846                               /*CStyle=*/false,
4847                               /*AllowObjCWritebackConversion=*/false);
4848}
4849
4850/// PerformContextuallyConvertToBool - Perform a contextual conversion
4851/// of the expression From to bool (C++0x [conv]p3).
4852ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4853  if (checkPlaceholderForOverload(*this, From))
4854    return ExprError();
4855
4856  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4857  if (!ICS.isBad())
4858    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4859
4860  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4861    return Diag(From->getLocStart(),
4862                diag::err_typecheck_bool_condition)
4863                  << From->getType() << From->getSourceRange();
4864  return ExprError();
4865}
4866
4867/// Check that the specified conversion is permitted in a converted constant
4868/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4869/// is acceptable.
4870static bool CheckConvertedConstantConversions(Sema &S,
4871                                              StandardConversionSequence &SCS) {
4872  // Since we know that the target type is an integral or unscoped enumeration
4873  // type, most conversion kinds are impossible. All possible First and Third
4874  // conversions are fine.
4875  switch (SCS.Second) {
4876  case ICK_Identity:
4877  case ICK_Integral_Promotion:
4878  case ICK_Integral_Conversion:
4879  case ICK_Zero_Event_Conversion:
4880    return true;
4881
4882  case ICK_Boolean_Conversion:
4883    // Conversion from an integral or unscoped enumeration type to bool is
4884    // classified as ICK_Boolean_Conversion, but it's also an integral
4885    // conversion, so it's permitted in a converted constant expression.
4886    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4887           SCS.getToType(2)->isBooleanType();
4888
4889  case ICK_Floating_Integral:
4890  case ICK_Complex_Real:
4891    return false;
4892
4893  case ICK_Lvalue_To_Rvalue:
4894  case ICK_Array_To_Pointer:
4895  case ICK_Function_To_Pointer:
4896  case ICK_NoReturn_Adjustment:
4897  case ICK_Qualification:
4898  case ICK_Compatible_Conversion:
4899  case ICK_Vector_Conversion:
4900  case ICK_Vector_Splat:
4901  case ICK_Derived_To_Base:
4902  case ICK_Pointer_Conversion:
4903  case ICK_Pointer_Member:
4904  case ICK_Block_Pointer_Conversion:
4905  case ICK_Writeback_Conversion:
4906  case ICK_Floating_Promotion:
4907  case ICK_Complex_Promotion:
4908  case ICK_Complex_Conversion:
4909  case ICK_Floating_Conversion:
4910  case ICK_TransparentUnionConversion:
4911    llvm_unreachable("unexpected second conversion kind");
4912
4913  case ICK_Num_Conversion_Kinds:
4914    break;
4915  }
4916
4917  llvm_unreachable("unknown conversion kind");
4918}
4919
4920/// CheckConvertedConstantExpression - Check that the expression From is a
4921/// converted constant expression of type T, perform the conversion and produce
4922/// the converted expression, per C++11 [expr.const]p3.
4923ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4924                                                  llvm::APSInt &Value,
4925                                                  CCEKind CCE) {
4926  assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4927  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4928
4929  if (checkPlaceholderForOverload(*this, From))
4930    return ExprError();
4931
4932  // C++11 [expr.const]p3 with proposed wording fixes:
4933  //  A converted constant expression of type T is a core constant expression,
4934  //  implicitly converted to a prvalue of type T, where the converted
4935  //  expression is a literal constant expression and the implicit conversion
4936  //  sequence contains only user-defined conversions, lvalue-to-rvalue
4937  //  conversions, integral promotions, and integral conversions other than
4938  //  narrowing conversions.
4939  ImplicitConversionSequence ICS =
4940    TryImplicitConversion(From, T,
4941                          /*SuppressUserConversions=*/false,
4942                          /*AllowExplicit=*/false,
4943                          /*InOverloadResolution=*/false,
4944                          /*CStyle=*/false,
4945                          /*AllowObjcWritebackConversion=*/false);
4946  StandardConversionSequence *SCS = 0;
4947  switch (ICS.getKind()) {
4948  case ImplicitConversionSequence::StandardConversion:
4949    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4950      return Diag(From->getLocStart(),
4951                  diag::err_typecheck_converted_constant_expression_disallowed)
4952               << From->getType() << From->getSourceRange() << T;
4953    SCS = &ICS.Standard;
4954    break;
4955  case ImplicitConversionSequence::UserDefinedConversion:
4956    // We are converting from class type to an integral or enumeration type, so
4957    // the Before sequence must be trivial.
4958    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4959      return Diag(From->getLocStart(),
4960                  diag::err_typecheck_converted_constant_expression_disallowed)
4961               << From->getType() << From->getSourceRange() << T;
4962    SCS = &ICS.UserDefined.After;
4963    break;
4964  case ImplicitConversionSequence::AmbiguousConversion:
4965  case ImplicitConversionSequence::BadConversion:
4966    if (!DiagnoseMultipleUserDefinedConversion(From, T))
4967      return Diag(From->getLocStart(),
4968                  diag::err_typecheck_converted_constant_expression)
4969                    << From->getType() << From->getSourceRange() << T;
4970    return ExprError();
4971
4972  case ImplicitConversionSequence::EllipsisConversion:
4973    llvm_unreachable("ellipsis conversion in converted constant expression");
4974  }
4975
4976  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4977  if (Result.isInvalid())
4978    return Result;
4979
4980  // Check for a narrowing implicit conversion.
4981  APValue PreNarrowingValue;
4982  QualType PreNarrowingType;
4983  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4984                                PreNarrowingType)) {
4985  case NK_Variable_Narrowing:
4986    // Implicit conversion to a narrower type, and the value is not a constant
4987    // expression. We'll diagnose this in a moment.
4988  case NK_Not_Narrowing:
4989    break;
4990
4991  case NK_Constant_Narrowing:
4992    Diag(From->getLocStart(),
4993         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4994                             diag::err_cce_narrowing)
4995      << CCE << /*Constant*/1
4996      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
4997    break;
4998
4999  case NK_Type_Narrowing:
5000    Diag(From->getLocStart(),
5001         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5002                             diag::err_cce_narrowing)
5003      << CCE << /*Constant*/0 << From->getType() << T;
5004    break;
5005  }
5006
5007  // Check the expression is a constant expression.
5008  SmallVector<PartialDiagnosticAt, 8> Notes;
5009  Expr::EvalResult Eval;
5010  Eval.Diag = &Notes;
5011
5012  if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
5013    // The expression can't be folded, so we can't keep it at this position in
5014    // the AST.
5015    Result = ExprError();
5016  } else {
5017    Value = Eval.Val.getInt();
5018
5019    if (Notes.empty()) {
5020      // It's a constant expression.
5021      return Result;
5022    }
5023  }
5024
5025  // It's not a constant expression. Produce an appropriate diagnostic.
5026  if (Notes.size() == 1 &&
5027      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5028    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5029  else {
5030    Diag(From->getLocStart(), diag::err_expr_not_cce)
5031      << CCE << From->getSourceRange();
5032    for (unsigned I = 0; I < Notes.size(); ++I)
5033      Diag(Notes[I].first, Notes[I].second);
5034  }
5035  return Result;
5036}
5037
5038/// dropPointerConversions - If the given standard conversion sequence
5039/// involves any pointer conversions, remove them.  This may change
5040/// the result type of the conversion sequence.
5041static void dropPointerConversion(StandardConversionSequence &SCS) {
5042  if (SCS.Second == ICK_Pointer_Conversion) {
5043    SCS.Second = ICK_Identity;
5044    SCS.Third = ICK_Identity;
5045    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5046  }
5047}
5048
5049/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5050/// convert the expression From to an Objective-C pointer type.
5051static ImplicitConversionSequence
5052TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5053  // Do an implicit conversion to 'id'.
5054  QualType Ty = S.Context.getObjCIdType();
5055  ImplicitConversionSequence ICS
5056    = TryImplicitConversion(S, From, Ty,
5057                            // FIXME: Are these flags correct?
5058                            /*SuppressUserConversions=*/false,
5059                            /*AllowExplicit=*/true,
5060                            /*InOverloadResolution=*/false,
5061                            /*CStyle=*/false,
5062                            /*AllowObjCWritebackConversion=*/false);
5063
5064  // Strip off any final conversions to 'id'.
5065  switch (ICS.getKind()) {
5066  case ImplicitConversionSequence::BadConversion:
5067  case ImplicitConversionSequence::AmbiguousConversion:
5068  case ImplicitConversionSequence::EllipsisConversion:
5069    break;
5070
5071  case ImplicitConversionSequence::UserDefinedConversion:
5072    dropPointerConversion(ICS.UserDefined.After);
5073    break;
5074
5075  case ImplicitConversionSequence::StandardConversion:
5076    dropPointerConversion(ICS.Standard);
5077    break;
5078  }
5079
5080  return ICS;
5081}
5082
5083/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5084/// conversion of the expression From to an Objective-C pointer type.
5085ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5086  if (checkPlaceholderForOverload(*this, From))
5087    return ExprError();
5088
5089  QualType Ty = Context.getObjCIdType();
5090  ImplicitConversionSequence ICS =
5091    TryContextuallyConvertToObjCPointer(*this, From);
5092  if (!ICS.isBad())
5093    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5094  return ExprError();
5095}
5096
5097/// Determine whether the provided type is an integral type, or an enumeration
5098/// type of a permitted flavor.
5099static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5100  return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5101                         : T->isIntegralOrUnscopedEnumerationType();
5102}
5103
5104/// \brief Attempt to convert the given expression to an integral or
5105/// enumeration type.
5106///
5107/// This routine will attempt to convert an expression of class type to an
5108/// integral or enumeration type, if that class type only has a single
5109/// conversion to an integral or enumeration type.
5110///
5111/// \param Loc The source location of the construct that requires the
5112/// conversion.
5113///
5114/// \param From The expression we're converting from.
5115///
5116/// \param Diagnoser Used to output any diagnostics.
5117///
5118/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5119/// enumerations should be considered.
5120///
5121/// \returns The expression, converted to an integral or enumeration type if
5122/// successful.
5123ExprResult
5124Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
5125                                         ICEConvertDiagnoser &Diagnoser,
5126                                         bool AllowScopedEnumerations) {
5127  // We can't perform any more checking for type-dependent expressions.
5128  if (From->isTypeDependent())
5129    return Owned(From);
5130
5131  // Process placeholders immediately.
5132  if (From->hasPlaceholderType()) {
5133    ExprResult result = CheckPlaceholderExpr(From);
5134    if (result.isInvalid()) return result;
5135    From = result.take();
5136  }
5137
5138  // If the expression already has integral or enumeration type, we're golden.
5139  QualType T = From->getType();
5140  if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
5141    return DefaultLvalueConversion(From);
5142
5143  // FIXME: Check for missing '()' if T is a function type?
5144
5145  // If we don't have a class type in C++, there's no way we can get an
5146  // expression of integral or enumeration type.
5147  const RecordType *RecordTy = T->getAs<RecordType>();
5148  if (!RecordTy || !getLangOpts().CPlusPlus) {
5149    if (!Diagnoser.Suppress)
5150      Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
5151    return Owned(From);
5152  }
5153
5154  // We must have a complete class type.
5155  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5156    ICEConvertDiagnoser &Diagnoser;
5157    Expr *From;
5158
5159    TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5160      : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
5161
5162    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5163      Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5164    }
5165  } IncompleteDiagnoser(Diagnoser, From);
5166
5167  if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5168    return Owned(From);
5169
5170  // Look for a conversion to an integral or enumeration type.
5171  UnresolvedSet<4> ViableConversions;
5172  UnresolvedSet<4> ExplicitConversions;
5173  std::pair<CXXRecordDecl::conversion_iterator,
5174            CXXRecordDecl::conversion_iterator> Conversions
5175    = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5176
5177  bool HadMultipleCandidates
5178    = (std::distance(Conversions.first, Conversions.second) > 1);
5179
5180  for (CXXRecordDecl::conversion_iterator
5181         I = Conversions.first, E = Conversions.second; I != E; ++I) {
5182    if (CXXConversionDecl *Conversion
5183          = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5184      if (isIntegralOrEnumerationType(
5185            Conversion->getConversionType().getNonReferenceType(),
5186            AllowScopedEnumerations)) {
5187        if (Conversion->isExplicit())
5188          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5189        else
5190          ViableConversions.addDecl(I.getDecl(), I.getAccess());
5191      }
5192    }
5193  }
5194
5195  switch (ViableConversions.size()) {
5196  case 0:
5197    if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
5198      DeclAccessPair Found = ExplicitConversions[0];
5199      CXXConversionDecl *Conversion
5200        = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5201
5202      // The user probably meant to invoke the given explicit
5203      // conversion; use it.
5204      QualType ConvTy
5205        = Conversion->getConversionType().getNonReferenceType();
5206      std::string TypeStr;
5207      ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
5208
5209      Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
5210        << FixItHint::CreateInsertion(From->getLocStart(),
5211                                      "static_cast<" + TypeStr + ">(")
5212        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5213                                      ")");
5214      Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
5215
5216      // If we aren't in a SFINAE context, build a call to the
5217      // explicit conversion function.
5218      if (isSFINAEContext())
5219        return ExprError();
5220
5221      CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5222      ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5223                                                 HadMultipleCandidates);
5224      if (Result.isInvalid())
5225        return ExprError();
5226      // Record usage of conversion in an implicit cast.
5227      From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5228                                      CK_UserDefinedConversion,
5229                                      Result.get(), 0,
5230                                      Result.get()->getValueKind());
5231    }
5232
5233    // We'll complain below about a non-integral condition type.
5234    break;
5235
5236  case 1: {
5237    // Apply this conversion.
5238    DeclAccessPair Found = ViableConversions[0];
5239    CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5240
5241    CXXConversionDecl *Conversion
5242      = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5243    QualType ConvTy
5244      = Conversion->getConversionType().getNonReferenceType();
5245    if (!Diagnoser.SuppressConversion) {
5246      if (isSFINAEContext())
5247        return ExprError();
5248
5249      Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5250        << From->getSourceRange();
5251    }
5252
5253    ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5254                                               HadMultipleCandidates);
5255    if (Result.isInvalid())
5256      return ExprError();
5257    // Record usage of conversion in an implicit cast.
5258    From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5259                                    CK_UserDefinedConversion,
5260                                    Result.get(), 0,
5261                                    Result.get()->getValueKind());
5262    break;
5263  }
5264
5265  default:
5266    if (Diagnoser.Suppress)
5267      return ExprError();
5268
5269    Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
5270    for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5271      CXXConversionDecl *Conv
5272        = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5273      QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5274      Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
5275    }
5276    return Owned(From);
5277  }
5278
5279  if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5280      !Diagnoser.Suppress) {
5281    Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5282      << From->getSourceRange();
5283  }
5284
5285  return DefaultLvalueConversion(From);
5286}
5287
5288/// AddOverloadCandidate - Adds the given function to the set of
5289/// candidate functions, using the given function call arguments.  If
5290/// @p SuppressUserConversions, then don't allow user-defined
5291/// conversions via constructors or conversion operators.
5292///
5293/// \param PartialOverloading true if we are performing "partial" overloading
5294/// based on an incomplete set of function arguments. This feature is used by
5295/// code completion.
5296void
5297Sema::AddOverloadCandidate(FunctionDecl *Function,
5298                           DeclAccessPair FoundDecl,
5299                           ArrayRef<Expr *> Args,
5300                           OverloadCandidateSet& CandidateSet,
5301                           bool SuppressUserConversions,
5302                           bool PartialOverloading,
5303                           bool AllowExplicit) {
5304  const FunctionProtoType* Proto
5305    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5306  assert(Proto && "Functions without a prototype cannot be overloaded");
5307  assert(!Function->getDescribedFunctionTemplate() &&
5308         "Use AddTemplateOverloadCandidate for function templates");
5309
5310  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5311    if (!isa<CXXConstructorDecl>(Method)) {
5312      // If we get here, it's because we're calling a member function
5313      // that is named without a member access expression (e.g.,
5314      // "this->f") that was either written explicitly or created
5315      // implicitly. This can happen with a qualified call to a member
5316      // function, e.g., X::f(). We use an empty type for the implied
5317      // object argument (C++ [over.call.func]p3), and the acting context
5318      // is irrelevant.
5319      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5320                         QualType(), Expr::Classification::makeSimpleLValue(),
5321                         Args, CandidateSet, SuppressUserConversions);
5322      return;
5323    }
5324    // We treat a constructor like a non-member function, since its object
5325    // argument doesn't participate in overload resolution.
5326  }
5327
5328  if (!CandidateSet.isNewCandidate(Function))
5329    return;
5330
5331  // Overload resolution is always an unevaluated context.
5332  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5333
5334  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5335    // C++ [class.copy]p3:
5336    //   A member function template is never instantiated to perform the copy
5337    //   of a class object to an object of its class type.
5338    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5339    if (Args.size() == 1 &&
5340        Constructor->isSpecializationCopyingObject() &&
5341        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5342         IsDerivedFrom(Args[0]->getType(), ClassType)))
5343      return;
5344  }
5345
5346  // Add this candidate
5347  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5348  Candidate.FoundDecl = FoundDecl;
5349  Candidate.Function = Function;
5350  Candidate.Viable = true;
5351  Candidate.IsSurrogate = false;
5352  Candidate.IgnoreObjectArgument = false;
5353  Candidate.ExplicitCallArguments = Args.size();
5354
5355  unsigned NumArgsInProto = Proto->getNumArgs();
5356
5357  // (C++ 13.3.2p2): A candidate function having fewer than m
5358  // parameters is viable only if it has an ellipsis in its parameter
5359  // list (8.3.5).
5360  if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5361      !Proto->isVariadic()) {
5362    Candidate.Viable = false;
5363    Candidate.FailureKind = ovl_fail_too_many_arguments;
5364    return;
5365  }
5366
5367  // (C++ 13.3.2p2): A candidate function having more than m parameters
5368  // is viable only if the (m+1)st parameter has a default argument
5369  // (8.3.6). For the purposes of overload resolution, the
5370  // parameter list is truncated on the right, so that there are
5371  // exactly m parameters.
5372  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5373  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5374    // Not enough arguments.
5375    Candidate.Viable = false;
5376    Candidate.FailureKind = ovl_fail_too_few_arguments;
5377    return;
5378  }
5379
5380  // (CUDA B.1): Check for invalid calls between targets.
5381  if (getLangOpts().CUDA)
5382    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5383      if (CheckCUDATarget(Caller, Function)) {
5384        Candidate.Viable = false;
5385        Candidate.FailureKind = ovl_fail_bad_target;
5386        return;
5387      }
5388
5389  // Determine the implicit conversion sequences for each of the
5390  // arguments.
5391  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5392    if (ArgIdx < NumArgsInProto) {
5393      // (C++ 13.3.2p3): for F to be a viable function, there shall
5394      // exist for each argument an implicit conversion sequence
5395      // (13.3.3.1) that converts that argument to the corresponding
5396      // parameter of F.
5397      QualType ParamType = Proto->getArgType(ArgIdx);
5398      Candidate.Conversions[ArgIdx]
5399        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5400                                SuppressUserConversions,
5401                                /*InOverloadResolution=*/true,
5402                                /*AllowObjCWritebackConversion=*/
5403                                  getLangOpts().ObjCAutoRefCount,
5404                                AllowExplicit);
5405      if (Candidate.Conversions[ArgIdx].isBad()) {
5406        Candidate.Viable = false;
5407        Candidate.FailureKind = ovl_fail_bad_conversion;
5408        break;
5409      }
5410    } else {
5411      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5412      // argument for which there is no corresponding parameter is
5413      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5414      Candidate.Conversions[ArgIdx].setEllipsis();
5415    }
5416  }
5417}
5418
5419/// \brief Add all of the function declarations in the given function set to
5420/// the overload canddiate set.
5421void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5422                                 ArrayRef<Expr *> Args,
5423                                 OverloadCandidateSet& CandidateSet,
5424                                 bool SuppressUserConversions,
5425                               TemplateArgumentListInfo *ExplicitTemplateArgs) {
5426  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5427    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5428    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5429      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5430        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5431                           cast<CXXMethodDecl>(FD)->getParent(),
5432                           Args[0]->getType(), Args[0]->Classify(Context),
5433                           Args.slice(1), CandidateSet,
5434                           SuppressUserConversions);
5435      else
5436        AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5437                             SuppressUserConversions);
5438    } else {
5439      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5440      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5441          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5442        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5443                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5444                                   ExplicitTemplateArgs,
5445                                   Args[0]->getType(),
5446                                   Args[0]->Classify(Context), Args.slice(1),
5447                                   CandidateSet, SuppressUserConversions);
5448      else
5449        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5450                                     ExplicitTemplateArgs, Args,
5451                                     CandidateSet, SuppressUserConversions);
5452    }
5453  }
5454}
5455
5456/// AddMethodCandidate - Adds a named decl (which is some kind of
5457/// method) as a method candidate to the given overload set.
5458void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5459                              QualType ObjectType,
5460                              Expr::Classification ObjectClassification,
5461                              Expr **Args, unsigned NumArgs,
5462                              OverloadCandidateSet& CandidateSet,
5463                              bool SuppressUserConversions) {
5464  NamedDecl *Decl = FoundDecl.getDecl();
5465  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5466
5467  if (isa<UsingShadowDecl>(Decl))
5468    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5469
5470  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5471    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5472           "Expected a member function template");
5473    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5474                               /*ExplicitArgs*/ 0,
5475                               ObjectType, ObjectClassification,
5476                               llvm::makeArrayRef(Args, NumArgs), CandidateSet,
5477                               SuppressUserConversions);
5478  } else {
5479    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5480                       ObjectType, ObjectClassification,
5481                       llvm::makeArrayRef(Args, NumArgs),
5482                       CandidateSet, SuppressUserConversions);
5483  }
5484}
5485
5486/// AddMethodCandidate - Adds the given C++ member function to the set
5487/// of candidate functions, using the given function call arguments
5488/// and the object argument (@c Object). For example, in a call
5489/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5490/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5491/// allow user-defined conversions via constructors or conversion
5492/// operators.
5493void
5494Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5495                         CXXRecordDecl *ActingContext, QualType ObjectType,
5496                         Expr::Classification ObjectClassification,
5497                         ArrayRef<Expr *> Args,
5498                         OverloadCandidateSet& CandidateSet,
5499                         bool SuppressUserConversions) {
5500  const FunctionProtoType* Proto
5501    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5502  assert(Proto && "Methods without a prototype cannot be overloaded");
5503  assert(!isa<CXXConstructorDecl>(Method) &&
5504         "Use AddOverloadCandidate for constructors");
5505
5506  if (!CandidateSet.isNewCandidate(Method))
5507    return;
5508
5509  // Overload resolution is always an unevaluated context.
5510  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5511
5512  // Add this candidate
5513  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5514  Candidate.FoundDecl = FoundDecl;
5515  Candidate.Function = Method;
5516  Candidate.IsSurrogate = false;
5517  Candidate.IgnoreObjectArgument = false;
5518  Candidate.ExplicitCallArguments = Args.size();
5519
5520  unsigned NumArgsInProto = Proto->getNumArgs();
5521
5522  // (C++ 13.3.2p2): A candidate function having fewer than m
5523  // parameters is viable only if it has an ellipsis in its parameter
5524  // list (8.3.5).
5525  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5526    Candidate.Viable = false;
5527    Candidate.FailureKind = ovl_fail_too_many_arguments;
5528    return;
5529  }
5530
5531  // (C++ 13.3.2p2): A candidate function having more than m parameters
5532  // is viable only if the (m+1)st parameter has a default argument
5533  // (8.3.6). For the purposes of overload resolution, the
5534  // parameter list is truncated on the right, so that there are
5535  // exactly m parameters.
5536  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5537  if (Args.size() < MinRequiredArgs) {
5538    // Not enough arguments.
5539    Candidate.Viable = false;
5540    Candidate.FailureKind = ovl_fail_too_few_arguments;
5541    return;
5542  }
5543
5544  Candidate.Viable = true;
5545
5546  if (Method->isStatic() || ObjectType.isNull())
5547    // The implicit object argument is ignored.
5548    Candidate.IgnoreObjectArgument = true;
5549  else {
5550    // Determine the implicit conversion sequence for the object
5551    // parameter.
5552    Candidate.Conversions[0]
5553      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5554                                        Method, ActingContext);
5555    if (Candidate.Conversions[0].isBad()) {
5556      Candidate.Viable = false;
5557      Candidate.FailureKind = ovl_fail_bad_conversion;
5558      return;
5559    }
5560  }
5561
5562  // Determine the implicit conversion sequences for each of the
5563  // arguments.
5564  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5565    if (ArgIdx < NumArgsInProto) {
5566      // (C++ 13.3.2p3): for F to be a viable function, there shall
5567      // exist for each argument an implicit conversion sequence
5568      // (13.3.3.1) that converts that argument to the corresponding
5569      // parameter of F.
5570      QualType ParamType = Proto->getArgType(ArgIdx);
5571      Candidate.Conversions[ArgIdx + 1]
5572        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5573                                SuppressUserConversions,
5574                                /*InOverloadResolution=*/true,
5575                                /*AllowObjCWritebackConversion=*/
5576                                  getLangOpts().ObjCAutoRefCount);
5577      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5578        Candidate.Viable = false;
5579        Candidate.FailureKind = ovl_fail_bad_conversion;
5580        break;
5581      }
5582    } else {
5583      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5584      // argument for which there is no corresponding parameter is
5585      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5586      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5587    }
5588  }
5589}
5590
5591/// \brief Add a C++ member function template as a candidate to the candidate
5592/// set, using template argument deduction to produce an appropriate member
5593/// function template specialization.
5594void
5595Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5596                                 DeclAccessPair FoundDecl,
5597                                 CXXRecordDecl *ActingContext,
5598                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5599                                 QualType ObjectType,
5600                                 Expr::Classification ObjectClassification,
5601                                 ArrayRef<Expr *> Args,
5602                                 OverloadCandidateSet& CandidateSet,
5603                                 bool SuppressUserConversions) {
5604  if (!CandidateSet.isNewCandidate(MethodTmpl))
5605    return;
5606
5607  // C++ [over.match.funcs]p7:
5608  //   In each case where a candidate is a function template, candidate
5609  //   function template specializations are generated using template argument
5610  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5611  //   candidate functions in the usual way.113) A given name can refer to one
5612  //   or more function templates and also to a set of overloaded non-template
5613  //   functions. In such a case, the candidate functions generated from each
5614  //   function template are combined with the set of non-template candidate
5615  //   functions.
5616  TemplateDeductionInfo Info(CandidateSet.getLocation());
5617  FunctionDecl *Specialization = 0;
5618  if (TemplateDeductionResult Result
5619      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5620                                Specialization, Info)) {
5621    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5622    Candidate.FoundDecl = FoundDecl;
5623    Candidate.Function = MethodTmpl->getTemplatedDecl();
5624    Candidate.Viable = false;
5625    Candidate.FailureKind = ovl_fail_bad_deduction;
5626    Candidate.IsSurrogate = false;
5627    Candidate.IgnoreObjectArgument = false;
5628    Candidate.ExplicitCallArguments = Args.size();
5629    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5630                                                          Info);
5631    return;
5632  }
5633
5634  // Add the function template specialization produced by template argument
5635  // deduction as a candidate.
5636  assert(Specialization && "Missing member function template specialization?");
5637  assert(isa<CXXMethodDecl>(Specialization) &&
5638         "Specialization is not a member function?");
5639  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5640                     ActingContext, ObjectType, ObjectClassification, Args,
5641                     CandidateSet, SuppressUserConversions);
5642}
5643
5644/// \brief Add a C++ function template specialization as a candidate
5645/// in the candidate set, using template argument deduction to produce
5646/// an appropriate function template specialization.
5647void
5648Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5649                                   DeclAccessPair FoundDecl,
5650                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5651                                   ArrayRef<Expr *> Args,
5652                                   OverloadCandidateSet& CandidateSet,
5653                                   bool SuppressUserConversions) {
5654  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5655    return;
5656
5657  // C++ [over.match.funcs]p7:
5658  //   In each case where a candidate is a function template, candidate
5659  //   function template specializations are generated using template argument
5660  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5661  //   candidate functions in the usual way.113) A given name can refer to one
5662  //   or more function templates and also to a set of overloaded non-template
5663  //   functions. In such a case, the candidate functions generated from each
5664  //   function template are combined with the set of non-template candidate
5665  //   functions.
5666  TemplateDeductionInfo Info(CandidateSet.getLocation());
5667  FunctionDecl *Specialization = 0;
5668  if (TemplateDeductionResult Result
5669        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5670                                  Specialization, Info)) {
5671    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5672    Candidate.FoundDecl = FoundDecl;
5673    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5674    Candidate.Viable = false;
5675    Candidate.FailureKind = ovl_fail_bad_deduction;
5676    Candidate.IsSurrogate = false;
5677    Candidate.IgnoreObjectArgument = false;
5678    Candidate.ExplicitCallArguments = Args.size();
5679    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5680                                                          Info);
5681    return;
5682  }
5683
5684  // Add the function template specialization produced by template argument
5685  // deduction as a candidate.
5686  assert(Specialization && "Missing function template specialization?");
5687  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5688                       SuppressUserConversions);
5689}
5690
5691/// AddConversionCandidate - Add a C++ conversion function as a
5692/// candidate in the candidate set (C++ [over.match.conv],
5693/// C++ [over.match.copy]). From is the expression we're converting from,
5694/// and ToType is the type that we're eventually trying to convert to
5695/// (which may or may not be the same type as the type that the
5696/// conversion function produces).
5697void
5698Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5699                             DeclAccessPair FoundDecl,
5700                             CXXRecordDecl *ActingContext,
5701                             Expr *From, QualType ToType,
5702                             OverloadCandidateSet& CandidateSet) {
5703  assert(!Conversion->getDescribedFunctionTemplate() &&
5704         "Conversion function templates use AddTemplateConversionCandidate");
5705  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5706  if (!CandidateSet.isNewCandidate(Conversion))
5707    return;
5708
5709  // Overload resolution is always an unevaluated context.
5710  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5711
5712  // Add this candidate
5713  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5714  Candidate.FoundDecl = FoundDecl;
5715  Candidate.Function = Conversion;
5716  Candidate.IsSurrogate = false;
5717  Candidate.IgnoreObjectArgument = false;
5718  Candidate.FinalConversion.setAsIdentityConversion();
5719  Candidate.FinalConversion.setFromType(ConvType);
5720  Candidate.FinalConversion.setAllToTypes(ToType);
5721  Candidate.Viable = true;
5722  Candidate.ExplicitCallArguments = 1;
5723
5724  // C++ [over.match.funcs]p4:
5725  //   For conversion functions, the function is considered to be a member of
5726  //   the class of the implicit implied object argument for the purpose of
5727  //   defining the type of the implicit object parameter.
5728  //
5729  // Determine the implicit conversion sequence for the implicit
5730  // object parameter.
5731  QualType ImplicitParamType = From->getType();
5732  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5733    ImplicitParamType = FromPtrType->getPointeeType();
5734  CXXRecordDecl *ConversionContext
5735    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5736
5737  Candidate.Conversions[0]
5738    = TryObjectArgumentInitialization(*this, From->getType(),
5739                                      From->Classify(Context),
5740                                      Conversion, ConversionContext);
5741
5742  if (Candidate.Conversions[0].isBad()) {
5743    Candidate.Viable = false;
5744    Candidate.FailureKind = ovl_fail_bad_conversion;
5745    return;
5746  }
5747
5748  // We won't go through a user-define type conversion function to convert a
5749  // derived to base as such conversions are given Conversion Rank. They only
5750  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5751  QualType FromCanon
5752    = Context.getCanonicalType(From->getType().getUnqualifiedType());
5753  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5754  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5755    Candidate.Viable = false;
5756    Candidate.FailureKind = ovl_fail_trivial_conversion;
5757    return;
5758  }
5759
5760  // To determine what the conversion from the result of calling the
5761  // conversion function to the type we're eventually trying to
5762  // convert to (ToType), we need to synthesize a call to the
5763  // conversion function and attempt copy initialization from it. This
5764  // makes sure that we get the right semantics with respect to
5765  // lvalues/rvalues and the type. Fortunately, we can allocate this
5766  // call on the stack and we don't need its arguments to be
5767  // well-formed.
5768  DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5769                            VK_LValue, From->getLocStart());
5770  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5771                                Context.getPointerType(Conversion->getType()),
5772                                CK_FunctionToPointerDecay,
5773                                &ConversionRef, VK_RValue);
5774
5775  QualType ConversionType = Conversion->getConversionType();
5776  if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5777    Candidate.Viable = false;
5778    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5779    return;
5780  }
5781
5782  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5783
5784  // Note that it is safe to allocate CallExpr on the stack here because
5785  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5786  // allocator).
5787  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5788  CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
5789                From->getLocStart());
5790  ImplicitConversionSequence ICS =
5791    TryCopyInitialization(*this, &Call, ToType,
5792                          /*SuppressUserConversions=*/true,
5793                          /*InOverloadResolution=*/false,
5794                          /*AllowObjCWritebackConversion=*/false);
5795
5796  switch (ICS.getKind()) {
5797  case ImplicitConversionSequence::StandardConversion:
5798    Candidate.FinalConversion = ICS.Standard;
5799
5800    // C++ [over.ics.user]p3:
5801    //   If the user-defined conversion is specified by a specialization of a
5802    //   conversion function template, the second standard conversion sequence
5803    //   shall have exact match rank.
5804    if (Conversion->getPrimaryTemplate() &&
5805        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5806      Candidate.Viable = false;
5807      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5808    }
5809
5810    // C++0x [dcl.init.ref]p5:
5811    //    In the second case, if the reference is an rvalue reference and
5812    //    the second standard conversion sequence of the user-defined
5813    //    conversion sequence includes an lvalue-to-rvalue conversion, the
5814    //    program is ill-formed.
5815    if (ToType->isRValueReferenceType() &&
5816        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5817      Candidate.Viable = false;
5818      Candidate.FailureKind = ovl_fail_bad_final_conversion;
5819    }
5820    break;
5821
5822  case ImplicitConversionSequence::BadConversion:
5823    Candidate.Viable = false;
5824    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5825    break;
5826
5827  default:
5828    llvm_unreachable(
5829           "Can only end up with a standard conversion sequence or failure");
5830  }
5831}
5832
5833/// \brief Adds a conversion function template specialization
5834/// candidate to the overload set, using template argument deduction
5835/// to deduce the template arguments of the conversion function
5836/// template from the type that we are converting to (C++
5837/// [temp.deduct.conv]).
5838void
5839Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5840                                     DeclAccessPair FoundDecl,
5841                                     CXXRecordDecl *ActingDC,
5842                                     Expr *From, QualType ToType,
5843                                     OverloadCandidateSet &CandidateSet) {
5844  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5845         "Only conversion function templates permitted here");
5846
5847  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5848    return;
5849
5850  TemplateDeductionInfo Info(CandidateSet.getLocation());
5851  CXXConversionDecl *Specialization = 0;
5852  if (TemplateDeductionResult Result
5853        = DeduceTemplateArguments(FunctionTemplate, ToType,
5854                                  Specialization, Info)) {
5855    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5856    Candidate.FoundDecl = FoundDecl;
5857    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5858    Candidate.Viable = false;
5859    Candidate.FailureKind = ovl_fail_bad_deduction;
5860    Candidate.IsSurrogate = false;
5861    Candidate.IgnoreObjectArgument = false;
5862    Candidate.ExplicitCallArguments = 1;
5863    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5864                                                          Info);
5865    return;
5866  }
5867
5868  // Add the conversion function template specialization produced by
5869  // template argument deduction as a candidate.
5870  assert(Specialization && "Missing function template specialization?");
5871  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5872                         CandidateSet);
5873}
5874
5875/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5876/// converts the given @c Object to a function pointer via the
5877/// conversion function @c Conversion, and then attempts to call it
5878/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5879/// the type of function that we'll eventually be calling.
5880void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5881                                 DeclAccessPair FoundDecl,
5882                                 CXXRecordDecl *ActingContext,
5883                                 const FunctionProtoType *Proto,
5884                                 Expr *Object,
5885                                 ArrayRef<Expr *> Args,
5886                                 OverloadCandidateSet& CandidateSet) {
5887  if (!CandidateSet.isNewCandidate(Conversion))
5888    return;
5889
5890  // Overload resolution is always an unevaluated context.
5891  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5892
5893  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5894  Candidate.FoundDecl = FoundDecl;
5895  Candidate.Function = 0;
5896  Candidate.Surrogate = Conversion;
5897  Candidate.Viable = true;
5898  Candidate.IsSurrogate = true;
5899  Candidate.IgnoreObjectArgument = false;
5900  Candidate.ExplicitCallArguments = Args.size();
5901
5902  // Determine the implicit conversion sequence for the implicit
5903  // object parameter.
5904  ImplicitConversionSequence ObjectInit
5905    = TryObjectArgumentInitialization(*this, Object->getType(),
5906                                      Object->Classify(Context),
5907                                      Conversion, ActingContext);
5908  if (ObjectInit.isBad()) {
5909    Candidate.Viable = false;
5910    Candidate.FailureKind = ovl_fail_bad_conversion;
5911    Candidate.Conversions[0] = ObjectInit;
5912    return;
5913  }
5914
5915  // The first conversion is actually a user-defined conversion whose
5916  // first conversion is ObjectInit's standard conversion (which is
5917  // effectively a reference binding). Record it as such.
5918  Candidate.Conversions[0].setUserDefined();
5919  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
5920  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
5921  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
5922  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
5923  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
5924  Candidate.Conversions[0].UserDefined.After
5925    = Candidate.Conversions[0].UserDefined.Before;
5926  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5927
5928  // Find the
5929  unsigned NumArgsInProto = Proto->getNumArgs();
5930
5931  // (C++ 13.3.2p2): A candidate function having fewer than m
5932  // parameters is viable only if it has an ellipsis in its parameter
5933  // list (8.3.5).
5934  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5935    Candidate.Viable = false;
5936    Candidate.FailureKind = ovl_fail_too_many_arguments;
5937    return;
5938  }
5939
5940  // Function types don't have any default arguments, so just check if
5941  // we have enough arguments.
5942  if (Args.size() < NumArgsInProto) {
5943    // Not enough arguments.
5944    Candidate.Viable = false;
5945    Candidate.FailureKind = ovl_fail_too_few_arguments;
5946    return;
5947  }
5948
5949  // Determine the implicit conversion sequences for each of the
5950  // arguments.
5951  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5952    if (ArgIdx < NumArgsInProto) {
5953      // (C++ 13.3.2p3): for F to be a viable function, there shall
5954      // exist for each argument an implicit conversion sequence
5955      // (13.3.3.1) that converts that argument to the corresponding
5956      // parameter of F.
5957      QualType ParamType = Proto->getArgType(ArgIdx);
5958      Candidate.Conversions[ArgIdx + 1]
5959        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5960                                /*SuppressUserConversions=*/false,
5961                                /*InOverloadResolution=*/false,
5962                                /*AllowObjCWritebackConversion=*/
5963                                  getLangOpts().ObjCAutoRefCount);
5964      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5965        Candidate.Viable = false;
5966        Candidate.FailureKind = ovl_fail_bad_conversion;
5967        break;
5968      }
5969    } else {
5970      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5971      // argument for which there is no corresponding parameter is
5972      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5973      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5974    }
5975  }
5976}
5977
5978/// \brief Add overload candidates for overloaded operators that are
5979/// member functions.
5980///
5981/// Add the overloaded operator candidates that are member functions
5982/// for the operator Op that was used in an operator expression such
5983/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5984/// CandidateSet will store the added overload candidates. (C++
5985/// [over.match.oper]).
5986void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5987                                       SourceLocation OpLoc,
5988                                       Expr **Args, unsigned NumArgs,
5989                                       OverloadCandidateSet& CandidateSet,
5990                                       SourceRange OpRange) {
5991  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5992
5993  // C++ [over.match.oper]p3:
5994  //   For a unary operator @ with an operand of a type whose
5995  //   cv-unqualified version is T1, and for a binary operator @ with
5996  //   a left operand of a type whose cv-unqualified version is T1 and
5997  //   a right operand of a type whose cv-unqualified version is T2,
5998  //   three sets of candidate functions, designated member
5999  //   candidates, non-member candidates and built-in candidates, are
6000  //   constructed as follows:
6001  QualType T1 = Args[0]->getType();
6002
6003  //     -- If T1 is a class type, the set of member candidates is the
6004  //        result of the qualified lookup of T1::operator@
6005  //        (13.3.1.1.1); otherwise, the set of member candidates is
6006  //        empty.
6007  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6008    // Complete the type if it can be completed. Otherwise, we're done.
6009    if (RequireCompleteType(OpLoc, T1, 0))
6010      return;
6011
6012    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6013    LookupQualifiedName(Operators, T1Rec->getDecl());
6014    Operators.suppressDiagnostics();
6015
6016    for (LookupResult::iterator Oper = Operators.begin(),
6017                             OperEnd = Operators.end();
6018         Oper != OperEnd;
6019         ++Oper)
6020      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6021                         Args[0]->Classify(Context), Args + 1, NumArgs - 1,
6022                         CandidateSet,
6023                         /* SuppressUserConversions = */ false);
6024  }
6025}
6026
6027/// AddBuiltinCandidate - Add a candidate for a built-in
6028/// operator. ResultTy and ParamTys are the result and parameter types
6029/// of the built-in candidate, respectively. Args and NumArgs are the
6030/// arguments being passed to the candidate. IsAssignmentOperator
6031/// should be true when this built-in candidate is an assignment
6032/// operator. NumContextualBoolArguments is the number of arguments
6033/// (at the beginning of the argument list) that will be contextually
6034/// converted to bool.
6035void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6036                               Expr **Args, unsigned NumArgs,
6037                               OverloadCandidateSet& CandidateSet,
6038                               bool IsAssignmentOperator,
6039                               unsigned NumContextualBoolArguments) {
6040  // Overload resolution is always an unevaluated context.
6041  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6042
6043  // Add this candidate
6044  OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
6045  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
6046  Candidate.Function = 0;
6047  Candidate.IsSurrogate = false;
6048  Candidate.IgnoreObjectArgument = false;
6049  Candidate.BuiltinTypes.ResultTy = ResultTy;
6050  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6051    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6052
6053  // Determine the implicit conversion sequences for each of the
6054  // arguments.
6055  Candidate.Viable = true;
6056  Candidate.ExplicitCallArguments = NumArgs;
6057  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6058    // C++ [over.match.oper]p4:
6059    //   For the built-in assignment operators, conversions of the
6060    //   left operand are restricted as follows:
6061    //     -- no temporaries are introduced to hold the left operand, and
6062    //     -- no user-defined conversions are applied to the left
6063    //        operand to achieve a type match with the left-most
6064    //        parameter of a built-in candidate.
6065    //
6066    // We block these conversions by turning off user-defined
6067    // conversions, since that is the only way that initialization of
6068    // a reference to a non-class type can occur from something that
6069    // is not of the same type.
6070    if (ArgIdx < NumContextualBoolArguments) {
6071      assert(ParamTys[ArgIdx] == Context.BoolTy &&
6072             "Contextual conversion to bool requires bool type");
6073      Candidate.Conversions[ArgIdx]
6074        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6075    } else {
6076      Candidate.Conversions[ArgIdx]
6077        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6078                                ArgIdx == 0 && IsAssignmentOperator,
6079                                /*InOverloadResolution=*/false,
6080                                /*AllowObjCWritebackConversion=*/
6081                                  getLangOpts().ObjCAutoRefCount);
6082    }
6083    if (Candidate.Conversions[ArgIdx].isBad()) {
6084      Candidate.Viable = false;
6085      Candidate.FailureKind = ovl_fail_bad_conversion;
6086      break;
6087    }
6088  }
6089}
6090
6091/// BuiltinCandidateTypeSet - A set of types that will be used for the
6092/// candidate operator functions for built-in operators (C++
6093/// [over.built]). The types are separated into pointer types and
6094/// enumeration types.
6095class BuiltinCandidateTypeSet  {
6096  /// TypeSet - A set of types.
6097  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6098
6099  /// PointerTypes - The set of pointer types that will be used in the
6100  /// built-in candidates.
6101  TypeSet PointerTypes;
6102
6103  /// MemberPointerTypes - The set of member pointer types that will be
6104  /// used in the built-in candidates.
6105  TypeSet MemberPointerTypes;
6106
6107  /// EnumerationTypes - The set of enumeration types that will be
6108  /// used in the built-in candidates.
6109  TypeSet EnumerationTypes;
6110
6111  /// \brief The set of vector types that will be used in the built-in
6112  /// candidates.
6113  TypeSet VectorTypes;
6114
6115  /// \brief A flag indicating non-record types are viable candidates
6116  bool HasNonRecordTypes;
6117
6118  /// \brief A flag indicating whether either arithmetic or enumeration types
6119  /// were present in the candidate set.
6120  bool HasArithmeticOrEnumeralTypes;
6121
6122  /// \brief A flag indicating whether the nullptr type was present in the
6123  /// candidate set.
6124  bool HasNullPtrType;
6125
6126  /// Sema - The semantic analysis instance where we are building the
6127  /// candidate type set.
6128  Sema &SemaRef;
6129
6130  /// Context - The AST context in which we will build the type sets.
6131  ASTContext &Context;
6132
6133  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6134                                               const Qualifiers &VisibleQuals);
6135  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6136
6137public:
6138  /// iterator - Iterates through the types that are part of the set.
6139  typedef TypeSet::iterator iterator;
6140
6141  BuiltinCandidateTypeSet(Sema &SemaRef)
6142    : HasNonRecordTypes(false),
6143      HasArithmeticOrEnumeralTypes(false),
6144      HasNullPtrType(false),
6145      SemaRef(SemaRef),
6146      Context(SemaRef.Context) { }
6147
6148  void AddTypesConvertedFrom(QualType Ty,
6149                             SourceLocation Loc,
6150                             bool AllowUserConversions,
6151                             bool AllowExplicitConversions,
6152                             const Qualifiers &VisibleTypeConversionsQuals);
6153
6154  /// pointer_begin - First pointer type found;
6155  iterator pointer_begin() { return PointerTypes.begin(); }
6156
6157  /// pointer_end - Past the last pointer type found;
6158  iterator pointer_end() { return PointerTypes.end(); }
6159
6160  /// member_pointer_begin - First member pointer type found;
6161  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6162
6163  /// member_pointer_end - Past the last member pointer type found;
6164  iterator member_pointer_end() { return MemberPointerTypes.end(); }
6165
6166  /// enumeration_begin - First enumeration type found;
6167  iterator enumeration_begin() { return EnumerationTypes.begin(); }
6168
6169  /// enumeration_end - Past the last enumeration type found;
6170  iterator enumeration_end() { return EnumerationTypes.end(); }
6171
6172  iterator vector_begin() { return VectorTypes.begin(); }
6173  iterator vector_end() { return VectorTypes.end(); }
6174
6175  bool hasNonRecordTypes() { return HasNonRecordTypes; }
6176  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6177  bool hasNullPtrType() const { return HasNullPtrType; }
6178};
6179
6180/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6181/// the set of pointer types along with any more-qualified variants of
6182/// that type. For example, if @p Ty is "int const *", this routine
6183/// will add "int const *", "int const volatile *", "int const
6184/// restrict *", and "int const volatile restrict *" to the set of
6185/// pointer types. Returns true if the add of @p Ty itself succeeded,
6186/// false otherwise.
6187///
6188/// FIXME: what to do about extended qualifiers?
6189bool
6190BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6191                                             const Qualifiers &VisibleQuals) {
6192
6193  // Insert this type.
6194  if (!PointerTypes.insert(Ty))
6195    return false;
6196
6197  QualType PointeeTy;
6198  const PointerType *PointerTy = Ty->getAs<PointerType>();
6199  bool buildObjCPtr = false;
6200  if (!PointerTy) {
6201    const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6202    PointeeTy = PTy->getPointeeType();
6203    buildObjCPtr = true;
6204  } else {
6205    PointeeTy = PointerTy->getPointeeType();
6206  }
6207
6208  // Don't add qualified variants of arrays. For one, they're not allowed
6209  // (the qualifier would sink to the element type), and for another, the
6210  // only overload situation where it matters is subscript or pointer +- int,
6211  // and those shouldn't have qualifier variants anyway.
6212  if (PointeeTy->isArrayType())
6213    return true;
6214
6215  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6216  bool hasVolatile = VisibleQuals.hasVolatile();
6217  bool hasRestrict = VisibleQuals.hasRestrict();
6218
6219  // Iterate through all strict supersets of BaseCVR.
6220  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6221    if ((CVR | BaseCVR) != CVR) continue;
6222    // Skip over volatile if no volatile found anywhere in the types.
6223    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6224
6225    // Skip over restrict if no restrict found anywhere in the types, or if
6226    // the type cannot be restrict-qualified.
6227    if ((CVR & Qualifiers::Restrict) &&
6228        (!hasRestrict ||
6229         (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6230      continue;
6231
6232    // Build qualified pointee type.
6233    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6234
6235    // Build qualified pointer type.
6236    QualType QPointerTy;
6237    if (!buildObjCPtr)
6238      QPointerTy = Context.getPointerType(QPointeeTy);
6239    else
6240      QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6241
6242    // Insert qualified pointer type.
6243    PointerTypes.insert(QPointerTy);
6244  }
6245
6246  return true;
6247}
6248
6249/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6250/// to the set of pointer types along with any more-qualified variants of
6251/// that type. For example, if @p Ty is "int const *", this routine
6252/// will add "int const *", "int const volatile *", "int const
6253/// restrict *", and "int const volatile restrict *" to the set of
6254/// pointer types. Returns true if the add of @p Ty itself succeeded,
6255/// false otherwise.
6256///
6257/// FIXME: what to do about extended qualifiers?
6258bool
6259BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6260    QualType Ty) {
6261  // Insert this type.
6262  if (!MemberPointerTypes.insert(Ty))
6263    return false;
6264
6265  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6266  assert(PointerTy && "type was not a member pointer type!");
6267
6268  QualType PointeeTy = PointerTy->getPointeeType();
6269  // Don't add qualified variants of arrays. For one, they're not allowed
6270  // (the qualifier would sink to the element type), and for another, the
6271  // only overload situation where it matters is subscript or pointer +- int,
6272  // and those shouldn't have qualifier variants anyway.
6273  if (PointeeTy->isArrayType())
6274    return true;
6275  const Type *ClassTy = PointerTy->getClass();
6276
6277  // Iterate through all strict supersets of the pointee type's CVR
6278  // qualifiers.
6279  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6280  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6281    if ((CVR | BaseCVR) != CVR) continue;
6282
6283    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6284    MemberPointerTypes.insert(
6285      Context.getMemberPointerType(QPointeeTy, ClassTy));
6286  }
6287
6288  return true;
6289}
6290
6291/// AddTypesConvertedFrom - Add each of the types to which the type @p
6292/// Ty can be implicit converted to the given set of @p Types. We're
6293/// primarily interested in pointer types and enumeration types. We also
6294/// take member pointer types, for the conditional operator.
6295/// AllowUserConversions is true if we should look at the conversion
6296/// functions of a class type, and AllowExplicitConversions if we
6297/// should also include the explicit conversion functions of a class
6298/// type.
6299void
6300BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6301                                               SourceLocation Loc,
6302                                               bool AllowUserConversions,
6303                                               bool AllowExplicitConversions,
6304                                               const Qualifiers &VisibleQuals) {
6305  // Only deal with canonical types.
6306  Ty = Context.getCanonicalType(Ty);
6307
6308  // Look through reference types; they aren't part of the type of an
6309  // expression for the purposes of conversions.
6310  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6311    Ty = RefTy->getPointeeType();
6312
6313  // If we're dealing with an array type, decay to the pointer.
6314  if (Ty->isArrayType())
6315    Ty = SemaRef.Context.getArrayDecayedType(Ty);
6316
6317  // Otherwise, we don't care about qualifiers on the type.
6318  Ty = Ty.getLocalUnqualifiedType();
6319
6320  // Flag if we ever add a non-record type.
6321  const RecordType *TyRec = Ty->getAs<RecordType>();
6322  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6323
6324  // Flag if we encounter an arithmetic type.
6325  HasArithmeticOrEnumeralTypes =
6326    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6327
6328  if (Ty->isObjCIdType() || Ty->isObjCClassType())
6329    PointerTypes.insert(Ty);
6330  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6331    // Insert our type, and its more-qualified variants, into the set
6332    // of types.
6333    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6334      return;
6335  } else if (Ty->isMemberPointerType()) {
6336    // Member pointers are far easier, since the pointee can't be converted.
6337    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6338      return;
6339  } else if (Ty->isEnumeralType()) {
6340    HasArithmeticOrEnumeralTypes = true;
6341    EnumerationTypes.insert(Ty);
6342  } else if (Ty->isVectorType()) {
6343    // We treat vector types as arithmetic types in many contexts as an
6344    // extension.
6345    HasArithmeticOrEnumeralTypes = true;
6346    VectorTypes.insert(Ty);
6347  } else if (Ty->isNullPtrType()) {
6348    HasNullPtrType = true;
6349  } else if (AllowUserConversions && TyRec) {
6350    // No conversion functions in incomplete types.
6351    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6352      return;
6353
6354    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6355    std::pair<CXXRecordDecl::conversion_iterator,
6356              CXXRecordDecl::conversion_iterator>
6357      Conversions = ClassDecl->getVisibleConversionFunctions();
6358    for (CXXRecordDecl::conversion_iterator
6359           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6360      NamedDecl *D = I.getDecl();
6361      if (isa<UsingShadowDecl>(D))
6362        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6363
6364      // Skip conversion function templates; they don't tell us anything
6365      // about which builtin types we can convert to.
6366      if (isa<FunctionTemplateDecl>(D))
6367        continue;
6368
6369      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6370      if (AllowExplicitConversions || !Conv->isExplicit()) {
6371        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6372                              VisibleQuals);
6373      }
6374    }
6375  }
6376}
6377
6378/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6379/// the volatile- and non-volatile-qualified assignment operators for the
6380/// given type to the candidate set.
6381static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6382                                                   QualType T,
6383                                                   Expr **Args,
6384                                                   unsigned NumArgs,
6385                                    OverloadCandidateSet &CandidateSet) {
6386  QualType ParamTypes[2];
6387
6388  // T& operator=(T&, T)
6389  ParamTypes[0] = S.Context.getLValueReferenceType(T);
6390  ParamTypes[1] = T;
6391  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6392                        /*IsAssignmentOperator=*/true);
6393
6394  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6395    // volatile T& operator=(volatile T&, T)
6396    ParamTypes[0]
6397      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6398    ParamTypes[1] = T;
6399    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6400                          /*IsAssignmentOperator=*/true);
6401  }
6402}
6403
6404/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6405/// if any, found in visible type conversion functions found in ArgExpr's type.
6406static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6407    Qualifiers VRQuals;
6408    const RecordType *TyRec;
6409    if (const MemberPointerType *RHSMPType =
6410        ArgExpr->getType()->getAs<MemberPointerType>())
6411      TyRec = RHSMPType->getClass()->getAs<RecordType>();
6412    else
6413      TyRec = ArgExpr->getType()->getAs<RecordType>();
6414    if (!TyRec) {
6415      // Just to be safe, assume the worst case.
6416      VRQuals.addVolatile();
6417      VRQuals.addRestrict();
6418      return VRQuals;
6419    }
6420
6421    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6422    if (!ClassDecl->hasDefinition())
6423      return VRQuals;
6424
6425    std::pair<CXXRecordDecl::conversion_iterator,
6426              CXXRecordDecl::conversion_iterator>
6427      Conversions = ClassDecl->getVisibleConversionFunctions();
6428
6429    for (CXXRecordDecl::conversion_iterator
6430           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6431      NamedDecl *D = I.getDecl();
6432      if (isa<UsingShadowDecl>(D))
6433        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6434      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6435        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6436        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6437          CanTy = ResTypeRef->getPointeeType();
6438        // Need to go down the pointer/mempointer chain and add qualifiers
6439        // as see them.
6440        bool done = false;
6441        while (!done) {
6442          if (CanTy.isRestrictQualified())
6443            VRQuals.addRestrict();
6444          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6445            CanTy = ResTypePtr->getPointeeType();
6446          else if (const MemberPointerType *ResTypeMPtr =
6447                CanTy->getAs<MemberPointerType>())
6448            CanTy = ResTypeMPtr->getPointeeType();
6449          else
6450            done = true;
6451          if (CanTy.isVolatileQualified())
6452            VRQuals.addVolatile();
6453          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6454            return VRQuals;
6455        }
6456      }
6457    }
6458    return VRQuals;
6459}
6460
6461namespace {
6462
6463/// \brief Helper class to manage the addition of builtin operator overload
6464/// candidates. It provides shared state and utility methods used throughout
6465/// the process, as well as a helper method to add each group of builtin
6466/// operator overloads from the standard to a candidate set.
6467class BuiltinOperatorOverloadBuilder {
6468  // Common instance state available to all overload candidate addition methods.
6469  Sema &S;
6470  Expr **Args;
6471  unsigned NumArgs;
6472  Qualifiers VisibleTypeConversionsQuals;
6473  bool HasArithmeticOrEnumeralCandidateType;
6474  SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6475  OverloadCandidateSet &CandidateSet;
6476
6477  // Define some constants used to index and iterate over the arithemetic types
6478  // provided via the getArithmeticType() method below.
6479  // The "promoted arithmetic types" are the arithmetic
6480  // types are that preserved by promotion (C++ [over.built]p2).
6481  static const unsigned FirstIntegralType = 3;
6482  static const unsigned LastIntegralType = 20;
6483  static const unsigned FirstPromotedIntegralType = 3,
6484                        LastPromotedIntegralType = 11;
6485  static const unsigned FirstPromotedArithmeticType = 0,
6486                        LastPromotedArithmeticType = 11;
6487  static const unsigned NumArithmeticTypes = 20;
6488
6489  /// \brief Get the canonical type for a given arithmetic type index.
6490  CanQualType getArithmeticType(unsigned index) {
6491    assert(index < NumArithmeticTypes);
6492    static CanQualType ASTContext::* const
6493      ArithmeticTypes[NumArithmeticTypes] = {
6494      // Start of promoted types.
6495      &ASTContext::FloatTy,
6496      &ASTContext::DoubleTy,
6497      &ASTContext::LongDoubleTy,
6498
6499      // Start of integral types.
6500      &ASTContext::IntTy,
6501      &ASTContext::LongTy,
6502      &ASTContext::LongLongTy,
6503      &ASTContext::Int128Ty,
6504      &ASTContext::UnsignedIntTy,
6505      &ASTContext::UnsignedLongTy,
6506      &ASTContext::UnsignedLongLongTy,
6507      &ASTContext::UnsignedInt128Ty,
6508      // End of promoted types.
6509
6510      &ASTContext::BoolTy,
6511      &ASTContext::CharTy,
6512      &ASTContext::WCharTy,
6513      &ASTContext::Char16Ty,
6514      &ASTContext::Char32Ty,
6515      &ASTContext::SignedCharTy,
6516      &ASTContext::ShortTy,
6517      &ASTContext::UnsignedCharTy,
6518      &ASTContext::UnsignedShortTy,
6519      // End of integral types.
6520      // FIXME: What about complex? What about half?
6521    };
6522    return S.Context.*ArithmeticTypes[index];
6523  }
6524
6525  /// \brief Gets the canonical type resulting from the usual arithemetic
6526  /// converions for the given arithmetic types.
6527  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6528    // Accelerator table for performing the usual arithmetic conversions.
6529    // The rules are basically:
6530    //   - if either is floating-point, use the wider floating-point
6531    //   - if same signedness, use the higher rank
6532    //   - if same size, use unsigned of the higher rank
6533    //   - use the larger type
6534    // These rules, together with the axiom that higher ranks are
6535    // never smaller, are sufficient to precompute all of these results
6536    // *except* when dealing with signed types of higher rank.
6537    // (we could precompute SLL x UI for all known platforms, but it's
6538    // better not to make any assumptions).
6539    // We assume that int128 has a higher rank than long long on all platforms.
6540    enum PromotedType {
6541            Dep=-1,
6542            Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6543    };
6544    static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6545                                        [LastPromotedArithmeticType] = {
6546/* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6547/* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6548/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6549/*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6550/*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6551/* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6552/*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6553/*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6554/*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6555/* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6556/*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6557    };
6558
6559    assert(L < LastPromotedArithmeticType);
6560    assert(R < LastPromotedArithmeticType);
6561    int Idx = ConversionsTable[L][R];
6562
6563    // Fast path: the table gives us a concrete answer.
6564    if (Idx != Dep) return getArithmeticType(Idx);
6565
6566    // Slow path: we need to compare widths.
6567    // An invariant is that the signed type has higher rank.
6568    CanQualType LT = getArithmeticType(L),
6569                RT = getArithmeticType(R);
6570    unsigned LW = S.Context.getIntWidth(LT),
6571             RW = S.Context.getIntWidth(RT);
6572
6573    // If they're different widths, use the signed type.
6574    if (LW > RW) return LT;
6575    else if (LW < RW) return RT;
6576
6577    // Otherwise, use the unsigned type of the signed type's rank.
6578    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6579    assert(L == SLL || R == SLL);
6580    return S.Context.UnsignedLongLongTy;
6581  }
6582
6583  /// \brief Helper method to factor out the common pattern of adding overloads
6584  /// for '++' and '--' builtin operators.
6585  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6586                                           bool HasVolatile,
6587                                           bool HasRestrict) {
6588    QualType ParamTypes[2] = {
6589      S.Context.getLValueReferenceType(CandidateTy),
6590      S.Context.IntTy
6591    };
6592
6593    // Non-volatile version.
6594    if (NumArgs == 1)
6595      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6596    else
6597      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6598
6599    // Use a heuristic to reduce number of builtin candidates in the set:
6600    // add volatile version only if there are conversions to a volatile type.
6601    if (HasVolatile) {
6602      ParamTypes[0] =
6603        S.Context.getLValueReferenceType(
6604          S.Context.getVolatileType(CandidateTy));
6605      if (NumArgs == 1)
6606        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6607      else
6608        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6609    }
6610
6611    // Add restrict version only if there are conversions to a restrict type
6612    // and our candidate type is a non-restrict-qualified pointer.
6613    if (HasRestrict && CandidateTy->isAnyPointerType() &&
6614        !CandidateTy.isRestrictQualified()) {
6615      ParamTypes[0]
6616        = S.Context.getLValueReferenceType(
6617            S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6618      if (NumArgs == 1)
6619        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6620      else
6621        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6622
6623      if (HasVolatile) {
6624        ParamTypes[0]
6625          = S.Context.getLValueReferenceType(
6626              S.Context.getCVRQualifiedType(CandidateTy,
6627                                            (Qualifiers::Volatile |
6628                                             Qualifiers::Restrict)));
6629        if (NumArgs == 1)
6630          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6631                                CandidateSet);
6632        else
6633          S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6634      }
6635    }
6636
6637  }
6638
6639public:
6640  BuiltinOperatorOverloadBuilder(
6641    Sema &S, Expr **Args, unsigned NumArgs,
6642    Qualifiers VisibleTypeConversionsQuals,
6643    bool HasArithmeticOrEnumeralCandidateType,
6644    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6645    OverloadCandidateSet &CandidateSet)
6646    : S(S), Args(Args), NumArgs(NumArgs),
6647      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6648      HasArithmeticOrEnumeralCandidateType(
6649        HasArithmeticOrEnumeralCandidateType),
6650      CandidateTypes(CandidateTypes),
6651      CandidateSet(CandidateSet) {
6652    // Validate some of our static helper constants in debug builds.
6653    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6654           "Invalid first promoted integral type");
6655    assert(getArithmeticType(LastPromotedIntegralType - 1)
6656             == S.Context.UnsignedInt128Ty &&
6657           "Invalid last promoted integral type");
6658    assert(getArithmeticType(FirstPromotedArithmeticType)
6659             == S.Context.FloatTy &&
6660           "Invalid first promoted arithmetic type");
6661    assert(getArithmeticType(LastPromotedArithmeticType - 1)
6662             == S.Context.UnsignedInt128Ty &&
6663           "Invalid last promoted arithmetic type");
6664  }
6665
6666  // C++ [over.built]p3:
6667  //
6668  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6669  //   is either volatile or empty, there exist candidate operator
6670  //   functions of the form
6671  //
6672  //       VQ T&      operator++(VQ T&);
6673  //       T          operator++(VQ T&, int);
6674  //
6675  // C++ [over.built]p4:
6676  //
6677  //   For every pair (T, VQ), where T is an arithmetic type other
6678  //   than bool, and VQ is either volatile or empty, there exist
6679  //   candidate operator functions of the form
6680  //
6681  //       VQ T&      operator--(VQ T&);
6682  //       T          operator--(VQ T&, int);
6683  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6684    if (!HasArithmeticOrEnumeralCandidateType)
6685      return;
6686
6687    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6688         Arith < NumArithmeticTypes; ++Arith) {
6689      addPlusPlusMinusMinusStyleOverloads(
6690        getArithmeticType(Arith),
6691        VisibleTypeConversionsQuals.hasVolatile(),
6692        VisibleTypeConversionsQuals.hasRestrict());
6693    }
6694  }
6695
6696  // C++ [over.built]p5:
6697  //
6698  //   For every pair (T, VQ), where T is a cv-qualified or
6699  //   cv-unqualified object type, and VQ is either volatile or
6700  //   empty, there exist candidate operator functions of the form
6701  //
6702  //       T*VQ&      operator++(T*VQ&);
6703  //       T*VQ&      operator--(T*VQ&);
6704  //       T*         operator++(T*VQ&, int);
6705  //       T*         operator--(T*VQ&, int);
6706  void addPlusPlusMinusMinusPointerOverloads() {
6707    for (BuiltinCandidateTypeSet::iterator
6708              Ptr = CandidateTypes[0].pointer_begin(),
6709           PtrEnd = CandidateTypes[0].pointer_end();
6710         Ptr != PtrEnd; ++Ptr) {
6711      // Skip pointer types that aren't pointers to object types.
6712      if (!(*Ptr)->getPointeeType()->isObjectType())
6713        continue;
6714
6715      addPlusPlusMinusMinusStyleOverloads(*Ptr,
6716        (!(*Ptr).isVolatileQualified() &&
6717         VisibleTypeConversionsQuals.hasVolatile()),
6718        (!(*Ptr).isRestrictQualified() &&
6719         VisibleTypeConversionsQuals.hasRestrict()));
6720    }
6721  }
6722
6723  // C++ [over.built]p6:
6724  //   For every cv-qualified or cv-unqualified object type T, there
6725  //   exist candidate operator functions of the form
6726  //
6727  //       T&         operator*(T*);
6728  //
6729  // C++ [over.built]p7:
6730  //   For every function type T that does not have cv-qualifiers or a
6731  //   ref-qualifier, there exist candidate operator functions of the form
6732  //       T&         operator*(T*);
6733  void addUnaryStarPointerOverloads() {
6734    for (BuiltinCandidateTypeSet::iterator
6735              Ptr = CandidateTypes[0].pointer_begin(),
6736           PtrEnd = CandidateTypes[0].pointer_end();
6737         Ptr != PtrEnd; ++Ptr) {
6738      QualType ParamTy = *Ptr;
6739      QualType PointeeTy = ParamTy->getPointeeType();
6740      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6741        continue;
6742
6743      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6744        if (Proto->getTypeQuals() || Proto->getRefQualifier())
6745          continue;
6746
6747      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6748                            &ParamTy, Args, 1, CandidateSet);
6749    }
6750  }
6751
6752  // C++ [over.built]p9:
6753  //  For every promoted arithmetic type T, there exist candidate
6754  //  operator functions of the form
6755  //
6756  //       T         operator+(T);
6757  //       T         operator-(T);
6758  void addUnaryPlusOrMinusArithmeticOverloads() {
6759    if (!HasArithmeticOrEnumeralCandidateType)
6760      return;
6761
6762    for (unsigned Arith = FirstPromotedArithmeticType;
6763         Arith < LastPromotedArithmeticType; ++Arith) {
6764      QualType ArithTy = getArithmeticType(Arith);
6765      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6766    }
6767
6768    // Extension: We also add these operators for vector types.
6769    for (BuiltinCandidateTypeSet::iterator
6770              Vec = CandidateTypes[0].vector_begin(),
6771           VecEnd = CandidateTypes[0].vector_end();
6772         Vec != VecEnd; ++Vec) {
6773      QualType VecTy = *Vec;
6774      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6775    }
6776  }
6777
6778  // C++ [over.built]p8:
6779  //   For every type T, there exist candidate operator functions of
6780  //   the form
6781  //
6782  //       T*         operator+(T*);
6783  void addUnaryPlusPointerOverloads() {
6784    for (BuiltinCandidateTypeSet::iterator
6785              Ptr = CandidateTypes[0].pointer_begin(),
6786           PtrEnd = CandidateTypes[0].pointer_end();
6787         Ptr != PtrEnd; ++Ptr) {
6788      QualType ParamTy = *Ptr;
6789      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6790    }
6791  }
6792
6793  // C++ [over.built]p10:
6794  //   For every promoted integral type T, there exist candidate
6795  //   operator functions of the form
6796  //
6797  //        T         operator~(T);
6798  void addUnaryTildePromotedIntegralOverloads() {
6799    if (!HasArithmeticOrEnumeralCandidateType)
6800      return;
6801
6802    for (unsigned Int = FirstPromotedIntegralType;
6803         Int < LastPromotedIntegralType; ++Int) {
6804      QualType IntTy = getArithmeticType(Int);
6805      S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6806    }
6807
6808    // Extension: We also add this operator for vector types.
6809    for (BuiltinCandidateTypeSet::iterator
6810              Vec = CandidateTypes[0].vector_begin(),
6811           VecEnd = CandidateTypes[0].vector_end();
6812         Vec != VecEnd; ++Vec) {
6813      QualType VecTy = *Vec;
6814      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6815    }
6816  }
6817
6818  // C++ [over.match.oper]p16:
6819  //   For every pointer to member type T, there exist candidate operator
6820  //   functions of the form
6821  //
6822  //        bool operator==(T,T);
6823  //        bool operator!=(T,T);
6824  void addEqualEqualOrNotEqualMemberPointerOverloads() {
6825    /// Set of (canonical) types that we've already handled.
6826    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6827
6828    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6829      for (BuiltinCandidateTypeSet::iterator
6830                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6831             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6832           MemPtr != MemPtrEnd;
6833           ++MemPtr) {
6834        // Don't add the same builtin candidate twice.
6835        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6836          continue;
6837
6838        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6839        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6840                              CandidateSet);
6841      }
6842    }
6843  }
6844
6845  // C++ [over.built]p15:
6846  //
6847  //   For every T, where T is an enumeration type, a pointer type, or
6848  //   std::nullptr_t, there exist candidate operator functions of the form
6849  //
6850  //        bool       operator<(T, T);
6851  //        bool       operator>(T, T);
6852  //        bool       operator<=(T, T);
6853  //        bool       operator>=(T, T);
6854  //        bool       operator==(T, T);
6855  //        bool       operator!=(T, T);
6856  void addRelationalPointerOrEnumeralOverloads() {
6857    // C++ [over.match.oper]p3:
6858    //   [...]the built-in candidates include all of the candidate operator
6859    //   functions defined in 13.6 that, compared to the given operator, [...]
6860    //   do not have the same parameter-type-list as any non-template non-member
6861    //   candidate.
6862    //
6863    // Note that in practice, this only affects enumeration types because there
6864    // aren't any built-in candidates of record type, and a user-defined operator
6865    // must have an operand of record or enumeration type. Also, the only other
6866    // overloaded operator with enumeration arguments, operator=,
6867    // cannot be overloaded for enumeration types, so this is the only place
6868    // where we must suppress candidates like this.
6869    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6870      UserDefinedBinaryOperators;
6871
6872    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6873      if (CandidateTypes[ArgIdx].enumeration_begin() !=
6874          CandidateTypes[ArgIdx].enumeration_end()) {
6875        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6876                                         CEnd = CandidateSet.end();
6877             C != CEnd; ++C) {
6878          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6879            continue;
6880
6881          if (C->Function->isFunctionTemplateSpecialization())
6882            continue;
6883
6884          QualType FirstParamType =
6885            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6886          QualType SecondParamType =
6887            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6888
6889          // Skip if either parameter isn't of enumeral type.
6890          if (!FirstParamType->isEnumeralType() ||
6891              !SecondParamType->isEnumeralType())
6892            continue;
6893
6894          // Add this operator to the set of known user-defined operators.
6895          UserDefinedBinaryOperators.insert(
6896            std::make_pair(S.Context.getCanonicalType(FirstParamType),
6897                           S.Context.getCanonicalType(SecondParamType)));
6898        }
6899      }
6900    }
6901
6902    /// Set of (canonical) types that we've already handled.
6903    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6904
6905    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6906      for (BuiltinCandidateTypeSet::iterator
6907                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6908             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6909           Ptr != PtrEnd; ++Ptr) {
6910        // Don't add the same builtin candidate twice.
6911        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6912          continue;
6913
6914        QualType ParamTypes[2] = { *Ptr, *Ptr };
6915        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6916                              CandidateSet);
6917      }
6918      for (BuiltinCandidateTypeSet::iterator
6919                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6920             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6921           Enum != EnumEnd; ++Enum) {
6922        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6923
6924        // Don't add the same builtin candidate twice, or if a user defined
6925        // candidate exists.
6926        if (!AddedTypes.insert(CanonType) ||
6927            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6928                                                            CanonType)))
6929          continue;
6930
6931        QualType ParamTypes[2] = { *Enum, *Enum };
6932        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6933                              CandidateSet);
6934      }
6935
6936      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6937        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6938        if (AddedTypes.insert(NullPtrTy) &&
6939            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6940                                                             NullPtrTy))) {
6941          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6942          S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6943                                CandidateSet);
6944        }
6945      }
6946    }
6947  }
6948
6949  // C++ [over.built]p13:
6950  //
6951  //   For every cv-qualified or cv-unqualified object type T
6952  //   there exist candidate operator functions of the form
6953  //
6954  //      T*         operator+(T*, ptrdiff_t);
6955  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
6956  //      T*         operator-(T*, ptrdiff_t);
6957  //      T*         operator+(ptrdiff_t, T*);
6958  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
6959  //
6960  // C++ [over.built]p14:
6961  //
6962  //   For every T, where T is a pointer to object type, there
6963  //   exist candidate operator functions of the form
6964  //
6965  //      ptrdiff_t  operator-(T, T);
6966  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6967    /// Set of (canonical) types that we've already handled.
6968    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6969
6970    for (int Arg = 0; Arg < 2; ++Arg) {
6971      QualType AsymetricParamTypes[2] = {
6972        S.Context.getPointerDiffType(),
6973        S.Context.getPointerDiffType(),
6974      };
6975      for (BuiltinCandidateTypeSet::iterator
6976                Ptr = CandidateTypes[Arg].pointer_begin(),
6977             PtrEnd = CandidateTypes[Arg].pointer_end();
6978           Ptr != PtrEnd; ++Ptr) {
6979        QualType PointeeTy = (*Ptr)->getPointeeType();
6980        if (!PointeeTy->isObjectType())
6981          continue;
6982
6983        AsymetricParamTypes[Arg] = *Ptr;
6984        if (Arg == 0 || Op == OO_Plus) {
6985          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6986          // T* operator+(ptrdiff_t, T*);
6987          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6988                                CandidateSet);
6989        }
6990        if (Op == OO_Minus) {
6991          // ptrdiff_t operator-(T, T);
6992          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6993            continue;
6994
6995          QualType ParamTypes[2] = { *Ptr, *Ptr };
6996          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6997                                Args, 2, CandidateSet);
6998        }
6999      }
7000    }
7001  }
7002
7003  // C++ [over.built]p12:
7004  //
7005  //   For every pair of promoted arithmetic types L and R, there
7006  //   exist candidate operator functions of the form
7007  //
7008  //        LR         operator*(L, R);
7009  //        LR         operator/(L, R);
7010  //        LR         operator+(L, R);
7011  //        LR         operator-(L, R);
7012  //        bool       operator<(L, R);
7013  //        bool       operator>(L, R);
7014  //        bool       operator<=(L, R);
7015  //        bool       operator>=(L, R);
7016  //        bool       operator==(L, R);
7017  //        bool       operator!=(L, R);
7018  //
7019  //   where LR is the result of the usual arithmetic conversions
7020  //   between types L and R.
7021  //
7022  // C++ [over.built]p24:
7023  //
7024  //   For every pair of promoted arithmetic types L and R, there exist
7025  //   candidate operator functions of the form
7026  //
7027  //        LR       operator?(bool, L, R);
7028  //
7029  //   where LR is the result of the usual arithmetic conversions
7030  //   between types L and R.
7031  // Our candidates ignore the first parameter.
7032  void addGenericBinaryArithmeticOverloads(bool isComparison) {
7033    if (!HasArithmeticOrEnumeralCandidateType)
7034      return;
7035
7036    for (unsigned Left = FirstPromotedArithmeticType;
7037         Left < LastPromotedArithmeticType; ++Left) {
7038      for (unsigned Right = FirstPromotedArithmeticType;
7039           Right < LastPromotedArithmeticType; ++Right) {
7040        QualType LandR[2] = { getArithmeticType(Left),
7041                              getArithmeticType(Right) };
7042        QualType Result =
7043          isComparison ? S.Context.BoolTy
7044                       : getUsualArithmeticConversions(Left, Right);
7045        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7046      }
7047    }
7048
7049    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7050    // conditional operator for vector types.
7051    for (BuiltinCandidateTypeSet::iterator
7052              Vec1 = CandidateTypes[0].vector_begin(),
7053           Vec1End = CandidateTypes[0].vector_end();
7054         Vec1 != Vec1End; ++Vec1) {
7055      for (BuiltinCandidateTypeSet::iterator
7056                Vec2 = CandidateTypes[1].vector_begin(),
7057             Vec2End = CandidateTypes[1].vector_end();
7058           Vec2 != Vec2End; ++Vec2) {
7059        QualType LandR[2] = { *Vec1, *Vec2 };
7060        QualType Result = S.Context.BoolTy;
7061        if (!isComparison) {
7062          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7063            Result = *Vec1;
7064          else
7065            Result = *Vec2;
7066        }
7067
7068        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7069      }
7070    }
7071  }
7072
7073  // C++ [over.built]p17:
7074  //
7075  //   For every pair of promoted integral types L and R, there
7076  //   exist candidate operator functions of the form
7077  //
7078  //      LR         operator%(L, R);
7079  //      LR         operator&(L, R);
7080  //      LR         operator^(L, R);
7081  //      LR         operator|(L, R);
7082  //      L          operator<<(L, R);
7083  //      L          operator>>(L, R);
7084  //
7085  //   where LR is the result of the usual arithmetic conversions
7086  //   between types L and R.
7087  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7088    if (!HasArithmeticOrEnumeralCandidateType)
7089      return;
7090
7091    for (unsigned Left = FirstPromotedIntegralType;
7092         Left < LastPromotedIntegralType; ++Left) {
7093      for (unsigned Right = FirstPromotedIntegralType;
7094           Right < LastPromotedIntegralType; ++Right) {
7095        QualType LandR[2] = { getArithmeticType(Left),
7096                              getArithmeticType(Right) };
7097        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7098            ? LandR[0]
7099            : getUsualArithmeticConversions(Left, Right);
7100        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7101      }
7102    }
7103  }
7104
7105  // C++ [over.built]p20:
7106  //
7107  //   For every pair (T, VQ), where T is an enumeration or
7108  //   pointer to member type and VQ is either volatile or
7109  //   empty, there exist candidate operator functions of the form
7110  //
7111  //        VQ T&      operator=(VQ T&, T);
7112  void addAssignmentMemberPointerOrEnumeralOverloads() {
7113    /// Set of (canonical) types that we've already handled.
7114    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7115
7116    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7117      for (BuiltinCandidateTypeSet::iterator
7118                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7119             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7120           Enum != EnumEnd; ++Enum) {
7121        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7122          continue;
7123
7124        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7125                                               CandidateSet);
7126      }
7127
7128      for (BuiltinCandidateTypeSet::iterator
7129                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7130             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7131           MemPtr != MemPtrEnd; ++MemPtr) {
7132        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7133          continue;
7134
7135        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7136                                               CandidateSet);
7137      }
7138    }
7139  }
7140
7141  // C++ [over.built]p19:
7142  //
7143  //   For every pair (T, VQ), where T is any type and VQ is either
7144  //   volatile or empty, there exist candidate operator functions
7145  //   of the form
7146  //
7147  //        T*VQ&      operator=(T*VQ&, T*);
7148  //
7149  // C++ [over.built]p21:
7150  //
7151  //   For every pair (T, VQ), where T is a cv-qualified or
7152  //   cv-unqualified object type and VQ is either volatile or
7153  //   empty, there exist candidate operator functions of the form
7154  //
7155  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7156  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7157  void addAssignmentPointerOverloads(bool isEqualOp) {
7158    /// Set of (canonical) types that we've already handled.
7159    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7160
7161    for (BuiltinCandidateTypeSet::iterator
7162              Ptr = CandidateTypes[0].pointer_begin(),
7163           PtrEnd = CandidateTypes[0].pointer_end();
7164         Ptr != PtrEnd; ++Ptr) {
7165      // If this is operator=, keep track of the builtin candidates we added.
7166      if (isEqualOp)
7167        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7168      else if (!(*Ptr)->getPointeeType()->isObjectType())
7169        continue;
7170
7171      // non-volatile version
7172      QualType ParamTypes[2] = {
7173        S.Context.getLValueReferenceType(*Ptr),
7174        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7175      };
7176      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7177                            /*IsAssigmentOperator=*/ isEqualOp);
7178
7179      bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7180                          VisibleTypeConversionsQuals.hasVolatile();
7181      if (NeedVolatile) {
7182        // volatile version
7183        ParamTypes[0] =
7184          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7185        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7186                              /*IsAssigmentOperator=*/isEqualOp);
7187      }
7188
7189      if (!(*Ptr).isRestrictQualified() &&
7190          VisibleTypeConversionsQuals.hasRestrict()) {
7191        // restrict version
7192        ParamTypes[0]
7193          = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7194        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7195                              /*IsAssigmentOperator=*/isEqualOp);
7196
7197        if (NeedVolatile) {
7198          // volatile restrict version
7199          ParamTypes[0]
7200            = S.Context.getLValueReferenceType(
7201                S.Context.getCVRQualifiedType(*Ptr,
7202                                              (Qualifiers::Volatile |
7203                                               Qualifiers::Restrict)));
7204          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7205                                CandidateSet,
7206                                /*IsAssigmentOperator=*/isEqualOp);
7207        }
7208      }
7209    }
7210
7211    if (isEqualOp) {
7212      for (BuiltinCandidateTypeSet::iterator
7213                Ptr = CandidateTypes[1].pointer_begin(),
7214             PtrEnd = CandidateTypes[1].pointer_end();
7215           Ptr != PtrEnd; ++Ptr) {
7216        // Make sure we don't add the same candidate twice.
7217        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7218          continue;
7219
7220        QualType ParamTypes[2] = {
7221          S.Context.getLValueReferenceType(*Ptr),
7222          *Ptr,
7223        };
7224
7225        // non-volatile version
7226        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7227                              /*IsAssigmentOperator=*/true);
7228
7229        bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7230                           VisibleTypeConversionsQuals.hasVolatile();
7231        if (NeedVolatile) {
7232          // volatile version
7233          ParamTypes[0] =
7234            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7235          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7236                                CandidateSet, /*IsAssigmentOperator=*/true);
7237        }
7238
7239        if (!(*Ptr).isRestrictQualified() &&
7240            VisibleTypeConversionsQuals.hasRestrict()) {
7241          // restrict version
7242          ParamTypes[0]
7243            = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7244          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7245                                CandidateSet, /*IsAssigmentOperator=*/true);
7246
7247          if (NeedVolatile) {
7248            // volatile restrict version
7249            ParamTypes[0]
7250              = S.Context.getLValueReferenceType(
7251                  S.Context.getCVRQualifiedType(*Ptr,
7252                                                (Qualifiers::Volatile |
7253                                                 Qualifiers::Restrict)));
7254            S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7255                                  CandidateSet, /*IsAssigmentOperator=*/true);
7256
7257          }
7258        }
7259      }
7260    }
7261  }
7262
7263  // C++ [over.built]p18:
7264  //
7265  //   For every triple (L, VQ, R), where L is an arithmetic type,
7266  //   VQ is either volatile or empty, and R is a promoted
7267  //   arithmetic type, there exist candidate operator functions of
7268  //   the form
7269  //
7270  //        VQ L&      operator=(VQ L&, R);
7271  //        VQ L&      operator*=(VQ L&, R);
7272  //        VQ L&      operator/=(VQ L&, R);
7273  //        VQ L&      operator+=(VQ L&, R);
7274  //        VQ L&      operator-=(VQ L&, R);
7275  void addAssignmentArithmeticOverloads(bool isEqualOp) {
7276    if (!HasArithmeticOrEnumeralCandidateType)
7277      return;
7278
7279    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7280      for (unsigned Right = FirstPromotedArithmeticType;
7281           Right < LastPromotedArithmeticType; ++Right) {
7282        QualType ParamTypes[2];
7283        ParamTypes[1] = getArithmeticType(Right);
7284
7285        // Add this built-in operator as a candidate (VQ is empty).
7286        ParamTypes[0] =
7287          S.Context.getLValueReferenceType(getArithmeticType(Left));
7288        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7289                              /*IsAssigmentOperator=*/isEqualOp);
7290
7291        // Add this built-in operator as a candidate (VQ is 'volatile').
7292        if (VisibleTypeConversionsQuals.hasVolatile()) {
7293          ParamTypes[0] =
7294            S.Context.getVolatileType(getArithmeticType(Left));
7295          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7296          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7297                                CandidateSet,
7298                                /*IsAssigmentOperator=*/isEqualOp);
7299        }
7300      }
7301    }
7302
7303    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7304    for (BuiltinCandidateTypeSet::iterator
7305              Vec1 = CandidateTypes[0].vector_begin(),
7306           Vec1End = CandidateTypes[0].vector_end();
7307         Vec1 != Vec1End; ++Vec1) {
7308      for (BuiltinCandidateTypeSet::iterator
7309                Vec2 = CandidateTypes[1].vector_begin(),
7310             Vec2End = CandidateTypes[1].vector_end();
7311           Vec2 != Vec2End; ++Vec2) {
7312        QualType ParamTypes[2];
7313        ParamTypes[1] = *Vec2;
7314        // Add this built-in operator as a candidate (VQ is empty).
7315        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7316        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7317                              /*IsAssigmentOperator=*/isEqualOp);
7318
7319        // Add this built-in operator as a candidate (VQ is 'volatile').
7320        if (VisibleTypeConversionsQuals.hasVolatile()) {
7321          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7322          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7323          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7324                                CandidateSet,
7325                                /*IsAssigmentOperator=*/isEqualOp);
7326        }
7327      }
7328    }
7329  }
7330
7331  // C++ [over.built]p22:
7332  //
7333  //   For every triple (L, VQ, R), where L is an integral type, VQ
7334  //   is either volatile or empty, and R is a promoted integral
7335  //   type, there exist candidate operator functions of the form
7336  //
7337  //        VQ L&       operator%=(VQ L&, R);
7338  //        VQ L&       operator<<=(VQ L&, R);
7339  //        VQ L&       operator>>=(VQ L&, R);
7340  //        VQ L&       operator&=(VQ L&, R);
7341  //        VQ L&       operator^=(VQ L&, R);
7342  //        VQ L&       operator|=(VQ L&, R);
7343  void addAssignmentIntegralOverloads() {
7344    if (!HasArithmeticOrEnumeralCandidateType)
7345      return;
7346
7347    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7348      for (unsigned Right = FirstPromotedIntegralType;
7349           Right < LastPromotedIntegralType; ++Right) {
7350        QualType ParamTypes[2];
7351        ParamTypes[1] = getArithmeticType(Right);
7352
7353        // Add this built-in operator as a candidate (VQ is empty).
7354        ParamTypes[0] =
7355          S.Context.getLValueReferenceType(getArithmeticType(Left));
7356        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7357        if (VisibleTypeConversionsQuals.hasVolatile()) {
7358          // Add this built-in operator as a candidate (VQ is 'volatile').
7359          ParamTypes[0] = getArithmeticType(Left);
7360          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7361          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7362          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7363                                CandidateSet);
7364        }
7365      }
7366    }
7367  }
7368
7369  // C++ [over.operator]p23:
7370  //
7371  //   There also exist candidate operator functions of the form
7372  //
7373  //        bool        operator!(bool);
7374  //        bool        operator&&(bool, bool);
7375  //        bool        operator||(bool, bool);
7376  void addExclaimOverload() {
7377    QualType ParamTy = S.Context.BoolTy;
7378    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7379                          /*IsAssignmentOperator=*/false,
7380                          /*NumContextualBoolArguments=*/1);
7381  }
7382  void addAmpAmpOrPipePipeOverload() {
7383    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7384    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7385                          /*IsAssignmentOperator=*/false,
7386                          /*NumContextualBoolArguments=*/2);
7387  }
7388
7389  // C++ [over.built]p13:
7390  //
7391  //   For every cv-qualified or cv-unqualified object type T there
7392  //   exist candidate operator functions of the form
7393  //
7394  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7395  //        T&         operator[](T*, ptrdiff_t);
7396  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7397  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7398  //        T&         operator[](ptrdiff_t, T*);
7399  void addSubscriptOverloads() {
7400    for (BuiltinCandidateTypeSet::iterator
7401              Ptr = CandidateTypes[0].pointer_begin(),
7402           PtrEnd = CandidateTypes[0].pointer_end();
7403         Ptr != PtrEnd; ++Ptr) {
7404      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7405      QualType PointeeType = (*Ptr)->getPointeeType();
7406      if (!PointeeType->isObjectType())
7407        continue;
7408
7409      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7410
7411      // T& operator[](T*, ptrdiff_t)
7412      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7413    }
7414
7415    for (BuiltinCandidateTypeSet::iterator
7416              Ptr = CandidateTypes[1].pointer_begin(),
7417           PtrEnd = CandidateTypes[1].pointer_end();
7418         Ptr != PtrEnd; ++Ptr) {
7419      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7420      QualType PointeeType = (*Ptr)->getPointeeType();
7421      if (!PointeeType->isObjectType())
7422        continue;
7423
7424      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7425
7426      // T& operator[](ptrdiff_t, T*)
7427      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7428    }
7429  }
7430
7431  // C++ [over.built]p11:
7432  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7433  //    C1 is the same type as C2 or is a derived class of C2, T is an object
7434  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7435  //    there exist candidate operator functions of the form
7436  //
7437  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7438  //
7439  //    where CV12 is the union of CV1 and CV2.
7440  void addArrowStarOverloads() {
7441    for (BuiltinCandidateTypeSet::iterator
7442             Ptr = CandidateTypes[0].pointer_begin(),
7443           PtrEnd = CandidateTypes[0].pointer_end();
7444         Ptr != PtrEnd; ++Ptr) {
7445      QualType C1Ty = (*Ptr);
7446      QualType C1;
7447      QualifierCollector Q1;
7448      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7449      if (!isa<RecordType>(C1))
7450        continue;
7451      // heuristic to reduce number of builtin candidates in the set.
7452      // Add volatile/restrict version only if there are conversions to a
7453      // volatile/restrict type.
7454      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7455        continue;
7456      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7457        continue;
7458      for (BuiltinCandidateTypeSet::iterator
7459                MemPtr = CandidateTypes[1].member_pointer_begin(),
7460             MemPtrEnd = CandidateTypes[1].member_pointer_end();
7461           MemPtr != MemPtrEnd; ++MemPtr) {
7462        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7463        QualType C2 = QualType(mptr->getClass(), 0);
7464        C2 = C2.getUnqualifiedType();
7465        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7466          break;
7467        QualType ParamTypes[2] = { *Ptr, *MemPtr };
7468        // build CV12 T&
7469        QualType T = mptr->getPointeeType();
7470        if (!VisibleTypeConversionsQuals.hasVolatile() &&
7471            T.isVolatileQualified())
7472          continue;
7473        if (!VisibleTypeConversionsQuals.hasRestrict() &&
7474            T.isRestrictQualified())
7475          continue;
7476        T = Q1.apply(S.Context, T);
7477        QualType ResultTy = S.Context.getLValueReferenceType(T);
7478        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7479      }
7480    }
7481  }
7482
7483  // Note that we don't consider the first argument, since it has been
7484  // contextually converted to bool long ago. The candidates below are
7485  // therefore added as binary.
7486  //
7487  // C++ [over.built]p25:
7488  //   For every type T, where T is a pointer, pointer-to-member, or scoped
7489  //   enumeration type, there exist candidate operator functions of the form
7490  //
7491  //        T        operator?(bool, T, T);
7492  //
7493  void addConditionalOperatorOverloads() {
7494    /// Set of (canonical) types that we've already handled.
7495    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7496
7497    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7498      for (BuiltinCandidateTypeSet::iterator
7499                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7500             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7501           Ptr != PtrEnd; ++Ptr) {
7502        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7503          continue;
7504
7505        QualType ParamTypes[2] = { *Ptr, *Ptr };
7506        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7507      }
7508
7509      for (BuiltinCandidateTypeSet::iterator
7510                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7511             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7512           MemPtr != MemPtrEnd; ++MemPtr) {
7513        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7514          continue;
7515
7516        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7517        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7518      }
7519
7520      if (S.getLangOpts().CPlusPlus11) {
7521        for (BuiltinCandidateTypeSet::iterator
7522                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7523               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7524             Enum != EnumEnd; ++Enum) {
7525          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7526            continue;
7527
7528          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7529            continue;
7530
7531          QualType ParamTypes[2] = { *Enum, *Enum };
7532          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7533        }
7534      }
7535    }
7536  }
7537};
7538
7539} // end anonymous namespace
7540
7541/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7542/// operator overloads to the candidate set (C++ [over.built]), based
7543/// on the operator @p Op and the arguments given. For example, if the
7544/// operator is a binary '+', this routine might add "int
7545/// operator+(int, int)" to cover integer addition.
7546void
7547Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7548                                   SourceLocation OpLoc,
7549                                   Expr **Args, unsigned NumArgs,
7550                                   OverloadCandidateSet& CandidateSet) {
7551  // Find all of the types that the arguments can convert to, but only
7552  // if the operator we're looking at has built-in operator candidates
7553  // that make use of these types. Also record whether we encounter non-record
7554  // candidate types or either arithmetic or enumeral candidate types.
7555  Qualifiers VisibleTypeConversionsQuals;
7556  VisibleTypeConversionsQuals.addConst();
7557  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7558    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7559
7560  bool HasNonRecordCandidateType = false;
7561  bool HasArithmeticOrEnumeralCandidateType = false;
7562  SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7563  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7564    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7565    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7566                                                 OpLoc,
7567                                                 true,
7568                                                 (Op == OO_Exclaim ||
7569                                                  Op == OO_AmpAmp ||
7570                                                  Op == OO_PipePipe),
7571                                                 VisibleTypeConversionsQuals);
7572    HasNonRecordCandidateType = HasNonRecordCandidateType ||
7573        CandidateTypes[ArgIdx].hasNonRecordTypes();
7574    HasArithmeticOrEnumeralCandidateType =
7575        HasArithmeticOrEnumeralCandidateType ||
7576        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7577  }
7578
7579  // Exit early when no non-record types have been added to the candidate set
7580  // for any of the arguments to the operator.
7581  //
7582  // We can't exit early for !, ||, or &&, since there we have always have
7583  // 'bool' overloads.
7584  if (!HasNonRecordCandidateType &&
7585      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7586    return;
7587
7588  // Setup an object to manage the common state for building overloads.
7589  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7590                                           VisibleTypeConversionsQuals,
7591                                           HasArithmeticOrEnumeralCandidateType,
7592                                           CandidateTypes, CandidateSet);
7593
7594  // Dispatch over the operation to add in only those overloads which apply.
7595  switch (Op) {
7596  case OO_None:
7597  case NUM_OVERLOADED_OPERATORS:
7598    llvm_unreachable("Expected an overloaded operator");
7599
7600  case OO_New:
7601  case OO_Delete:
7602  case OO_Array_New:
7603  case OO_Array_Delete:
7604  case OO_Call:
7605    llvm_unreachable(
7606                    "Special operators don't use AddBuiltinOperatorCandidates");
7607
7608  case OO_Comma:
7609  case OO_Arrow:
7610    // C++ [over.match.oper]p3:
7611    //   -- For the operator ',', the unary operator '&', or the
7612    //      operator '->', the built-in candidates set is empty.
7613    break;
7614
7615  case OO_Plus: // '+' is either unary or binary
7616    if (NumArgs == 1)
7617      OpBuilder.addUnaryPlusPointerOverloads();
7618    // Fall through.
7619
7620  case OO_Minus: // '-' is either unary or binary
7621    if (NumArgs == 1) {
7622      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7623    } else {
7624      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7625      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7626    }
7627    break;
7628
7629  case OO_Star: // '*' is either unary or binary
7630    if (NumArgs == 1)
7631      OpBuilder.addUnaryStarPointerOverloads();
7632    else
7633      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7634    break;
7635
7636  case OO_Slash:
7637    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7638    break;
7639
7640  case OO_PlusPlus:
7641  case OO_MinusMinus:
7642    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7643    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7644    break;
7645
7646  case OO_EqualEqual:
7647  case OO_ExclaimEqual:
7648    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7649    // Fall through.
7650
7651  case OO_Less:
7652  case OO_Greater:
7653  case OO_LessEqual:
7654  case OO_GreaterEqual:
7655    OpBuilder.addRelationalPointerOrEnumeralOverloads();
7656    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7657    break;
7658
7659  case OO_Percent:
7660  case OO_Caret:
7661  case OO_Pipe:
7662  case OO_LessLess:
7663  case OO_GreaterGreater:
7664    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7665    break;
7666
7667  case OO_Amp: // '&' is either unary or binary
7668    if (NumArgs == 1)
7669      // C++ [over.match.oper]p3:
7670      //   -- For the operator ',', the unary operator '&', or the
7671      //      operator '->', the built-in candidates set is empty.
7672      break;
7673
7674    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7675    break;
7676
7677  case OO_Tilde:
7678    OpBuilder.addUnaryTildePromotedIntegralOverloads();
7679    break;
7680
7681  case OO_Equal:
7682    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7683    // Fall through.
7684
7685  case OO_PlusEqual:
7686  case OO_MinusEqual:
7687    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7688    // Fall through.
7689
7690  case OO_StarEqual:
7691  case OO_SlashEqual:
7692    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7693    break;
7694
7695  case OO_PercentEqual:
7696  case OO_LessLessEqual:
7697  case OO_GreaterGreaterEqual:
7698  case OO_AmpEqual:
7699  case OO_CaretEqual:
7700  case OO_PipeEqual:
7701    OpBuilder.addAssignmentIntegralOverloads();
7702    break;
7703
7704  case OO_Exclaim:
7705    OpBuilder.addExclaimOverload();
7706    break;
7707
7708  case OO_AmpAmp:
7709  case OO_PipePipe:
7710    OpBuilder.addAmpAmpOrPipePipeOverload();
7711    break;
7712
7713  case OO_Subscript:
7714    OpBuilder.addSubscriptOverloads();
7715    break;
7716
7717  case OO_ArrowStar:
7718    OpBuilder.addArrowStarOverloads();
7719    break;
7720
7721  case OO_Conditional:
7722    OpBuilder.addConditionalOperatorOverloads();
7723    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7724    break;
7725  }
7726}
7727
7728/// \brief Add function candidates found via argument-dependent lookup
7729/// to the set of overloading candidates.
7730///
7731/// This routine performs argument-dependent name lookup based on the
7732/// given function name (which may also be an operator name) and adds
7733/// all of the overload candidates found by ADL to the overload
7734/// candidate set (C++ [basic.lookup.argdep]).
7735void
7736Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7737                                           bool Operator, SourceLocation Loc,
7738                                           ArrayRef<Expr *> Args,
7739                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7740                                           OverloadCandidateSet& CandidateSet,
7741                                           bool PartialOverloading) {
7742  ADLResult Fns;
7743
7744  // FIXME: This approach for uniquing ADL results (and removing
7745  // redundant candidates from the set) relies on pointer-equality,
7746  // which means we need to key off the canonical decl.  However,
7747  // always going back to the canonical decl might not get us the
7748  // right set of default arguments.  What default arguments are
7749  // we supposed to consider on ADL candidates, anyway?
7750
7751  // FIXME: Pass in the explicit template arguments?
7752  ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
7753
7754  // Erase all of the candidates we already knew about.
7755  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7756                                   CandEnd = CandidateSet.end();
7757       Cand != CandEnd; ++Cand)
7758    if (Cand->Function) {
7759      Fns.erase(Cand->Function);
7760      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7761        Fns.erase(FunTmpl);
7762    }
7763
7764  // For each of the ADL candidates we found, add it to the overload
7765  // set.
7766  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7767    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7768    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7769      if (ExplicitTemplateArgs)
7770        continue;
7771
7772      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7773                           PartialOverloading);
7774    } else
7775      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7776                                   FoundDecl, ExplicitTemplateArgs,
7777                                   Args, CandidateSet);
7778  }
7779}
7780
7781/// isBetterOverloadCandidate - Determines whether the first overload
7782/// candidate is a better candidate than the second (C++ 13.3.3p1).
7783bool
7784isBetterOverloadCandidate(Sema &S,
7785                          const OverloadCandidate &Cand1,
7786                          const OverloadCandidate &Cand2,
7787                          SourceLocation Loc,
7788                          bool UserDefinedConversion) {
7789  // Define viable functions to be better candidates than non-viable
7790  // functions.
7791  if (!Cand2.Viable)
7792    return Cand1.Viable;
7793  else if (!Cand1.Viable)
7794    return false;
7795
7796  // C++ [over.match.best]p1:
7797  //
7798  //   -- if F is a static member function, ICS1(F) is defined such
7799  //      that ICS1(F) is neither better nor worse than ICS1(G) for
7800  //      any function G, and, symmetrically, ICS1(G) is neither
7801  //      better nor worse than ICS1(F).
7802  unsigned StartArg = 0;
7803  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7804    StartArg = 1;
7805
7806  // C++ [over.match.best]p1:
7807  //   A viable function F1 is defined to be a better function than another
7808  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7809  //   conversion sequence than ICSi(F2), and then...
7810  unsigned NumArgs = Cand1.NumConversions;
7811  assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7812  bool HasBetterConversion = false;
7813  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7814    switch (CompareImplicitConversionSequences(S,
7815                                               Cand1.Conversions[ArgIdx],
7816                                               Cand2.Conversions[ArgIdx])) {
7817    case ImplicitConversionSequence::Better:
7818      // Cand1 has a better conversion sequence.
7819      HasBetterConversion = true;
7820      break;
7821
7822    case ImplicitConversionSequence::Worse:
7823      // Cand1 can't be better than Cand2.
7824      return false;
7825
7826    case ImplicitConversionSequence::Indistinguishable:
7827      // Do nothing.
7828      break;
7829    }
7830  }
7831
7832  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7833  //       ICSj(F2), or, if not that,
7834  if (HasBetterConversion)
7835    return true;
7836
7837  //     - F1 is a non-template function and F2 is a function template
7838  //       specialization, or, if not that,
7839  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7840      Cand2.Function && Cand2.Function->getPrimaryTemplate())
7841    return true;
7842
7843  //   -- F1 and F2 are function template specializations, and the function
7844  //      template for F1 is more specialized than the template for F2
7845  //      according to the partial ordering rules described in 14.5.5.2, or,
7846  //      if not that,
7847  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7848      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7849    if (FunctionTemplateDecl *BetterTemplate
7850          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7851                                         Cand2.Function->getPrimaryTemplate(),
7852                                         Loc,
7853                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7854                                                             : TPOC_Call,
7855                                         Cand1.ExplicitCallArguments))
7856      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7857  }
7858
7859  //   -- the context is an initialization by user-defined conversion
7860  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7861  //      from the return type of F1 to the destination type (i.e.,
7862  //      the type of the entity being initialized) is a better
7863  //      conversion sequence than the standard conversion sequence
7864  //      from the return type of F2 to the destination type.
7865  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7866      isa<CXXConversionDecl>(Cand1.Function) &&
7867      isa<CXXConversionDecl>(Cand2.Function)) {
7868    // First check whether we prefer one of the conversion functions over the
7869    // other. This only distinguishes the results in non-standard, extension
7870    // cases such as the conversion from a lambda closure type to a function
7871    // pointer or block.
7872    ImplicitConversionSequence::CompareKind FuncResult
7873      = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7874    if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7875      return FuncResult;
7876
7877    switch (CompareStandardConversionSequences(S,
7878                                               Cand1.FinalConversion,
7879                                               Cand2.FinalConversion)) {
7880    case ImplicitConversionSequence::Better:
7881      // Cand1 has a better conversion sequence.
7882      return true;
7883
7884    case ImplicitConversionSequence::Worse:
7885      // Cand1 can't be better than Cand2.
7886      return false;
7887
7888    case ImplicitConversionSequence::Indistinguishable:
7889      // Do nothing
7890      break;
7891    }
7892  }
7893
7894  return false;
7895}
7896
7897/// \brief Computes the best viable function (C++ 13.3.3)
7898/// within an overload candidate set.
7899///
7900/// \param Loc The location of the function name (or operator symbol) for
7901/// which overload resolution occurs.
7902///
7903/// \param Best If overload resolution was successful or found a deleted
7904/// function, \p Best points to the candidate function found.
7905///
7906/// \returns The result of overload resolution.
7907OverloadingResult
7908OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
7909                                         iterator &Best,
7910                                         bool UserDefinedConversion) {
7911  // Find the best viable function.
7912  Best = end();
7913  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7914    if (Cand->Viable)
7915      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
7916                                                     UserDefinedConversion))
7917        Best = Cand;
7918  }
7919
7920  // If we didn't find any viable functions, abort.
7921  if (Best == end())
7922    return OR_No_Viable_Function;
7923
7924  // Make sure that this function is better than every other viable
7925  // function. If not, we have an ambiguity.
7926  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7927    if (Cand->Viable &&
7928        Cand != Best &&
7929        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
7930                                   UserDefinedConversion)) {
7931      Best = end();
7932      return OR_Ambiguous;
7933    }
7934  }
7935
7936  // Best is the best viable function.
7937  if (Best->Function &&
7938      (Best->Function->isDeleted() ||
7939       S.isFunctionConsideredUnavailable(Best->Function)))
7940    return OR_Deleted;
7941
7942  return OR_Success;
7943}
7944
7945namespace {
7946
7947enum OverloadCandidateKind {
7948  oc_function,
7949  oc_method,
7950  oc_constructor,
7951  oc_function_template,
7952  oc_method_template,
7953  oc_constructor_template,
7954  oc_implicit_default_constructor,
7955  oc_implicit_copy_constructor,
7956  oc_implicit_move_constructor,
7957  oc_implicit_copy_assignment,
7958  oc_implicit_move_assignment,
7959  oc_implicit_inherited_constructor
7960};
7961
7962OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7963                                                FunctionDecl *Fn,
7964                                                std::string &Description) {
7965  bool isTemplate = false;
7966
7967  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7968    isTemplate = true;
7969    Description = S.getTemplateArgumentBindingsText(
7970      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7971  }
7972
7973  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
7974    if (!Ctor->isImplicit())
7975      return isTemplate ? oc_constructor_template : oc_constructor;
7976
7977    if (Ctor->getInheritedConstructor())
7978      return oc_implicit_inherited_constructor;
7979
7980    if (Ctor->isDefaultConstructor())
7981      return oc_implicit_default_constructor;
7982
7983    if (Ctor->isMoveConstructor())
7984      return oc_implicit_move_constructor;
7985
7986    assert(Ctor->isCopyConstructor() &&
7987           "unexpected sort of implicit constructor");
7988    return oc_implicit_copy_constructor;
7989  }
7990
7991  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7992    // This actually gets spelled 'candidate function' for now, but
7993    // it doesn't hurt to split it out.
7994    if (!Meth->isImplicit())
7995      return isTemplate ? oc_method_template : oc_method;
7996
7997    if (Meth->isMoveAssignmentOperator())
7998      return oc_implicit_move_assignment;
7999
8000    if (Meth->isCopyAssignmentOperator())
8001      return oc_implicit_copy_assignment;
8002
8003    assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8004    return oc_method;
8005  }
8006
8007  return isTemplate ? oc_function_template : oc_function;
8008}
8009
8010void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8011  const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8012  if (!Ctor) return;
8013
8014  Ctor = Ctor->getInheritedConstructor();
8015  if (!Ctor) return;
8016
8017  S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8018}
8019
8020} // end anonymous namespace
8021
8022// Notes the location of an overload candidate.
8023void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8024  std::string FnDesc;
8025  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8026  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8027                             << (unsigned) K << FnDesc;
8028  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8029  Diag(Fn->getLocation(), PD);
8030  MaybeEmitInheritedConstructorNote(*this, Fn);
8031}
8032
8033//Notes the location of all overload candidates designated through
8034// OverloadedExpr
8035void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8036  assert(OverloadedExpr->getType() == Context.OverloadTy);
8037
8038  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8039  OverloadExpr *OvlExpr = Ovl.Expression;
8040
8041  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8042                            IEnd = OvlExpr->decls_end();
8043       I != IEnd; ++I) {
8044    if (FunctionTemplateDecl *FunTmpl =
8045                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8046      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8047    } else if (FunctionDecl *Fun
8048                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8049      NoteOverloadCandidate(Fun, DestType);
8050    }
8051  }
8052}
8053
8054/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8055/// "lead" diagnostic; it will be given two arguments, the source and
8056/// target types of the conversion.
8057void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8058                                 Sema &S,
8059                                 SourceLocation CaretLoc,
8060                                 const PartialDiagnostic &PDiag) const {
8061  S.Diag(CaretLoc, PDiag)
8062    << Ambiguous.getFromType() << Ambiguous.getToType();
8063  // FIXME: The note limiting machinery is borrowed from
8064  // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8065  // refactoring here.
8066  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8067  unsigned CandsShown = 0;
8068  AmbiguousConversionSequence::const_iterator I, E;
8069  for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8070    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8071      break;
8072    ++CandsShown;
8073    S.NoteOverloadCandidate(*I);
8074  }
8075  if (I != E)
8076    S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8077}
8078
8079namespace {
8080
8081void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8082  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8083  assert(Conv.isBad());
8084  assert(Cand->Function && "for now, candidate must be a function");
8085  FunctionDecl *Fn = Cand->Function;
8086
8087  // There's a conversion slot for the object argument if this is a
8088  // non-constructor method.  Note that 'I' corresponds the
8089  // conversion-slot index.
8090  bool isObjectArgument = false;
8091  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8092    if (I == 0)
8093      isObjectArgument = true;
8094    else
8095      I--;
8096  }
8097
8098  std::string FnDesc;
8099  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8100
8101  Expr *FromExpr = Conv.Bad.FromExpr;
8102  QualType FromTy = Conv.Bad.getFromType();
8103  QualType ToTy = Conv.Bad.getToType();
8104
8105  if (FromTy == S.Context.OverloadTy) {
8106    assert(FromExpr && "overload set argument came from implicit argument?");
8107    Expr *E = FromExpr->IgnoreParens();
8108    if (isa<UnaryOperator>(E))
8109      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8110    DeclarationName Name = cast<OverloadExpr>(E)->getName();
8111
8112    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8113      << (unsigned) FnKind << FnDesc
8114      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8115      << ToTy << Name << I+1;
8116    MaybeEmitInheritedConstructorNote(S, Fn);
8117    return;
8118  }
8119
8120  // Do some hand-waving analysis to see if the non-viability is due
8121  // to a qualifier mismatch.
8122  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8123  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8124  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8125    CToTy = RT->getPointeeType();
8126  else {
8127    // TODO: detect and diagnose the full richness of const mismatches.
8128    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8129      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8130        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8131  }
8132
8133  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8134      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8135    Qualifiers FromQs = CFromTy.getQualifiers();
8136    Qualifiers ToQs = CToTy.getQualifiers();
8137
8138    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8139      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8140        << (unsigned) FnKind << FnDesc
8141        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8142        << FromTy
8143        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8144        << (unsigned) isObjectArgument << I+1;
8145      MaybeEmitInheritedConstructorNote(S, Fn);
8146      return;
8147    }
8148
8149    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8150      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8151        << (unsigned) FnKind << FnDesc
8152        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8153        << FromTy
8154        << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8155        << (unsigned) isObjectArgument << I+1;
8156      MaybeEmitInheritedConstructorNote(S, Fn);
8157      return;
8158    }
8159
8160    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8161      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8162      << (unsigned) FnKind << FnDesc
8163      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8164      << FromTy
8165      << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8166      << (unsigned) isObjectArgument << I+1;
8167      MaybeEmitInheritedConstructorNote(S, Fn);
8168      return;
8169    }
8170
8171    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8172    assert(CVR && "unexpected qualifiers mismatch");
8173
8174    if (isObjectArgument) {
8175      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8176        << (unsigned) FnKind << FnDesc
8177        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8178        << FromTy << (CVR - 1);
8179    } else {
8180      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8181        << (unsigned) FnKind << FnDesc
8182        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8183        << FromTy << (CVR - 1) << I+1;
8184    }
8185    MaybeEmitInheritedConstructorNote(S, Fn);
8186    return;
8187  }
8188
8189  // Special diagnostic for failure to convert an initializer list, since
8190  // telling the user that it has type void is not useful.
8191  if (FromExpr && isa<InitListExpr>(FromExpr)) {
8192    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8193      << (unsigned) FnKind << FnDesc
8194      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8195      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8196    MaybeEmitInheritedConstructorNote(S, Fn);
8197    return;
8198  }
8199
8200  // Diagnose references or pointers to incomplete types differently,
8201  // since it's far from impossible that the incompleteness triggered
8202  // the failure.
8203  QualType TempFromTy = FromTy.getNonReferenceType();
8204  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8205    TempFromTy = PTy->getPointeeType();
8206  if (TempFromTy->isIncompleteType()) {
8207    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8208      << (unsigned) FnKind << FnDesc
8209      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8210      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8211    MaybeEmitInheritedConstructorNote(S, Fn);
8212    return;
8213  }
8214
8215  // Diagnose base -> derived pointer conversions.
8216  unsigned BaseToDerivedConversion = 0;
8217  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8218    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8219      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8220                                               FromPtrTy->getPointeeType()) &&
8221          !FromPtrTy->getPointeeType()->isIncompleteType() &&
8222          !ToPtrTy->getPointeeType()->isIncompleteType() &&
8223          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8224                          FromPtrTy->getPointeeType()))
8225        BaseToDerivedConversion = 1;
8226    }
8227  } else if (const ObjCObjectPointerType *FromPtrTy
8228                                    = FromTy->getAs<ObjCObjectPointerType>()) {
8229    if (const ObjCObjectPointerType *ToPtrTy
8230                                        = ToTy->getAs<ObjCObjectPointerType>())
8231      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8232        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8233          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8234                                                FromPtrTy->getPointeeType()) &&
8235              FromIface->isSuperClassOf(ToIface))
8236            BaseToDerivedConversion = 2;
8237  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8238    if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8239        !FromTy->isIncompleteType() &&
8240        !ToRefTy->getPointeeType()->isIncompleteType() &&
8241        S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8242      BaseToDerivedConversion = 3;
8243    } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8244               ToTy.getNonReferenceType().getCanonicalType() ==
8245               FromTy.getNonReferenceType().getCanonicalType()) {
8246      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8247        << (unsigned) FnKind << FnDesc
8248        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8249        << (unsigned) isObjectArgument << I + 1;
8250      MaybeEmitInheritedConstructorNote(S, Fn);
8251      return;
8252    }
8253  }
8254
8255  if (BaseToDerivedConversion) {
8256    S.Diag(Fn->getLocation(),
8257           diag::note_ovl_candidate_bad_base_to_derived_conv)
8258      << (unsigned) FnKind << FnDesc
8259      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8260      << (BaseToDerivedConversion - 1)
8261      << FromTy << ToTy << I+1;
8262    MaybeEmitInheritedConstructorNote(S, Fn);
8263    return;
8264  }
8265
8266  if (isa<ObjCObjectPointerType>(CFromTy) &&
8267      isa<PointerType>(CToTy)) {
8268      Qualifiers FromQs = CFromTy.getQualifiers();
8269      Qualifiers ToQs = CToTy.getQualifiers();
8270      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8271        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8272        << (unsigned) FnKind << FnDesc
8273        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8274        << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8275        MaybeEmitInheritedConstructorNote(S, Fn);
8276        return;
8277      }
8278  }
8279
8280  // Emit the generic diagnostic and, optionally, add the hints to it.
8281  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8282  FDiag << (unsigned) FnKind << FnDesc
8283    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8284    << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8285    << (unsigned) (Cand->Fix.Kind);
8286
8287  // If we can fix the conversion, suggest the FixIts.
8288  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8289       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8290    FDiag << *HI;
8291  S.Diag(Fn->getLocation(), FDiag);
8292
8293  MaybeEmitInheritedConstructorNote(S, Fn);
8294}
8295
8296void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8297                           unsigned NumFormalArgs) {
8298  // TODO: treat calls to a missing default constructor as a special case
8299
8300  FunctionDecl *Fn = Cand->Function;
8301  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8302
8303  unsigned MinParams = Fn->getMinRequiredArguments();
8304
8305  // With invalid overloaded operators, it's possible that we think we
8306  // have an arity mismatch when it fact it looks like we have the
8307  // right number of arguments, because only overloaded operators have
8308  // the weird behavior of overloading member and non-member functions.
8309  // Just don't report anything.
8310  if (Fn->isInvalidDecl() &&
8311      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8312    return;
8313
8314  // at least / at most / exactly
8315  unsigned mode, modeCount;
8316  if (NumFormalArgs < MinParams) {
8317    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8318           (Cand->FailureKind == ovl_fail_bad_deduction &&
8319            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8320    if (MinParams != FnTy->getNumArgs() ||
8321        FnTy->isVariadic() || FnTy->isTemplateVariadic())
8322      mode = 0; // "at least"
8323    else
8324      mode = 2; // "exactly"
8325    modeCount = MinParams;
8326  } else {
8327    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8328           (Cand->FailureKind == ovl_fail_bad_deduction &&
8329            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8330    if (MinParams != FnTy->getNumArgs())
8331      mode = 1; // "at most"
8332    else
8333      mode = 2; // "exactly"
8334    modeCount = FnTy->getNumArgs();
8335  }
8336
8337  std::string Description;
8338  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8339
8340  if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8341    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8342      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8343      << Fn->getParamDecl(0) << NumFormalArgs;
8344  else
8345    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8346      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8347      << modeCount << NumFormalArgs;
8348  MaybeEmitInheritedConstructorNote(S, Fn);
8349}
8350
8351/// Diagnose a failed template-argument deduction.
8352void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8353                          unsigned NumArgs) {
8354  FunctionDecl *Fn = Cand->Function; // pattern
8355
8356  TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
8357  NamedDecl *ParamD;
8358  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8359  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8360  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8361  switch (Cand->DeductionFailure.Result) {
8362  case Sema::TDK_Success:
8363    llvm_unreachable("TDK_success while diagnosing bad deduction");
8364
8365  case Sema::TDK_Incomplete: {
8366    assert(ParamD && "no parameter found for incomplete deduction result");
8367    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8368      << ParamD->getDeclName();
8369    MaybeEmitInheritedConstructorNote(S, Fn);
8370    return;
8371  }
8372
8373  case Sema::TDK_Underqualified: {
8374    assert(ParamD && "no parameter found for bad qualifiers deduction result");
8375    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8376
8377    QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8378
8379    // Param will have been canonicalized, but it should just be a
8380    // qualified version of ParamD, so move the qualifiers to that.
8381    QualifierCollector Qs;
8382    Qs.strip(Param);
8383    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8384    assert(S.Context.hasSameType(Param, NonCanonParam));
8385
8386    // Arg has also been canonicalized, but there's nothing we can do
8387    // about that.  It also doesn't matter as much, because it won't
8388    // have any template parameters in it (because deduction isn't
8389    // done on dependent types).
8390    QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8391
8392    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8393      << ParamD->getDeclName() << Arg << NonCanonParam;
8394    MaybeEmitInheritedConstructorNote(S, Fn);
8395    return;
8396  }
8397
8398  case Sema::TDK_Inconsistent: {
8399    assert(ParamD && "no parameter found for inconsistent deduction result");
8400    int which = 0;
8401    if (isa<TemplateTypeParmDecl>(ParamD))
8402      which = 0;
8403    else if (isa<NonTypeTemplateParmDecl>(ParamD))
8404      which = 1;
8405    else {
8406      which = 2;
8407    }
8408
8409    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8410      << which << ParamD->getDeclName()
8411      << *Cand->DeductionFailure.getFirstArg()
8412      << *Cand->DeductionFailure.getSecondArg();
8413    MaybeEmitInheritedConstructorNote(S, Fn);
8414    return;
8415  }
8416
8417  case Sema::TDK_InvalidExplicitArguments:
8418    assert(ParamD && "no parameter found for invalid explicit arguments");
8419    if (ParamD->getDeclName())
8420      S.Diag(Fn->getLocation(),
8421             diag::note_ovl_candidate_explicit_arg_mismatch_named)
8422        << ParamD->getDeclName();
8423    else {
8424      int index = 0;
8425      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8426        index = TTP->getIndex();
8427      else if (NonTypeTemplateParmDecl *NTTP
8428                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8429        index = NTTP->getIndex();
8430      else
8431        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8432      S.Diag(Fn->getLocation(),
8433             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8434        << (index + 1);
8435    }
8436    MaybeEmitInheritedConstructorNote(S, Fn);
8437    return;
8438
8439  case Sema::TDK_TooManyArguments:
8440  case Sema::TDK_TooFewArguments:
8441    DiagnoseArityMismatch(S, Cand, NumArgs);
8442    return;
8443
8444  case Sema::TDK_InstantiationDepth:
8445    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8446    MaybeEmitInheritedConstructorNote(S, Fn);
8447    return;
8448
8449  case Sema::TDK_SubstitutionFailure: {
8450    // Format the template argument list into the argument string.
8451    SmallString<128> TemplateArgString;
8452    if (TemplateArgumentList *Args =
8453          Cand->DeductionFailure.getTemplateArgumentList()) {
8454      TemplateArgString = " ";
8455      TemplateArgString += S.getTemplateArgumentBindingsText(
8456          Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8457    }
8458
8459    // If this candidate was disabled by enable_if, say so.
8460    PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8461    if (PDiag && PDiag->second.getDiagID() ==
8462          diag::err_typename_nested_not_found_enable_if) {
8463      // FIXME: Use the source range of the condition, and the fully-qualified
8464      //        name of the enable_if template. These are both present in PDiag.
8465      S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8466        << "'enable_if'" << TemplateArgString;
8467      return;
8468    }
8469
8470    // Format the SFINAE diagnostic into the argument string.
8471    // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8472    //        formatted message in another diagnostic.
8473    SmallString<128> SFINAEArgString;
8474    SourceRange R;
8475    if (PDiag) {
8476      SFINAEArgString = ": ";
8477      R = SourceRange(PDiag->first, PDiag->first);
8478      PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8479    }
8480
8481    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8482      << TemplateArgString << SFINAEArgString << R;
8483    MaybeEmitInheritedConstructorNote(S, Fn);
8484    return;
8485  }
8486
8487  case Sema::TDK_FailedOverloadResolution: {
8488    OverloadExpr::FindResult R =
8489        OverloadExpr::find(Cand->DeductionFailure.getExpr());
8490    S.Diag(Fn->getLocation(),
8491           diag::note_ovl_candidate_failed_overload_resolution)
8492      << R.Expression->getName();
8493    return;
8494  }
8495
8496  case Sema::TDK_NonDeducedMismatch:
8497    // FIXME: Provide a source location to indicate what we couldn't match.
8498    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
8499      << *Cand->DeductionFailure.getFirstArg()
8500      << *Cand->DeductionFailure.getSecondArg();
8501    return;
8502
8503  // TODO: diagnose these individually, then kill off
8504  // note_ovl_candidate_bad_deduction, which is uselessly vague.
8505  case Sema::TDK_MiscellaneousDeductionFailure:
8506    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8507    MaybeEmitInheritedConstructorNote(S, Fn);
8508    return;
8509  }
8510}
8511
8512/// CUDA: diagnose an invalid call across targets.
8513void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8514  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8515  FunctionDecl *Callee = Cand->Function;
8516
8517  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8518                           CalleeTarget = S.IdentifyCUDATarget(Callee);
8519
8520  std::string FnDesc;
8521  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8522
8523  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8524      << (unsigned) FnKind << CalleeTarget << CallerTarget;
8525}
8526
8527/// Generates a 'note' diagnostic for an overload candidate.  We've
8528/// already generated a primary error at the call site.
8529///
8530/// It really does need to be a single diagnostic with its caret
8531/// pointed at the candidate declaration.  Yes, this creates some
8532/// major challenges of technical writing.  Yes, this makes pointing
8533/// out problems with specific arguments quite awkward.  It's still
8534/// better than generating twenty screens of text for every failed
8535/// overload.
8536///
8537/// It would be great to be able to express per-candidate problems
8538/// more richly for those diagnostic clients that cared, but we'd
8539/// still have to be just as careful with the default diagnostics.
8540void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8541                           unsigned NumArgs) {
8542  FunctionDecl *Fn = Cand->Function;
8543
8544  // Note deleted candidates, but only if they're viable.
8545  if (Cand->Viable && (Fn->isDeleted() ||
8546      S.isFunctionConsideredUnavailable(Fn))) {
8547    std::string FnDesc;
8548    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8549
8550    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8551      << FnKind << FnDesc
8552      << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8553    MaybeEmitInheritedConstructorNote(S, Fn);
8554    return;
8555  }
8556
8557  // We don't really have anything else to say about viable candidates.
8558  if (Cand->Viable) {
8559    S.NoteOverloadCandidate(Fn);
8560    return;
8561  }
8562
8563  switch (Cand->FailureKind) {
8564  case ovl_fail_too_many_arguments:
8565  case ovl_fail_too_few_arguments:
8566    return DiagnoseArityMismatch(S, Cand, NumArgs);
8567
8568  case ovl_fail_bad_deduction:
8569    return DiagnoseBadDeduction(S, Cand, NumArgs);
8570
8571  case ovl_fail_trivial_conversion:
8572  case ovl_fail_bad_final_conversion:
8573  case ovl_fail_final_conversion_not_exact:
8574    return S.NoteOverloadCandidate(Fn);
8575
8576  case ovl_fail_bad_conversion: {
8577    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8578    for (unsigned N = Cand->NumConversions; I != N; ++I)
8579      if (Cand->Conversions[I].isBad())
8580        return DiagnoseBadConversion(S, Cand, I);
8581
8582    // FIXME: this currently happens when we're called from SemaInit
8583    // when user-conversion overload fails.  Figure out how to handle
8584    // those conditions and diagnose them well.
8585    return S.NoteOverloadCandidate(Fn);
8586  }
8587
8588  case ovl_fail_bad_target:
8589    return DiagnoseBadTarget(S, Cand);
8590  }
8591}
8592
8593void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8594  // Desugar the type of the surrogate down to a function type,
8595  // retaining as many typedefs as possible while still showing
8596  // the function type (and, therefore, its parameter types).
8597  QualType FnType = Cand->Surrogate->getConversionType();
8598  bool isLValueReference = false;
8599  bool isRValueReference = false;
8600  bool isPointer = false;
8601  if (const LValueReferenceType *FnTypeRef =
8602        FnType->getAs<LValueReferenceType>()) {
8603    FnType = FnTypeRef->getPointeeType();
8604    isLValueReference = true;
8605  } else if (const RValueReferenceType *FnTypeRef =
8606               FnType->getAs<RValueReferenceType>()) {
8607    FnType = FnTypeRef->getPointeeType();
8608    isRValueReference = true;
8609  }
8610  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8611    FnType = FnTypePtr->getPointeeType();
8612    isPointer = true;
8613  }
8614  // Desugar down to a function type.
8615  FnType = QualType(FnType->getAs<FunctionType>(), 0);
8616  // Reconstruct the pointer/reference as appropriate.
8617  if (isPointer) FnType = S.Context.getPointerType(FnType);
8618  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8619  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8620
8621  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8622    << FnType;
8623  MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8624}
8625
8626void NoteBuiltinOperatorCandidate(Sema &S,
8627                                  StringRef Opc,
8628                                  SourceLocation OpLoc,
8629                                  OverloadCandidate *Cand) {
8630  assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8631  std::string TypeStr("operator");
8632  TypeStr += Opc;
8633  TypeStr += "(";
8634  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8635  if (Cand->NumConversions == 1) {
8636    TypeStr += ")";
8637    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8638  } else {
8639    TypeStr += ", ";
8640    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8641    TypeStr += ")";
8642    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8643  }
8644}
8645
8646void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8647                                  OverloadCandidate *Cand) {
8648  unsigned NoOperands = Cand->NumConversions;
8649  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8650    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8651    if (ICS.isBad()) break; // all meaningless after first invalid
8652    if (!ICS.isAmbiguous()) continue;
8653
8654    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8655                              S.PDiag(diag::note_ambiguous_type_conversion));
8656  }
8657}
8658
8659SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8660  if (Cand->Function)
8661    return Cand->Function->getLocation();
8662  if (Cand->IsSurrogate)
8663    return Cand->Surrogate->getLocation();
8664  return SourceLocation();
8665}
8666
8667static unsigned
8668RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8669  switch ((Sema::TemplateDeductionResult)DFI.Result) {
8670  case Sema::TDK_Success:
8671    llvm_unreachable("TDK_success while diagnosing bad deduction");
8672
8673  case Sema::TDK_Invalid:
8674  case Sema::TDK_Incomplete:
8675    return 1;
8676
8677  case Sema::TDK_Underqualified:
8678  case Sema::TDK_Inconsistent:
8679    return 2;
8680
8681  case Sema::TDK_SubstitutionFailure:
8682  case Sema::TDK_NonDeducedMismatch:
8683  case Sema::TDK_MiscellaneousDeductionFailure:
8684    return 3;
8685
8686  case Sema::TDK_InstantiationDepth:
8687  case Sema::TDK_FailedOverloadResolution:
8688    return 4;
8689
8690  case Sema::TDK_InvalidExplicitArguments:
8691    return 5;
8692
8693  case Sema::TDK_TooManyArguments:
8694  case Sema::TDK_TooFewArguments:
8695    return 6;
8696  }
8697  llvm_unreachable("Unhandled deduction result");
8698}
8699
8700struct CompareOverloadCandidatesForDisplay {
8701  Sema &S;
8702  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8703
8704  bool operator()(const OverloadCandidate *L,
8705                  const OverloadCandidate *R) {
8706    // Fast-path this check.
8707    if (L == R) return false;
8708
8709    // Order first by viability.
8710    if (L->Viable) {
8711      if (!R->Viable) return true;
8712
8713      // TODO: introduce a tri-valued comparison for overload
8714      // candidates.  Would be more worthwhile if we had a sort
8715      // that could exploit it.
8716      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8717      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8718    } else if (R->Viable)
8719      return false;
8720
8721    assert(L->Viable == R->Viable);
8722
8723    // Criteria by which we can sort non-viable candidates:
8724    if (!L->Viable) {
8725      // 1. Arity mismatches come after other candidates.
8726      if (L->FailureKind == ovl_fail_too_many_arguments ||
8727          L->FailureKind == ovl_fail_too_few_arguments)
8728        return false;
8729      if (R->FailureKind == ovl_fail_too_many_arguments ||
8730          R->FailureKind == ovl_fail_too_few_arguments)
8731        return true;
8732
8733      // 2. Bad conversions come first and are ordered by the number
8734      // of bad conversions and quality of good conversions.
8735      if (L->FailureKind == ovl_fail_bad_conversion) {
8736        if (R->FailureKind != ovl_fail_bad_conversion)
8737          return true;
8738
8739        // The conversion that can be fixed with a smaller number of changes,
8740        // comes first.
8741        unsigned numLFixes = L->Fix.NumConversionsFixed;
8742        unsigned numRFixes = R->Fix.NumConversionsFixed;
8743        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8744        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8745        if (numLFixes != numRFixes) {
8746          if (numLFixes < numRFixes)
8747            return true;
8748          else
8749            return false;
8750        }
8751
8752        // If there's any ordering between the defined conversions...
8753        // FIXME: this might not be transitive.
8754        assert(L->NumConversions == R->NumConversions);
8755
8756        int leftBetter = 0;
8757        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8758        for (unsigned E = L->NumConversions; I != E; ++I) {
8759          switch (CompareImplicitConversionSequences(S,
8760                                                     L->Conversions[I],
8761                                                     R->Conversions[I])) {
8762          case ImplicitConversionSequence::Better:
8763            leftBetter++;
8764            break;
8765
8766          case ImplicitConversionSequence::Worse:
8767            leftBetter--;
8768            break;
8769
8770          case ImplicitConversionSequence::Indistinguishable:
8771            break;
8772          }
8773        }
8774        if (leftBetter > 0) return true;
8775        if (leftBetter < 0) return false;
8776
8777      } else if (R->FailureKind == ovl_fail_bad_conversion)
8778        return false;
8779
8780      if (L->FailureKind == ovl_fail_bad_deduction) {
8781        if (R->FailureKind != ovl_fail_bad_deduction)
8782          return true;
8783
8784        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8785          return RankDeductionFailure(L->DeductionFailure)
8786               < RankDeductionFailure(R->DeductionFailure);
8787      } else if (R->FailureKind == ovl_fail_bad_deduction)
8788        return false;
8789
8790      // TODO: others?
8791    }
8792
8793    // Sort everything else by location.
8794    SourceLocation LLoc = GetLocationForCandidate(L);
8795    SourceLocation RLoc = GetLocationForCandidate(R);
8796
8797    // Put candidates without locations (e.g. builtins) at the end.
8798    if (LLoc.isInvalid()) return false;
8799    if (RLoc.isInvalid()) return true;
8800
8801    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8802  }
8803};
8804
8805/// CompleteNonViableCandidate - Normally, overload resolution only
8806/// computes up to the first. Produces the FixIt set if possible.
8807void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8808                                ArrayRef<Expr *> Args) {
8809  assert(!Cand->Viable);
8810
8811  // Don't do anything on failures other than bad conversion.
8812  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8813
8814  // We only want the FixIts if all the arguments can be corrected.
8815  bool Unfixable = false;
8816  // Use a implicit copy initialization to check conversion fixes.
8817  Cand->Fix.setConversionChecker(TryCopyInitialization);
8818
8819  // Skip forward to the first bad conversion.
8820  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
8821  unsigned ConvCount = Cand->NumConversions;
8822  while (true) {
8823    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8824    ConvIdx++;
8825    if (Cand->Conversions[ConvIdx - 1].isBad()) {
8826      Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
8827      break;
8828    }
8829  }
8830
8831  if (ConvIdx == ConvCount)
8832    return;
8833
8834  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8835         "remaining conversion is initialized?");
8836
8837  // FIXME: this should probably be preserved from the overload
8838  // operation somehow.
8839  bool SuppressUserConversions = false;
8840
8841  const FunctionProtoType* Proto;
8842  unsigned ArgIdx = ConvIdx;
8843
8844  if (Cand->IsSurrogate) {
8845    QualType ConvType
8846      = Cand->Surrogate->getConversionType().getNonReferenceType();
8847    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8848      ConvType = ConvPtrType->getPointeeType();
8849    Proto = ConvType->getAs<FunctionProtoType>();
8850    ArgIdx--;
8851  } else if (Cand->Function) {
8852    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8853    if (isa<CXXMethodDecl>(Cand->Function) &&
8854        !isa<CXXConstructorDecl>(Cand->Function))
8855      ArgIdx--;
8856  } else {
8857    // Builtin binary operator with a bad first conversion.
8858    assert(ConvCount <= 3);
8859    for (; ConvIdx != ConvCount; ++ConvIdx)
8860      Cand->Conversions[ConvIdx]
8861        = TryCopyInitialization(S, Args[ConvIdx],
8862                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
8863                                SuppressUserConversions,
8864                                /*InOverloadResolution*/ true,
8865                                /*AllowObjCWritebackConversion=*/
8866                                  S.getLangOpts().ObjCAutoRefCount);
8867    return;
8868  }
8869
8870  // Fill in the rest of the conversions.
8871  unsigned NumArgsInProto = Proto->getNumArgs();
8872  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
8873    if (ArgIdx < NumArgsInProto) {
8874      Cand->Conversions[ConvIdx]
8875        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
8876                                SuppressUserConversions,
8877                                /*InOverloadResolution=*/true,
8878                                /*AllowObjCWritebackConversion=*/
8879                                  S.getLangOpts().ObjCAutoRefCount);
8880      // Store the FixIt in the candidate if it exists.
8881      if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
8882        Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
8883    }
8884    else
8885      Cand->Conversions[ConvIdx].setEllipsis();
8886  }
8887}
8888
8889} // end anonymous namespace
8890
8891/// PrintOverloadCandidates - When overload resolution fails, prints
8892/// diagnostic messages containing the candidates in the candidate
8893/// set.
8894void OverloadCandidateSet::NoteCandidates(Sema &S,
8895                                          OverloadCandidateDisplayKind OCD,
8896                                          ArrayRef<Expr *> Args,
8897                                          StringRef Opc,
8898                                          SourceLocation OpLoc) {
8899  // Sort the candidates by viability and position.  Sorting directly would
8900  // be prohibitive, so we make a set of pointers and sort those.
8901  SmallVector<OverloadCandidate*, 32> Cands;
8902  if (OCD == OCD_AllCandidates) Cands.reserve(size());
8903  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
8904    if (Cand->Viable)
8905      Cands.push_back(Cand);
8906    else if (OCD == OCD_AllCandidates) {
8907      CompleteNonViableCandidate(S, Cand, Args);
8908      if (Cand->Function || Cand->IsSurrogate)
8909        Cands.push_back(Cand);
8910      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
8911      // want to list every possible builtin candidate.
8912    }
8913  }
8914
8915  std::sort(Cands.begin(), Cands.end(),
8916            CompareOverloadCandidatesForDisplay(S));
8917
8918  bool ReportedAmbiguousConversions = false;
8919
8920  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
8921  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8922  unsigned CandsShown = 0;
8923  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8924    OverloadCandidate *Cand = *I;
8925
8926    // Set an arbitrary limit on the number of candidate functions we'll spam
8927    // the user with.  FIXME: This limit should depend on details of the
8928    // candidate list.
8929    if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
8930      break;
8931    }
8932    ++CandsShown;
8933
8934    if (Cand->Function)
8935      NoteFunctionCandidate(S, Cand, Args.size());
8936    else if (Cand->IsSurrogate)
8937      NoteSurrogateCandidate(S, Cand);
8938    else {
8939      assert(Cand->Viable &&
8940             "Non-viable built-in candidates are not added to Cands.");
8941      // Generally we only see ambiguities including viable builtin
8942      // operators if overload resolution got screwed up by an
8943      // ambiguous user-defined conversion.
8944      //
8945      // FIXME: It's quite possible for different conversions to see
8946      // different ambiguities, though.
8947      if (!ReportedAmbiguousConversions) {
8948        NoteAmbiguousUserConversions(S, OpLoc, Cand);
8949        ReportedAmbiguousConversions = true;
8950      }
8951
8952      // If this is a viable builtin, print it.
8953      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
8954    }
8955  }
8956
8957  if (I != E)
8958    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
8959}
8960
8961// [PossiblyAFunctionType]  -->   [Return]
8962// NonFunctionType --> NonFunctionType
8963// R (A) --> R(A)
8964// R (*)(A) --> R (A)
8965// R (&)(A) --> R (A)
8966// R (S::*)(A) --> R (A)
8967QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8968  QualType Ret = PossiblyAFunctionType;
8969  if (const PointerType *ToTypePtr =
8970    PossiblyAFunctionType->getAs<PointerType>())
8971    Ret = ToTypePtr->getPointeeType();
8972  else if (const ReferenceType *ToTypeRef =
8973    PossiblyAFunctionType->getAs<ReferenceType>())
8974    Ret = ToTypeRef->getPointeeType();
8975  else if (const MemberPointerType *MemTypePtr =
8976    PossiblyAFunctionType->getAs<MemberPointerType>())
8977    Ret = MemTypePtr->getPointeeType();
8978  Ret =
8979    Context.getCanonicalType(Ret).getUnqualifiedType();
8980  return Ret;
8981}
8982
8983// A helper class to help with address of function resolution
8984// - allows us to avoid passing around all those ugly parameters
8985class AddressOfFunctionResolver
8986{
8987  Sema& S;
8988  Expr* SourceExpr;
8989  const QualType& TargetType;
8990  QualType TargetFunctionType; // Extracted function type from target type
8991
8992  bool Complain;
8993  //DeclAccessPair& ResultFunctionAccessPair;
8994  ASTContext& Context;
8995
8996  bool TargetTypeIsNonStaticMemberFunction;
8997  bool FoundNonTemplateFunction;
8998
8999  OverloadExpr::FindResult OvlExprInfo;
9000  OverloadExpr *OvlExpr;
9001  TemplateArgumentListInfo OvlExplicitTemplateArgs;
9002  SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9003
9004public:
9005  AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9006                            const QualType& TargetType, bool Complain)
9007    : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9008      Complain(Complain), Context(S.getASTContext()),
9009      TargetTypeIsNonStaticMemberFunction(
9010                                    !!TargetType->getAs<MemberPointerType>()),
9011      FoundNonTemplateFunction(false),
9012      OvlExprInfo(OverloadExpr::find(SourceExpr)),
9013      OvlExpr(OvlExprInfo.Expression)
9014  {
9015    ExtractUnqualifiedFunctionTypeFromTargetType();
9016
9017    if (!TargetFunctionType->isFunctionType()) {
9018      if (OvlExpr->hasExplicitTemplateArgs()) {
9019        DeclAccessPair dap;
9020        if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
9021                                            OvlExpr, false, &dap) ) {
9022
9023          if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9024            if (!Method->isStatic()) {
9025              // If the target type is a non-function type and the function
9026              // found is a non-static member function, pretend as if that was
9027              // the target, it's the only possible type to end up with.
9028              TargetTypeIsNonStaticMemberFunction = true;
9029
9030              // And skip adding the function if its not in the proper form.
9031              // We'll diagnose this due to an empty set of functions.
9032              if (!OvlExprInfo.HasFormOfMemberPointer)
9033                return;
9034            }
9035          }
9036
9037          Matches.push_back(std::make_pair(dap,Fn));
9038        }
9039      }
9040      return;
9041    }
9042
9043    if (OvlExpr->hasExplicitTemplateArgs())
9044      OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9045
9046    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9047      // C++ [over.over]p4:
9048      //   If more than one function is selected, [...]
9049      if (Matches.size() > 1) {
9050        if (FoundNonTemplateFunction)
9051          EliminateAllTemplateMatches();
9052        else
9053          EliminateAllExceptMostSpecializedTemplate();
9054      }
9055    }
9056  }
9057
9058private:
9059  bool isTargetTypeAFunction() const {
9060    return TargetFunctionType->isFunctionType();
9061  }
9062
9063  // [ToType]     [Return]
9064
9065  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9066  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9067  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9068  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9069    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9070  }
9071
9072  // return true if any matching specializations were found
9073  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9074                                   const DeclAccessPair& CurAccessFunPair) {
9075    if (CXXMethodDecl *Method
9076              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9077      // Skip non-static function templates when converting to pointer, and
9078      // static when converting to member pointer.
9079      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9080        return false;
9081    }
9082    else if (TargetTypeIsNonStaticMemberFunction)
9083      return false;
9084
9085    // C++ [over.over]p2:
9086    //   If the name is a function template, template argument deduction is
9087    //   done (14.8.2.2), and if the argument deduction succeeds, the
9088    //   resulting template argument list is used to generate a single
9089    //   function template specialization, which is added to the set of
9090    //   overloaded functions considered.
9091    FunctionDecl *Specialization = 0;
9092    TemplateDeductionInfo Info(OvlExpr->getNameLoc());
9093    if (Sema::TemplateDeductionResult Result
9094          = S.DeduceTemplateArguments(FunctionTemplate,
9095                                      &OvlExplicitTemplateArgs,
9096                                      TargetFunctionType, Specialization,
9097                                      Info)) {
9098      // FIXME: make a note of the failed deduction for diagnostics.
9099      (void)Result;
9100      return false;
9101    }
9102
9103    // Template argument deduction ensures that we have an exact match.
9104    // This function template specicalization works.
9105    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9106    assert(TargetFunctionType
9107                      == Context.getCanonicalType(Specialization->getType()));
9108    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9109    return true;
9110  }
9111
9112  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9113                                      const DeclAccessPair& CurAccessFunPair) {
9114    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9115      // Skip non-static functions when converting to pointer, and static
9116      // when converting to member pointer.
9117      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9118        return false;
9119    }
9120    else if (TargetTypeIsNonStaticMemberFunction)
9121      return false;
9122
9123    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9124      if (S.getLangOpts().CUDA)
9125        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9126          if (S.CheckCUDATarget(Caller, FunDecl))
9127            return false;
9128
9129      QualType ResultTy;
9130      if (Context.hasSameUnqualifiedType(TargetFunctionType,
9131                                         FunDecl->getType()) ||
9132          S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9133                                 ResultTy)) {
9134        Matches.push_back(std::make_pair(CurAccessFunPair,
9135          cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9136        FoundNonTemplateFunction = true;
9137        return true;
9138      }
9139    }
9140
9141    return false;
9142  }
9143
9144  bool FindAllFunctionsThatMatchTargetTypeExactly() {
9145    bool Ret = false;
9146
9147    // If the overload expression doesn't have the form of a pointer to
9148    // member, don't try to convert it to a pointer-to-member type.
9149    if (IsInvalidFormOfPointerToMemberFunction())
9150      return false;
9151
9152    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9153                               E = OvlExpr->decls_end();
9154         I != E; ++I) {
9155      // Look through any using declarations to find the underlying function.
9156      NamedDecl *Fn = (*I)->getUnderlyingDecl();
9157
9158      // C++ [over.over]p3:
9159      //   Non-member functions and static member functions match
9160      //   targets of type "pointer-to-function" or "reference-to-function."
9161      //   Nonstatic member functions match targets of
9162      //   type "pointer-to-member-function."
9163      // Note that according to DR 247, the containing class does not matter.
9164      if (FunctionTemplateDecl *FunctionTemplate
9165                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
9166        if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9167          Ret = true;
9168      }
9169      // If we have explicit template arguments supplied, skip non-templates.
9170      else if (!OvlExpr->hasExplicitTemplateArgs() &&
9171               AddMatchingNonTemplateFunction(Fn, I.getPair()))
9172        Ret = true;
9173    }
9174    assert(Ret || Matches.empty());
9175    return Ret;
9176  }
9177
9178  void EliminateAllExceptMostSpecializedTemplate() {
9179    //   [...] and any given function template specialization F1 is
9180    //   eliminated if the set contains a second function template
9181    //   specialization whose function template is more specialized
9182    //   than the function template of F1 according to the partial
9183    //   ordering rules of 14.5.5.2.
9184
9185    // The algorithm specified above is quadratic. We instead use a
9186    // two-pass algorithm (similar to the one used to identify the
9187    // best viable function in an overload set) that identifies the
9188    // best function template (if it exists).
9189
9190    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9191    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9192      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9193
9194    UnresolvedSetIterator Result =
9195      S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9196                           TPOC_Other, 0, SourceExpr->getLocStart(),
9197                           S.PDiag(),
9198                           S.PDiag(diag::err_addr_ovl_ambiguous)
9199                             << Matches[0].second->getDeclName(),
9200                           S.PDiag(diag::note_ovl_candidate)
9201                             << (unsigned) oc_function_template,
9202                           Complain, TargetFunctionType);
9203
9204    if (Result != MatchesCopy.end()) {
9205      // Make it the first and only element
9206      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9207      Matches[0].second = cast<FunctionDecl>(*Result);
9208      Matches.resize(1);
9209    }
9210  }
9211
9212  void EliminateAllTemplateMatches() {
9213    //   [...] any function template specializations in the set are
9214    //   eliminated if the set also contains a non-template function, [...]
9215    for (unsigned I = 0, N = Matches.size(); I != N; ) {
9216      if (Matches[I].second->getPrimaryTemplate() == 0)
9217        ++I;
9218      else {
9219        Matches[I] = Matches[--N];
9220        Matches.set_size(N);
9221      }
9222    }
9223  }
9224
9225public:
9226  void ComplainNoMatchesFound() const {
9227    assert(Matches.empty());
9228    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9229        << OvlExpr->getName() << TargetFunctionType
9230        << OvlExpr->getSourceRange();
9231    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9232  }
9233
9234  bool IsInvalidFormOfPointerToMemberFunction() const {
9235    return TargetTypeIsNonStaticMemberFunction &&
9236      !OvlExprInfo.HasFormOfMemberPointer;
9237  }
9238
9239  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9240      // TODO: Should we condition this on whether any functions might
9241      // have matched, or is it more appropriate to do that in callers?
9242      // TODO: a fixit wouldn't hurt.
9243      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9244        << TargetType << OvlExpr->getSourceRange();
9245  }
9246
9247  void ComplainOfInvalidConversion() const {
9248    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9249      << OvlExpr->getName() << TargetType;
9250  }
9251
9252  void ComplainMultipleMatchesFound() const {
9253    assert(Matches.size() > 1);
9254    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9255      << OvlExpr->getName()
9256      << OvlExpr->getSourceRange();
9257    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9258  }
9259
9260  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9261
9262  int getNumMatches() const { return Matches.size(); }
9263
9264  FunctionDecl* getMatchingFunctionDecl() const {
9265    if (Matches.size() != 1) return 0;
9266    return Matches[0].second;
9267  }
9268
9269  const DeclAccessPair* getMatchingFunctionAccessPair() const {
9270    if (Matches.size() != 1) return 0;
9271    return &Matches[0].first;
9272  }
9273};
9274
9275/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9276/// an overloaded function (C++ [over.over]), where @p From is an
9277/// expression with overloaded function type and @p ToType is the type
9278/// we're trying to resolve to. For example:
9279///
9280/// @code
9281/// int f(double);
9282/// int f(int);
9283///
9284/// int (*pfd)(double) = f; // selects f(double)
9285/// @endcode
9286///
9287/// This routine returns the resulting FunctionDecl if it could be
9288/// resolved, and NULL otherwise. When @p Complain is true, this
9289/// routine will emit diagnostics if there is an error.
9290FunctionDecl *
9291Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9292                                         QualType TargetType,
9293                                         bool Complain,
9294                                         DeclAccessPair &FoundResult,
9295                                         bool *pHadMultipleCandidates) {
9296  assert(AddressOfExpr->getType() == Context.OverloadTy);
9297
9298  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9299                                     Complain);
9300  int NumMatches = Resolver.getNumMatches();
9301  FunctionDecl* Fn = 0;
9302  if (NumMatches == 0 && Complain) {
9303    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9304      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9305    else
9306      Resolver.ComplainNoMatchesFound();
9307  }
9308  else if (NumMatches > 1 && Complain)
9309    Resolver.ComplainMultipleMatchesFound();
9310  else if (NumMatches == 1) {
9311    Fn = Resolver.getMatchingFunctionDecl();
9312    assert(Fn);
9313    FoundResult = *Resolver.getMatchingFunctionAccessPair();
9314    if (Complain)
9315      CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9316  }
9317
9318  if (pHadMultipleCandidates)
9319    *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9320  return Fn;
9321}
9322
9323/// \brief Given an expression that refers to an overloaded function, try to
9324/// resolve that overloaded function expression down to a single function.
9325///
9326/// This routine can only resolve template-ids that refer to a single function
9327/// template, where that template-id refers to a single template whose template
9328/// arguments are either provided by the template-id or have defaults,
9329/// as described in C++0x [temp.arg.explicit]p3.
9330FunctionDecl *
9331Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9332                                                  bool Complain,
9333                                                  DeclAccessPair *FoundResult) {
9334  // C++ [over.over]p1:
9335  //   [...] [Note: any redundant set of parentheses surrounding the
9336  //   overloaded function name is ignored (5.1). ]
9337  // C++ [over.over]p1:
9338  //   [...] The overloaded function name can be preceded by the &
9339  //   operator.
9340
9341  // If we didn't actually find any template-ids, we're done.
9342  if (!ovl->hasExplicitTemplateArgs())
9343    return 0;
9344
9345  TemplateArgumentListInfo ExplicitTemplateArgs;
9346  ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9347
9348  // Look through all of the overloaded functions, searching for one
9349  // whose type matches exactly.
9350  FunctionDecl *Matched = 0;
9351  for (UnresolvedSetIterator I = ovl->decls_begin(),
9352         E = ovl->decls_end(); I != E; ++I) {
9353    // C++0x [temp.arg.explicit]p3:
9354    //   [...] In contexts where deduction is done and fails, or in contexts
9355    //   where deduction is not done, if a template argument list is
9356    //   specified and it, along with any default template arguments,
9357    //   identifies a single function template specialization, then the
9358    //   template-id is an lvalue for the function template specialization.
9359    FunctionTemplateDecl *FunctionTemplate
9360      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9361
9362    // C++ [over.over]p2:
9363    //   If the name is a function template, template argument deduction is
9364    //   done (14.8.2.2), and if the argument deduction succeeds, the
9365    //   resulting template argument list is used to generate a single
9366    //   function template specialization, which is added to the set of
9367    //   overloaded functions considered.
9368    FunctionDecl *Specialization = 0;
9369    TemplateDeductionInfo Info(ovl->getNameLoc());
9370    if (TemplateDeductionResult Result
9371          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9372                                    Specialization, Info)) {
9373      // FIXME: make a note of the failed deduction for diagnostics.
9374      (void)Result;
9375      continue;
9376    }
9377
9378    assert(Specialization && "no specialization and no error?");
9379
9380    // Multiple matches; we can't resolve to a single declaration.
9381    if (Matched) {
9382      if (Complain) {
9383        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9384          << ovl->getName();
9385        NoteAllOverloadCandidates(ovl);
9386      }
9387      return 0;
9388    }
9389
9390    Matched = Specialization;
9391    if (FoundResult) *FoundResult = I.getPair();
9392  }
9393
9394  return Matched;
9395}
9396
9397
9398
9399
9400// Resolve and fix an overloaded expression that can be resolved
9401// because it identifies a single function template specialization.
9402//
9403// Last three arguments should only be supplied if Complain = true
9404//
9405// Return true if it was logically possible to so resolve the
9406// expression, regardless of whether or not it succeeded.  Always
9407// returns true if 'complain' is set.
9408bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9409                      ExprResult &SrcExpr, bool doFunctionPointerConverion,
9410                   bool complain, const SourceRange& OpRangeForComplaining,
9411                                           QualType DestTypeForComplaining,
9412                                            unsigned DiagIDForComplaining) {
9413  assert(SrcExpr.get()->getType() == Context.OverloadTy);
9414
9415  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9416
9417  DeclAccessPair found;
9418  ExprResult SingleFunctionExpression;
9419  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9420                           ovl.Expression, /*complain*/ false, &found)) {
9421    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9422      SrcExpr = ExprError();
9423      return true;
9424    }
9425
9426    // It is only correct to resolve to an instance method if we're
9427    // resolving a form that's permitted to be a pointer to member.
9428    // Otherwise we'll end up making a bound member expression, which
9429    // is illegal in all the contexts we resolve like this.
9430    if (!ovl.HasFormOfMemberPointer &&
9431        isa<CXXMethodDecl>(fn) &&
9432        cast<CXXMethodDecl>(fn)->isInstance()) {
9433      if (!complain) return false;
9434
9435      Diag(ovl.Expression->getExprLoc(),
9436           diag::err_bound_member_function)
9437        << 0 << ovl.Expression->getSourceRange();
9438
9439      // TODO: I believe we only end up here if there's a mix of
9440      // static and non-static candidates (otherwise the expression
9441      // would have 'bound member' type, not 'overload' type).
9442      // Ideally we would note which candidate was chosen and why
9443      // the static candidates were rejected.
9444      SrcExpr = ExprError();
9445      return true;
9446    }
9447
9448    // Fix the expression to refer to 'fn'.
9449    SingleFunctionExpression =
9450      Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9451
9452    // If desired, do function-to-pointer decay.
9453    if (doFunctionPointerConverion) {
9454      SingleFunctionExpression =
9455        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9456      if (SingleFunctionExpression.isInvalid()) {
9457        SrcExpr = ExprError();
9458        return true;
9459      }
9460    }
9461  }
9462
9463  if (!SingleFunctionExpression.isUsable()) {
9464    if (complain) {
9465      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9466        << ovl.Expression->getName()
9467        << DestTypeForComplaining
9468        << OpRangeForComplaining
9469        << ovl.Expression->getQualifierLoc().getSourceRange();
9470      NoteAllOverloadCandidates(SrcExpr.get());
9471
9472      SrcExpr = ExprError();
9473      return true;
9474    }
9475
9476    return false;
9477  }
9478
9479  SrcExpr = SingleFunctionExpression;
9480  return true;
9481}
9482
9483/// \brief Add a single candidate to the overload set.
9484static void AddOverloadedCallCandidate(Sema &S,
9485                                       DeclAccessPair FoundDecl,
9486                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
9487                                       ArrayRef<Expr *> Args,
9488                                       OverloadCandidateSet &CandidateSet,
9489                                       bool PartialOverloading,
9490                                       bool KnownValid) {
9491  NamedDecl *Callee = FoundDecl.getDecl();
9492  if (isa<UsingShadowDecl>(Callee))
9493    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9494
9495  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9496    if (ExplicitTemplateArgs) {
9497      assert(!KnownValid && "Explicit template arguments?");
9498      return;
9499    }
9500    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9501                           PartialOverloading);
9502    return;
9503  }
9504
9505  if (FunctionTemplateDecl *FuncTemplate
9506      = dyn_cast<FunctionTemplateDecl>(Callee)) {
9507    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9508                                   ExplicitTemplateArgs, Args, CandidateSet);
9509    return;
9510  }
9511
9512  assert(!KnownValid && "unhandled case in overloaded call candidate");
9513}
9514
9515/// \brief Add the overload candidates named by callee and/or found by argument
9516/// dependent lookup to the given overload set.
9517void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9518                                       ArrayRef<Expr *> Args,
9519                                       OverloadCandidateSet &CandidateSet,
9520                                       bool PartialOverloading) {
9521
9522#ifndef NDEBUG
9523  // Verify that ArgumentDependentLookup is consistent with the rules
9524  // in C++0x [basic.lookup.argdep]p3:
9525  //
9526  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9527  //   and let Y be the lookup set produced by argument dependent
9528  //   lookup (defined as follows). If X contains
9529  //
9530  //     -- a declaration of a class member, or
9531  //
9532  //     -- a block-scope function declaration that is not a
9533  //        using-declaration, or
9534  //
9535  //     -- a declaration that is neither a function or a function
9536  //        template
9537  //
9538  //   then Y is empty.
9539
9540  if (ULE->requiresADL()) {
9541    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9542           E = ULE->decls_end(); I != E; ++I) {
9543      assert(!(*I)->getDeclContext()->isRecord());
9544      assert(isa<UsingShadowDecl>(*I) ||
9545             !(*I)->getDeclContext()->isFunctionOrMethod());
9546      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9547    }
9548  }
9549#endif
9550
9551  // It would be nice to avoid this copy.
9552  TemplateArgumentListInfo TABuffer;
9553  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9554  if (ULE->hasExplicitTemplateArgs()) {
9555    ULE->copyTemplateArgumentsInto(TABuffer);
9556    ExplicitTemplateArgs = &TABuffer;
9557  }
9558
9559  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9560         E = ULE->decls_end(); I != E; ++I)
9561    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9562                               CandidateSet, PartialOverloading,
9563                               /*KnownValid*/ true);
9564
9565  if (ULE->requiresADL())
9566    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9567                                         ULE->getExprLoc(),
9568                                         Args, ExplicitTemplateArgs,
9569                                         CandidateSet, PartialOverloading);
9570}
9571
9572/// Attempt to recover from an ill-formed use of a non-dependent name in a
9573/// template, where the non-dependent name was declared after the template
9574/// was defined. This is common in code written for a compilers which do not
9575/// correctly implement two-stage name lookup.
9576///
9577/// Returns true if a viable candidate was found and a diagnostic was issued.
9578static bool
9579DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9580                       const CXXScopeSpec &SS, LookupResult &R,
9581                       TemplateArgumentListInfo *ExplicitTemplateArgs,
9582                       ArrayRef<Expr *> Args) {
9583  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9584    return false;
9585
9586  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9587    if (DC->isTransparentContext())
9588      continue;
9589
9590    SemaRef.LookupQualifiedName(R, DC);
9591
9592    if (!R.empty()) {
9593      R.suppressDiagnostics();
9594
9595      if (isa<CXXRecordDecl>(DC)) {
9596        // Don't diagnose names we find in classes; we get much better
9597        // diagnostics for these from DiagnoseEmptyLookup.
9598        R.clear();
9599        return false;
9600      }
9601
9602      OverloadCandidateSet Candidates(FnLoc);
9603      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9604        AddOverloadedCallCandidate(SemaRef, I.getPair(),
9605                                   ExplicitTemplateArgs, Args,
9606                                   Candidates, false, /*KnownValid*/ false);
9607
9608      OverloadCandidateSet::iterator Best;
9609      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9610        // No viable functions. Don't bother the user with notes for functions
9611        // which don't work and shouldn't be found anyway.
9612        R.clear();
9613        return false;
9614      }
9615
9616      // Find the namespaces where ADL would have looked, and suggest
9617      // declaring the function there instead.
9618      Sema::AssociatedNamespaceSet AssociatedNamespaces;
9619      Sema::AssociatedClassSet AssociatedClasses;
9620      SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
9621                                                 AssociatedNamespaces,
9622                                                 AssociatedClasses);
9623      Sema::AssociatedNamespaceSet SuggestedNamespaces;
9624      DeclContext *Std = SemaRef.getStdNamespace();
9625      for (Sema::AssociatedNamespaceSet::iterator
9626             it = AssociatedNamespaces.begin(),
9627             end = AssociatedNamespaces.end(); it != end; ++it) {
9628        // Never suggest declaring a function within namespace 'std'.
9629        if (Std && Std->Encloses(*it))
9630          continue;
9631
9632        // Never suggest declaring a function within a namespace with a reserved
9633        // name, like __gnu_cxx.
9634        NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9635        if (NS &&
9636            NS->getQualifiedNameAsString().find("__") != std::string::npos)
9637          continue;
9638
9639        SuggestedNamespaces.insert(*it);
9640      }
9641
9642      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9643        << R.getLookupName();
9644      if (SuggestedNamespaces.empty()) {
9645        SemaRef.Diag(Best->Function->getLocation(),
9646                     diag::note_not_found_by_two_phase_lookup)
9647          << R.getLookupName() << 0;
9648      } else if (SuggestedNamespaces.size() == 1) {
9649        SemaRef.Diag(Best->Function->getLocation(),
9650                     diag::note_not_found_by_two_phase_lookup)
9651          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9652      } else {
9653        // FIXME: It would be useful to list the associated namespaces here,
9654        // but the diagnostics infrastructure doesn't provide a way to produce
9655        // a localized representation of a list of items.
9656        SemaRef.Diag(Best->Function->getLocation(),
9657                     diag::note_not_found_by_two_phase_lookup)
9658          << R.getLookupName() << 2;
9659      }
9660
9661      // Try to recover by calling this function.
9662      return true;
9663    }
9664
9665    R.clear();
9666  }
9667
9668  return false;
9669}
9670
9671/// Attempt to recover from ill-formed use of a non-dependent operator in a
9672/// template, where the non-dependent operator was declared after the template
9673/// was defined.
9674///
9675/// Returns true if a viable candidate was found and a diagnostic was issued.
9676static bool
9677DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9678                               SourceLocation OpLoc,
9679                               ArrayRef<Expr *> Args) {
9680  DeclarationName OpName =
9681    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9682  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9683  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9684                                /*ExplicitTemplateArgs=*/0, Args);
9685}
9686
9687namespace {
9688// Callback to limit the allowed keywords and to only accept typo corrections
9689// that are keywords or whose decls refer to functions (or template functions)
9690// that accept the given number of arguments.
9691class RecoveryCallCCC : public CorrectionCandidateCallback {
9692 public:
9693  RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9694      : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9695    WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
9696    WantRemainingKeywords = false;
9697  }
9698
9699  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9700    if (!candidate.getCorrectionDecl())
9701      return candidate.isKeyword();
9702
9703    for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9704           DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9705      FunctionDecl *FD = 0;
9706      NamedDecl *ND = (*DI)->getUnderlyingDecl();
9707      if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9708        FD = FTD->getTemplatedDecl();
9709      if (!HasExplicitTemplateArgs && !FD) {
9710        if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9711          // If the Decl is neither a function nor a template function,
9712          // determine if it is a pointer or reference to a function. If so,
9713          // check against the number of arguments expected for the pointee.
9714          QualType ValType = cast<ValueDecl>(ND)->getType();
9715          if (ValType->isAnyPointerType() || ValType->isReferenceType())
9716            ValType = ValType->getPointeeType();
9717          if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9718            if (FPT->getNumArgs() == NumArgs)
9719              return true;
9720        }
9721      }
9722      if (FD && FD->getNumParams() >= NumArgs &&
9723          FD->getMinRequiredArguments() <= NumArgs)
9724        return true;
9725    }
9726    return false;
9727  }
9728
9729 private:
9730  unsigned NumArgs;
9731  bool HasExplicitTemplateArgs;
9732};
9733
9734// Callback that effectively disabled typo correction
9735class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9736 public:
9737  NoTypoCorrectionCCC() {
9738    WantTypeSpecifiers = false;
9739    WantExpressionKeywords = false;
9740    WantCXXNamedCasts = false;
9741    WantRemainingKeywords = false;
9742  }
9743
9744  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9745    return false;
9746  }
9747};
9748
9749class BuildRecoveryCallExprRAII {
9750  Sema &SemaRef;
9751public:
9752  BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9753    assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9754    SemaRef.IsBuildingRecoveryCallExpr = true;
9755  }
9756
9757  ~BuildRecoveryCallExprRAII() {
9758    SemaRef.IsBuildingRecoveryCallExpr = false;
9759  }
9760};
9761
9762}
9763
9764/// Attempts to recover from a call where no functions were found.
9765///
9766/// Returns true if new candidates were found.
9767static ExprResult
9768BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9769                      UnresolvedLookupExpr *ULE,
9770                      SourceLocation LParenLoc,
9771                      llvm::MutableArrayRef<Expr *> Args,
9772                      SourceLocation RParenLoc,
9773                      bool EmptyLookup, bool AllowTypoCorrection) {
9774  // Do not try to recover if it is already building a recovery call.
9775  // This stops infinite loops for template instantiations like
9776  //
9777  // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9778  // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9779  //
9780  if (SemaRef.IsBuildingRecoveryCallExpr)
9781    return ExprError();
9782  BuildRecoveryCallExprRAII RCE(SemaRef);
9783
9784  CXXScopeSpec SS;
9785  SS.Adopt(ULE->getQualifierLoc());
9786  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9787
9788  TemplateArgumentListInfo TABuffer;
9789  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9790  if (ULE->hasExplicitTemplateArgs()) {
9791    ULE->copyTemplateArgumentsInto(TABuffer);
9792    ExplicitTemplateArgs = &TABuffer;
9793  }
9794
9795  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9796                 Sema::LookupOrdinaryName);
9797  RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
9798  NoTypoCorrectionCCC RejectAll;
9799  CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9800      (CorrectionCandidateCallback*)&Validator :
9801      (CorrectionCandidateCallback*)&RejectAll;
9802  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9803                              ExplicitTemplateArgs, Args) &&
9804      (!EmptyLookup ||
9805       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
9806                                   ExplicitTemplateArgs, Args)))
9807    return ExprError();
9808
9809  assert(!R.empty() && "lookup results empty despite recovery");
9810
9811  // Build an implicit member call if appropriate.  Just drop the
9812  // casts and such from the call, we don't really care.
9813  ExprResult NewFn = ExprError();
9814  if ((*R.begin())->isCXXClassMember())
9815    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9816                                                    R, ExplicitTemplateArgs);
9817  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
9818    NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9819                                        ExplicitTemplateArgs);
9820  else
9821    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9822
9823  if (NewFn.isInvalid())
9824    return ExprError();
9825
9826  // This shouldn't cause an infinite loop because we're giving it
9827  // an expression with viable lookup results, which should never
9828  // end up here.
9829  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
9830                               MultiExprArg(Args.data(), Args.size()),
9831                               RParenLoc);
9832}
9833
9834/// \brief Constructs and populates an OverloadedCandidateSet from
9835/// the given function.
9836/// \returns true when an the ExprResult output parameter has been set.
9837bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9838                                  UnresolvedLookupExpr *ULE,
9839                                  Expr **Args, unsigned NumArgs,
9840                                  SourceLocation RParenLoc,
9841                                  OverloadCandidateSet *CandidateSet,
9842                                  ExprResult *Result) {
9843#ifndef NDEBUG
9844  if (ULE->requiresADL()) {
9845    // To do ADL, we must have found an unqualified name.
9846    assert(!ULE->getQualifier() && "qualified name with ADL");
9847
9848    // We don't perform ADL for implicit declarations of builtins.
9849    // Verify that this was correctly set up.
9850    FunctionDecl *F;
9851    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9852        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9853        F->getBuiltinID() && F->isImplicit())
9854      llvm_unreachable("performing ADL for builtin");
9855
9856    // We don't perform ADL in C.
9857    assert(getLangOpts().CPlusPlus && "ADL enabled in C");
9858  }
9859#endif
9860
9861  UnbridgedCastsSet UnbridgedCasts;
9862  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9863    *Result = ExprError();
9864    return true;
9865  }
9866
9867  // Add the functions denoted by the callee to the set of candidate
9868  // functions, including those from argument-dependent lookup.
9869  AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9870                              *CandidateSet);
9871
9872  // If we found nothing, try to recover.
9873  // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9874  // out if it fails.
9875  if (CandidateSet->empty()) {
9876    // In Microsoft mode, if we are inside a template class member function then
9877    // create a type dependent CallExpr. The goal is to postpone name lookup
9878    // to instantiation time to be able to search into type dependent base
9879    // classes.
9880    if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
9881        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
9882      CallExpr *CE = new (Context) CallExpr(Context, Fn,
9883                                            llvm::makeArrayRef(Args, NumArgs),
9884                                            Context.DependentTy, VK_RValue,
9885                                            RParenLoc);
9886      CE->setTypeDependent(true);
9887      *Result = Owned(CE);
9888      return true;
9889    }
9890    return false;
9891  }
9892
9893  UnbridgedCasts.restore();
9894  return false;
9895}
9896
9897/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9898/// the completed call expression. If overload resolution fails, emits
9899/// diagnostics and returns ExprError()
9900static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9901                                           UnresolvedLookupExpr *ULE,
9902                                           SourceLocation LParenLoc,
9903                                           Expr **Args, unsigned NumArgs,
9904                                           SourceLocation RParenLoc,
9905                                           Expr *ExecConfig,
9906                                           OverloadCandidateSet *CandidateSet,
9907                                           OverloadCandidateSet::iterator *Best,
9908                                           OverloadingResult OverloadResult,
9909                                           bool AllowTypoCorrection) {
9910  if (CandidateSet->empty())
9911    return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9912                                 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9913                                 RParenLoc, /*EmptyLookup=*/true,
9914                                 AllowTypoCorrection);
9915
9916  switch (OverloadResult) {
9917  case OR_Success: {
9918    FunctionDecl *FDecl = (*Best)->Function;
9919    SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9920    SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9921    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9922    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9923                                         RParenLoc, ExecConfig);
9924  }
9925
9926  case OR_No_Viable_Function: {
9927    // Try to recover by looking for viable functions which the user might
9928    // have meant to call.
9929    ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9930                                  llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9931                                                RParenLoc,
9932                                                /*EmptyLookup=*/false,
9933                                                AllowTypoCorrection);
9934    if (!Recovery.isInvalid())
9935      return Recovery;
9936
9937    SemaRef.Diag(Fn->getLocStart(),
9938         diag::err_ovl_no_viable_function_in_call)
9939      << ULE->getName() << Fn->getSourceRange();
9940    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9941                                 llvm::makeArrayRef(Args, NumArgs));
9942    break;
9943  }
9944
9945  case OR_Ambiguous:
9946    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
9947      << ULE->getName() << Fn->getSourceRange();
9948    CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9949                                 llvm::makeArrayRef(Args, NumArgs));
9950    break;
9951
9952  case OR_Deleted: {
9953    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9954      << (*Best)->Function->isDeleted()
9955      << ULE->getName()
9956      << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9957      << Fn->getSourceRange();
9958    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9959                                 llvm::makeArrayRef(Args, NumArgs));
9960
9961    // We emitted an error for the unvailable/deleted function call but keep
9962    // the call in the AST.
9963    FunctionDecl *FDecl = (*Best)->Function;
9964    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9965    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9966                                 RParenLoc, ExecConfig);
9967  }
9968  }
9969
9970  // Overload resolution failed.
9971  return ExprError();
9972}
9973
9974/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9975/// (which eventually refers to the declaration Func) and the call
9976/// arguments Args/NumArgs, attempt to resolve the function call down
9977/// to a specific function. If overload resolution succeeds, returns
9978/// the call expression produced by overload resolution.
9979/// Otherwise, emits diagnostics and returns ExprError.
9980ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9981                                         UnresolvedLookupExpr *ULE,
9982                                         SourceLocation LParenLoc,
9983                                         Expr **Args, unsigned NumArgs,
9984                                         SourceLocation RParenLoc,
9985                                         Expr *ExecConfig,
9986                                         bool AllowTypoCorrection) {
9987  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9988  ExprResult result;
9989
9990  if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9991                             &CandidateSet, &result))
9992    return result;
9993
9994  OverloadCandidateSet::iterator Best;
9995  OverloadingResult OverloadResult =
9996      CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9997
9998  return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9999                                  RParenLoc, ExecConfig, &CandidateSet,
10000                                  &Best, OverloadResult,
10001                                  AllowTypoCorrection);
10002}
10003
10004static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10005  return Functions.size() > 1 ||
10006    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10007}
10008
10009/// \brief Create a unary operation that may resolve to an overloaded
10010/// operator.
10011///
10012/// \param OpLoc The location of the operator itself (e.g., '*').
10013///
10014/// \param OpcIn The UnaryOperator::Opcode that describes this
10015/// operator.
10016///
10017/// \param Fns The set of non-member functions that will be
10018/// considered by overload resolution. The caller needs to build this
10019/// set based on the context using, e.g.,
10020/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10021/// set should not contain any member functions; those will be added
10022/// by CreateOverloadedUnaryOp().
10023///
10024/// \param Input The input argument.
10025ExprResult
10026Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10027                              const UnresolvedSetImpl &Fns,
10028                              Expr *Input) {
10029  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10030
10031  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10032  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10033  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10034  // TODO: provide better source location info.
10035  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10036
10037  if (checkPlaceholderForOverload(*this, Input))
10038    return ExprError();
10039
10040  Expr *Args[2] = { Input, 0 };
10041  unsigned NumArgs = 1;
10042
10043  // For post-increment and post-decrement, add the implicit '0' as
10044  // the second argument, so that we know this is a post-increment or
10045  // post-decrement.
10046  if (Opc == UO_PostInc || Opc == UO_PostDec) {
10047    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10048    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10049                                     SourceLocation());
10050    NumArgs = 2;
10051  }
10052
10053  if (Input->isTypeDependent()) {
10054    if (Fns.empty())
10055      return Owned(new (Context) UnaryOperator(Input,
10056                                               Opc,
10057                                               Context.DependentTy,
10058                                               VK_RValue, OK_Ordinary,
10059                                               OpLoc));
10060
10061    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10062    UnresolvedLookupExpr *Fn
10063      = UnresolvedLookupExpr::Create(Context, NamingClass,
10064                                     NestedNameSpecifierLoc(), OpNameInfo,
10065                                     /*ADL*/ true, IsOverloaded(Fns),
10066                                     Fns.begin(), Fns.end());
10067    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
10068                                              llvm::makeArrayRef(Args, NumArgs),
10069                                                   Context.DependentTy,
10070                                                   VK_RValue,
10071                                                   OpLoc, false));
10072  }
10073
10074  // Build an empty overload set.
10075  OverloadCandidateSet CandidateSet(OpLoc);
10076
10077  // Add the candidates from the given function set.
10078  AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10079                        false);
10080
10081  // Add operator candidates that are member functions.
10082  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10083
10084  // Add candidates from ADL.
10085  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10086                                       OpLoc, llvm::makeArrayRef(Args, NumArgs),
10087                                       /*ExplicitTemplateArgs*/ 0,
10088                                       CandidateSet);
10089
10090  // Add builtin operator candidates.
10091  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10092
10093  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10094
10095  // Perform overload resolution.
10096  OverloadCandidateSet::iterator Best;
10097  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10098  case OR_Success: {
10099    // We found a built-in operator or an overloaded operator.
10100    FunctionDecl *FnDecl = Best->Function;
10101
10102    if (FnDecl) {
10103      // We matched an overloaded operator. Build a call to that
10104      // operator.
10105
10106      // Convert the arguments.
10107      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10108        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
10109
10110        ExprResult InputRes =
10111          PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10112                                              Best->FoundDecl, Method);
10113        if (InputRes.isInvalid())
10114          return ExprError();
10115        Input = InputRes.take();
10116      } else {
10117        // Convert the arguments.
10118        ExprResult InputInit
10119          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10120                                                      Context,
10121                                                      FnDecl->getParamDecl(0)),
10122                                      SourceLocation(),
10123                                      Input);
10124        if (InputInit.isInvalid())
10125          return ExprError();
10126        Input = InputInit.take();
10127      }
10128
10129      // Determine the result type.
10130      QualType ResultTy = FnDecl->getResultType();
10131      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10132      ResultTy = ResultTy.getNonLValueExprType(Context);
10133
10134      // Build the actual expression node.
10135      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10136                                                HadMultipleCandidates, OpLoc);
10137      if (FnExpr.isInvalid())
10138        return ExprError();
10139
10140      Args[0] = Input;
10141      CallExpr *TheCall =
10142        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10143                                          llvm::makeArrayRef(Args, NumArgs),
10144                                          ResultTy, VK, OpLoc, false);
10145
10146      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10147                              FnDecl))
10148        return ExprError();
10149
10150      return MaybeBindToTemporary(TheCall);
10151    } else {
10152      // We matched a built-in operator. Convert the arguments, then
10153      // break out so that we will build the appropriate built-in
10154      // operator node.
10155      ExprResult InputRes =
10156        PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10157                                  Best->Conversions[0], AA_Passing);
10158      if (InputRes.isInvalid())
10159        return ExprError();
10160      Input = InputRes.take();
10161      break;
10162    }
10163  }
10164
10165  case OR_No_Viable_Function:
10166    // This is an erroneous use of an operator which can be overloaded by
10167    // a non-member function. Check for non-member operators which were
10168    // defined too late to be candidates.
10169    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10170                                       llvm::makeArrayRef(Args, NumArgs)))
10171      // FIXME: Recover by calling the found function.
10172      return ExprError();
10173
10174    // No viable function; fall through to handling this as a
10175    // built-in operator, which will produce an error message for us.
10176    break;
10177
10178  case OR_Ambiguous:
10179    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10180        << UnaryOperator::getOpcodeStr(Opc)
10181        << Input->getType()
10182        << Input->getSourceRange();
10183    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10184                                llvm::makeArrayRef(Args, NumArgs),
10185                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10186    return ExprError();
10187
10188  case OR_Deleted:
10189    Diag(OpLoc, diag::err_ovl_deleted_oper)
10190      << Best->Function->isDeleted()
10191      << UnaryOperator::getOpcodeStr(Opc)
10192      << getDeletedOrUnavailableSuffix(Best->Function)
10193      << Input->getSourceRange();
10194    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10195                                llvm::makeArrayRef(Args, NumArgs),
10196                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10197    return ExprError();
10198  }
10199
10200  // Either we found no viable overloaded operator or we matched a
10201  // built-in operator. In either case, fall through to trying to
10202  // build a built-in operation.
10203  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10204}
10205
10206/// \brief Create a binary operation that may resolve to an overloaded
10207/// operator.
10208///
10209/// \param OpLoc The location of the operator itself (e.g., '+').
10210///
10211/// \param OpcIn The BinaryOperator::Opcode that describes this
10212/// operator.
10213///
10214/// \param Fns The set of non-member functions that will be
10215/// considered by overload resolution. The caller needs to build this
10216/// set based on the context using, e.g.,
10217/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10218/// set should not contain any member functions; those will be added
10219/// by CreateOverloadedBinOp().
10220///
10221/// \param LHS Left-hand argument.
10222/// \param RHS Right-hand argument.
10223ExprResult
10224Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10225                            unsigned OpcIn,
10226                            const UnresolvedSetImpl &Fns,
10227                            Expr *LHS, Expr *RHS) {
10228  Expr *Args[2] = { LHS, RHS };
10229  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10230
10231  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10232  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10233  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10234
10235  // If either side is type-dependent, create an appropriate dependent
10236  // expression.
10237  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10238    if (Fns.empty()) {
10239      // If there are no functions to store, just build a dependent
10240      // BinaryOperator or CompoundAssignment.
10241      if (Opc <= BO_Assign || Opc > BO_OrAssign)
10242        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10243                                                  Context.DependentTy,
10244                                                  VK_RValue, OK_Ordinary,
10245                                                  OpLoc,
10246                                                  FPFeatures.fp_contract));
10247
10248      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10249                                                        Context.DependentTy,
10250                                                        VK_LValue,
10251                                                        OK_Ordinary,
10252                                                        Context.DependentTy,
10253                                                        Context.DependentTy,
10254                                                        OpLoc,
10255                                                        FPFeatures.fp_contract));
10256    }
10257
10258    // FIXME: save results of ADL from here?
10259    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10260    // TODO: provide better source location info in DNLoc component.
10261    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10262    UnresolvedLookupExpr *Fn
10263      = UnresolvedLookupExpr::Create(Context, NamingClass,
10264                                     NestedNameSpecifierLoc(), OpNameInfo,
10265                                     /*ADL*/ true, IsOverloaded(Fns),
10266                                     Fns.begin(), Fns.end());
10267    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10268                                                Context.DependentTy, VK_RValue,
10269                                                OpLoc, FPFeatures.fp_contract));
10270  }
10271
10272  // Always do placeholder-like conversions on the RHS.
10273  if (checkPlaceholderForOverload(*this, Args[1]))
10274    return ExprError();
10275
10276  // Do placeholder-like conversion on the LHS; note that we should
10277  // not get here with a PseudoObject LHS.
10278  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10279  if (checkPlaceholderForOverload(*this, Args[0]))
10280    return ExprError();
10281
10282  // If this is the assignment operator, we only perform overload resolution
10283  // if the left-hand side is a class or enumeration type. This is actually
10284  // a hack. The standard requires that we do overload resolution between the
10285  // various built-in candidates, but as DR507 points out, this can lead to
10286  // problems. So we do it this way, which pretty much follows what GCC does.
10287  // Note that we go the traditional code path for compound assignment forms.
10288  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10289    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10290
10291  // If this is the .* operator, which is not overloadable, just
10292  // create a built-in binary operator.
10293  if (Opc == BO_PtrMemD)
10294    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10295
10296  // Build an empty overload set.
10297  OverloadCandidateSet CandidateSet(OpLoc);
10298
10299  // Add the candidates from the given function set.
10300  AddFunctionCandidates(Fns, Args, CandidateSet, false);
10301
10302  // Add operator candidates that are member functions.
10303  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10304
10305  // Add candidates from ADL.
10306  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10307                                       OpLoc, Args,
10308                                       /*ExplicitTemplateArgs*/ 0,
10309                                       CandidateSet);
10310
10311  // Add builtin operator candidates.
10312  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10313
10314  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10315
10316  // Perform overload resolution.
10317  OverloadCandidateSet::iterator Best;
10318  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10319    case OR_Success: {
10320      // We found a built-in operator or an overloaded operator.
10321      FunctionDecl *FnDecl = Best->Function;
10322
10323      if (FnDecl) {
10324        // We matched an overloaded operator. Build a call to that
10325        // operator.
10326
10327        // Convert the arguments.
10328        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10329          // Best->Access is only meaningful for class members.
10330          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10331
10332          ExprResult Arg1 =
10333            PerformCopyInitialization(
10334              InitializedEntity::InitializeParameter(Context,
10335                                                     FnDecl->getParamDecl(0)),
10336              SourceLocation(), Owned(Args[1]));
10337          if (Arg1.isInvalid())
10338            return ExprError();
10339
10340          ExprResult Arg0 =
10341            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10342                                                Best->FoundDecl, Method);
10343          if (Arg0.isInvalid())
10344            return ExprError();
10345          Args[0] = Arg0.takeAs<Expr>();
10346          Args[1] = RHS = Arg1.takeAs<Expr>();
10347        } else {
10348          // Convert the arguments.
10349          ExprResult Arg0 = PerformCopyInitialization(
10350            InitializedEntity::InitializeParameter(Context,
10351                                                   FnDecl->getParamDecl(0)),
10352            SourceLocation(), Owned(Args[0]));
10353          if (Arg0.isInvalid())
10354            return ExprError();
10355
10356          ExprResult Arg1 =
10357            PerformCopyInitialization(
10358              InitializedEntity::InitializeParameter(Context,
10359                                                     FnDecl->getParamDecl(1)),
10360              SourceLocation(), Owned(Args[1]));
10361          if (Arg1.isInvalid())
10362            return ExprError();
10363          Args[0] = LHS = Arg0.takeAs<Expr>();
10364          Args[1] = RHS = Arg1.takeAs<Expr>();
10365        }
10366
10367        // Determine the result type.
10368        QualType ResultTy = FnDecl->getResultType();
10369        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10370        ResultTy = ResultTy.getNonLValueExprType(Context);
10371
10372        // Build the actual expression node.
10373        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10374                                                  Best->FoundDecl,
10375                                                  HadMultipleCandidates, OpLoc);
10376        if (FnExpr.isInvalid())
10377          return ExprError();
10378
10379        CXXOperatorCallExpr *TheCall =
10380          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10381                                            Args, ResultTy, VK, OpLoc,
10382                                            FPFeatures.fp_contract);
10383
10384        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10385                                FnDecl))
10386          return ExprError();
10387
10388        ArrayRef<const Expr *> ArgsArray(Args, 2);
10389        // Cut off the implicit 'this'.
10390        if (isa<CXXMethodDecl>(FnDecl))
10391          ArgsArray = ArgsArray.slice(1);
10392        checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10393                  TheCall->getSourceRange(), VariadicDoesNotApply);
10394
10395        return MaybeBindToTemporary(TheCall);
10396      } else {
10397        // We matched a built-in operator. Convert the arguments, then
10398        // break out so that we will build the appropriate built-in
10399        // operator node.
10400        ExprResult ArgsRes0 =
10401          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10402                                    Best->Conversions[0], AA_Passing);
10403        if (ArgsRes0.isInvalid())
10404          return ExprError();
10405        Args[0] = ArgsRes0.take();
10406
10407        ExprResult ArgsRes1 =
10408          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10409                                    Best->Conversions[1], AA_Passing);
10410        if (ArgsRes1.isInvalid())
10411          return ExprError();
10412        Args[1] = ArgsRes1.take();
10413        break;
10414      }
10415    }
10416
10417    case OR_No_Viable_Function: {
10418      // C++ [over.match.oper]p9:
10419      //   If the operator is the operator , [...] and there are no
10420      //   viable functions, then the operator is assumed to be the
10421      //   built-in operator and interpreted according to clause 5.
10422      if (Opc == BO_Comma)
10423        break;
10424
10425      // For class as left operand for assignment or compound assigment
10426      // operator do not fall through to handling in built-in, but report that
10427      // no overloaded assignment operator found
10428      ExprResult Result = ExprError();
10429      if (Args[0]->getType()->isRecordType() &&
10430          Opc >= BO_Assign && Opc <= BO_OrAssign) {
10431        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10432             << BinaryOperator::getOpcodeStr(Opc)
10433             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10434      } else {
10435        // This is an erroneous use of an operator which can be overloaded by
10436        // a non-member function. Check for non-member operators which were
10437        // defined too late to be candidates.
10438        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10439          // FIXME: Recover by calling the found function.
10440          return ExprError();
10441
10442        // No viable function; try to create a built-in operation, which will
10443        // produce an error. Then, show the non-viable candidates.
10444        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10445      }
10446      assert(Result.isInvalid() &&
10447             "C++ binary operator overloading is missing candidates!");
10448      if (Result.isInvalid())
10449        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10450                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
10451      return Result;
10452    }
10453
10454    case OR_Ambiguous:
10455      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10456          << BinaryOperator::getOpcodeStr(Opc)
10457          << Args[0]->getType() << Args[1]->getType()
10458          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10459      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10460                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10461      return ExprError();
10462
10463    case OR_Deleted:
10464      if (isImplicitlyDeleted(Best->Function)) {
10465        CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10466        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10467          << Context.getRecordType(Method->getParent())
10468          << getSpecialMember(Method);
10469
10470        // The user probably meant to call this special member. Just
10471        // explain why it's deleted.
10472        NoteDeletedFunction(Method);
10473        return ExprError();
10474      } else {
10475        Diag(OpLoc, diag::err_ovl_deleted_oper)
10476          << Best->Function->isDeleted()
10477          << BinaryOperator::getOpcodeStr(Opc)
10478          << getDeletedOrUnavailableSuffix(Best->Function)
10479          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10480      }
10481      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10482                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10483      return ExprError();
10484  }
10485
10486  // We matched a built-in operator; build it.
10487  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10488}
10489
10490ExprResult
10491Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10492                                         SourceLocation RLoc,
10493                                         Expr *Base, Expr *Idx) {
10494  Expr *Args[2] = { Base, Idx };
10495  DeclarationName OpName =
10496      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10497
10498  // If either side is type-dependent, create an appropriate dependent
10499  // expression.
10500  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10501
10502    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10503    // CHECKME: no 'operator' keyword?
10504    DeclarationNameInfo OpNameInfo(OpName, LLoc);
10505    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10506    UnresolvedLookupExpr *Fn
10507      = UnresolvedLookupExpr::Create(Context, NamingClass,
10508                                     NestedNameSpecifierLoc(), OpNameInfo,
10509                                     /*ADL*/ true, /*Overloaded*/ false,
10510                                     UnresolvedSetIterator(),
10511                                     UnresolvedSetIterator());
10512    // Can't add any actual overloads yet
10513
10514    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10515                                                   Args,
10516                                                   Context.DependentTy,
10517                                                   VK_RValue,
10518                                                   RLoc, false));
10519  }
10520
10521  // Handle placeholders on both operands.
10522  if (checkPlaceholderForOverload(*this, Args[0]))
10523    return ExprError();
10524  if (checkPlaceholderForOverload(*this, Args[1]))
10525    return ExprError();
10526
10527  // Build an empty overload set.
10528  OverloadCandidateSet CandidateSet(LLoc);
10529
10530  // Subscript can only be overloaded as a member function.
10531
10532  // Add operator candidates that are member functions.
10533  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10534
10535  // Add builtin operator candidates.
10536  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10537
10538  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10539
10540  // Perform overload resolution.
10541  OverloadCandidateSet::iterator Best;
10542  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10543    case OR_Success: {
10544      // We found a built-in operator or an overloaded operator.
10545      FunctionDecl *FnDecl = Best->Function;
10546
10547      if (FnDecl) {
10548        // We matched an overloaded operator. Build a call to that
10549        // operator.
10550
10551        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10552
10553        // Convert the arguments.
10554        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10555        ExprResult Arg0 =
10556          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10557                                              Best->FoundDecl, Method);
10558        if (Arg0.isInvalid())
10559          return ExprError();
10560        Args[0] = Arg0.take();
10561
10562        // Convert the arguments.
10563        ExprResult InputInit
10564          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10565                                                      Context,
10566                                                      FnDecl->getParamDecl(0)),
10567                                      SourceLocation(),
10568                                      Owned(Args[1]));
10569        if (InputInit.isInvalid())
10570          return ExprError();
10571
10572        Args[1] = InputInit.takeAs<Expr>();
10573
10574        // Determine the result type
10575        QualType ResultTy = FnDecl->getResultType();
10576        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10577        ResultTy = ResultTy.getNonLValueExprType(Context);
10578
10579        // Build the actual expression node.
10580        DeclarationNameInfo OpLocInfo(OpName, LLoc);
10581        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10582        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10583                                                  Best->FoundDecl,
10584                                                  HadMultipleCandidates,
10585                                                  OpLocInfo.getLoc(),
10586                                                  OpLocInfo.getInfo());
10587        if (FnExpr.isInvalid())
10588          return ExprError();
10589
10590        CXXOperatorCallExpr *TheCall =
10591          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10592                                            FnExpr.take(), Args,
10593                                            ResultTy, VK, RLoc,
10594                                            false);
10595
10596        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10597                                FnDecl))
10598          return ExprError();
10599
10600        return MaybeBindToTemporary(TheCall);
10601      } else {
10602        // We matched a built-in operator. Convert the arguments, then
10603        // break out so that we will build the appropriate built-in
10604        // operator node.
10605        ExprResult ArgsRes0 =
10606          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10607                                    Best->Conversions[0], AA_Passing);
10608        if (ArgsRes0.isInvalid())
10609          return ExprError();
10610        Args[0] = ArgsRes0.take();
10611
10612        ExprResult ArgsRes1 =
10613          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10614                                    Best->Conversions[1], AA_Passing);
10615        if (ArgsRes1.isInvalid())
10616          return ExprError();
10617        Args[1] = ArgsRes1.take();
10618
10619        break;
10620      }
10621    }
10622
10623    case OR_No_Viable_Function: {
10624      if (CandidateSet.empty())
10625        Diag(LLoc, diag::err_ovl_no_oper)
10626          << Args[0]->getType() << /*subscript*/ 0
10627          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10628      else
10629        Diag(LLoc, diag::err_ovl_no_viable_subscript)
10630          << Args[0]->getType()
10631          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10632      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10633                                  "[]", LLoc);
10634      return ExprError();
10635    }
10636
10637    case OR_Ambiguous:
10638      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10639          << "[]"
10640          << Args[0]->getType() << Args[1]->getType()
10641          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10642      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10643                                  "[]", LLoc);
10644      return ExprError();
10645
10646    case OR_Deleted:
10647      Diag(LLoc, diag::err_ovl_deleted_oper)
10648        << Best->Function->isDeleted() << "[]"
10649        << getDeletedOrUnavailableSuffix(Best->Function)
10650        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10651      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10652                                  "[]", LLoc);
10653      return ExprError();
10654    }
10655
10656  // We matched a built-in operator; build it.
10657  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10658}
10659
10660/// BuildCallToMemberFunction - Build a call to a member
10661/// function. MemExpr is the expression that refers to the member
10662/// function (and includes the object parameter), Args/NumArgs are the
10663/// arguments to the function call (not including the object
10664/// parameter). The caller needs to validate that the member
10665/// expression refers to a non-static member function or an overloaded
10666/// member function.
10667ExprResult
10668Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10669                                SourceLocation LParenLoc, Expr **Args,
10670                                unsigned NumArgs, SourceLocation RParenLoc) {
10671  assert(MemExprE->getType() == Context.BoundMemberTy ||
10672         MemExprE->getType() == Context.OverloadTy);
10673
10674  // Dig out the member expression. This holds both the object
10675  // argument and the member function we're referring to.
10676  Expr *NakedMemExpr = MemExprE->IgnoreParens();
10677
10678  // Determine whether this is a call to a pointer-to-member function.
10679  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10680    assert(op->getType() == Context.BoundMemberTy);
10681    assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10682
10683    QualType fnType =
10684      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10685
10686    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10687    QualType resultType = proto->getCallResultType(Context);
10688    ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10689
10690    // Check that the object type isn't more qualified than the
10691    // member function we're calling.
10692    Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10693
10694    QualType objectType = op->getLHS()->getType();
10695    if (op->getOpcode() == BO_PtrMemI)
10696      objectType = objectType->castAs<PointerType>()->getPointeeType();
10697    Qualifiers objectQuals = objectType.getQualifiers();
10698
10699    Qualifiers difference = objectQuals - funcQuals;
10700    difference.removeObjCGCAttr();
10701    difference.removeAddressSpace();
10702    if (difference) {
10703      std::string qualsString = difference.getAsString();
10704      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10705        << fnType.getUnqualifiedType()
10706        << qualsString
10707        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10708    }
10709
10710    CXXMemberCallExpr *call
10711      = new (Context) CXXMemberCallExpr(Context, MemExprE,
10712                                        llvm::makeArrayRef(Args, NumArgs),
10713                                        resultType, valueKind, RParenLoc);
10714
10715    if (CheckCallReturnType(proto->getResultType(),
10716                            op->getRHS()->getLocStart(),
10717                            call, 0))
10718      return ExprError();
10719
10720    if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10721      return ExprError();
10722
10723    return MaybeBindToTemporary(call);
10724  }
10725
10726  UnbridgedCastsSet UnbridgedCasts;
10727  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10728    return ExprError();
10729
10730  MemberExpr *MemExpr;
10731  CXXMethodDecl *Method = 0;
10732  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10733  NestedNameSpecifier *Qualifier = 0;
10734  if (isa<MemberExpr>(NakedMemExpr)) {
10735    MemExpr = cast<MemberExpr>(NakedMemExpr);
10736    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10737    FoundDecl = MemExpr->getFoundDecl();
10738    Qualifier = MemExpr->getQualifier();
10739    UnbridgedCasts.restore();
10740  } else {
10741    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10742    Qualifier = UnresExpr->getQualifier();
10743
10744    QualType ObjectType = UnresExpr->getBaseType();
10745    Expr::Classification ObjectClassification
10746      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10747                            : UnresExpr->getBase()->Classify(Context);
10748
10749    // Add overload candidates
10750    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10751
10752    // FIXME: avoid copy.
10753    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10754    if (UnresExpr->hasExplicitTemplateArgs()) {
10755      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10756      TemplateArgs = &TemplateArgsBuffer;
10757    }
10758
10759    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10760           E = UnresExpr->decls_end(); I != E; ++I) {
10761
10762      NamedDecl *Func = *I;
10763      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10764      if (isa<UsingShadowDecl>(Func))
10765        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10766
10767
10768      // Microsoft supports direct constructor calls.
10769      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10770        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10771                             llvm::makeArrayRef(Args, NumArgs), CandidateSet);
10772      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10773        // If explicit template arguments were provided, we can't call a
10774        // non-template member function.
10775        if (TemplateArgs)
10776          continue;
10777
10778        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10779                           ObjectClassification,
10780                           llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10781                           /*SuppressUserConversions=*/false);
10782      } else {
10783        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10784                                   I.getPair(), ActingDC, TemplateArgs,
10785                                   ObjectType,  ObjectClassification,
10786                                   llvm::makeArrayRef(Args, NumArgs),
10787                                   CandidateSet,
10788                                   /*SuppressUsedConversions=*/false);
10789      }
10790    }
10791
10792    DeclarationName DeclName = UnresExpr->getMemberName();
10793
10794    UnbridgedCasts.restore();
10795
10796    OverloadCandidateSet::iterator Best;
10797    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10798                                            Best)) {
10799    case OR_Success:
10800      Method = cast<CXXMethodDecl>(Best->Function);
10801      FoundDecl = Best->FoundDecl;
10802      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10803      DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
10804      break;
10805
10806    case OR_No_Viable_Function:
10807      Diag(UnresExpr->getMemberLoc(),
10808           diag::err_ovl_no_viable_member_function_in_call)
10809        << DeclName << MemExprE->getSourceRange();
10810      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10811                                  llvm::makeArrayRef(Args, NumArgs));
10812      // FIXME: Leaking incoming expressions!
10813      return ExprError();
10814
10815    case OR_Ambiguous:
10816      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10817        << DeclName << MemExprE->getSourceRange();
10818      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10819                                  llvm::makeArrayRef(Args, NumArgs));
10820      // FIXME: Leaking incoming expressions!
10821      return ExprError();
10822
10823    case OR_Deleted:
10824      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10825        << Best->Function->isDeleted()
10826        << DeclName
10827        << getDeletedOrUnavailableSuffix(Best->Function)
10828        << MemExprE->getSourceRange();
10829      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10830                                  llvm::makeArrayRef(Args, NumArgs));
10831      // FIXME: Leaking incoming expressions!
10832      return ExprError();
10833    }
10834
10835    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10836
10837    // If overload resolution picked a static member, build a
10838    // non-member call based on that function.
10839    if (Method->isStatic()) {
10840      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10841                                   Args, NumArgs, RParenLoc);
10842    }
10843
10844    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10845  }
10846
10847  QualType ResultType = Method->getResultType();
10848  ExprValueKind VK = Expr::getValueKindForType(ResultType);
10849  ResultType = ResultType.getNonLValueExprType(Context);
10850
10851  assert(Method && "Member call to something that isn't a method?");
10852  CXXMemberCallExpr *TheCall =
10853    new (Context) CXXMemberCallExpr(Context, MemExprE,
10854                                    llvm::makeArrayRef(Args, NumArgs),
10855                                    ResultType, VK, RParenLoc);
10856
10857  // Check for a valid return type.
10858  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10859                          TheCall, Method))
10860    return ExprError();
10861
10862  // Convert the object argument (for a non-static member function call).
10863  // We only need to do this if there was actually an overload; otherwise
10864  // it was done at lookup.
10865  if (!Method->isStatic()) {
10866    ExprResult ObjectArg =
10867      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10868                                          FoundDecl, Method);
10869    if (ObjectArg.isInvalid())
10870      return ExprError();
10871    MemExpr->setBase(ObjectArg.take());
10872  }
10873
10874  // Convert the rest of the arguments
10875  const FunctionProtoType *Proto =
10876    Method->getType()->getAs<FunctionProtoType>();
10877  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10878                              RParenLoc))
10879    return ExprError();
10880
10881  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10882
10883  if (CheckFunctionCall(Method, TheCall, Proto))
10884    return ExprError();
10885
10886  if ((isa<CXXConstructorDecl>(CurContext) ||
10887       isa<CXXDestructorDecl>(CurContext)) &&
10888      TheCall->getMethodDecl()->isPure()) {
10889    const CXXMethodDecl *MD = TheCall->getMethodDecl();
10890
10891    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10892      Diag(MemExpr->getLocStart(),
10893           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10894        << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10895        << MD->getParent()->getDeclName();
10896
10897      Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10898    }
10899  }
10900  return MaybeBindToTemporary(TheCall);
10901}
10902
10903/// BuildCallToObjectOfClassType - Build a call to an object of class
10904/// type (C++ [over.call.object]), which can end up invoking an
10905/// overloaded function call operator (@c operator()) or performing a
10906/// user-defined conversion on the object argument.
10907ExprResult
10908Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10909                                   SourceLocation LParenLoc,
10910                                   Expr **Args, unsigned NumArgs,
10911                                   SourceLocation RParenLoc) {
10912  if (checkPlaceholderForOverload(*this, Obj))
10913    return ExprError();
10914  ExprResult Object = Owned(Obj);
10915
10916  UnbridgedCastsSet UnbridgedCasts;
10917  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10918    return ExprError();
10919
10920  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10921  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10922
10923  // C++ [over.call.object]p1:
10924  //  If the primary-expression E in the function call syntax
10925  //  evaluates to a class object of type "cv T", then the set of
10926  //  candidate functions includes at least the function call
10927  //  operators of T. The function call operators of T are obtained by
10928  //  ordinary lookup of the name operator() in the context of
10929  //  (E).operator().
10930  OverloadCandidateSet CandidateSet(LParenLoc);
10931  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10932
10933  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10934                          diag::err_incomplete_object_call, Object.get()))
10935    return true;
10936
10937  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10938  LookupQualifiedName(R, Record->getDecl());
10939  R.suppressDiagnostics();
10940
10941  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10942       Oper != OperEnd; ++Oper) {
10943    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10944                       Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
10945                       /*SuppressUserConversions=*/ false);
10946  }
10947
10948  // C++ [over.call.object]p2:
10949  //   In addition, for each (non-explicit in C++0x) conversion function
10950  //   declared in T of the form
10951  //
10952  //        operator conversion-type-id () cv-qualifier;
10953  //
10954  //   where cv-qualifier is the same cv-qualification as, or a
10955  //   greater cv-qualification than, cv, and where conversion-type-id
10956  //   denotes the type "pointer to function of (P1,...,Pn) returning
10957  //   R", or the type "reference to pointer to function of
10958  //   (P1,...,Pn) returning R", or the type "reference to function
10959  //   of (P1,...,Pn) returning R", a surrogate call function [...]
10960  //   is also considered as a candidate function. Similarly,
10961  //   surrogate call functions are added to the set of candidate
10962  //   functions for each conversion function declared in an
10963  //   accessible base class provided the function is not hidden
10964  //   within T by another intervening declaration.
10965  std::pair<CXXRecordDecl::conversion_iterator,
10966            CXXRecordDecl::conversion_iterator> Conversions
10967    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
10968  for (CXXRecordDecl::conversion_iterator
10969         I = Conversions.first, E = Conversions.second; I != E; ++I) {
10970    NamedDecl *D = *I;
10971    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10972    if (isa<UsingShadowDecl>(D))
10973      D = cast<UsingShadowDecl>(D)->getTargetDecl();
10974
10975    // Skip over templated conversion functions; they aren't
10976    // surrogates.
10977    if (isa<FunctionTemplateDecl>(D))
10978      continue;
10979
10980    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
10981    if (!Conv->isExplicit()) {
10982      // Strip the reference type (if any) and then the pointer type (if
10983      // any) to get down to what might be a function type.
10984      QualType ConvType = Conv->getConversionType().getNonReferenceType();
10985      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10986        ConvType = ConvPtrType->getPointeeType();
10987
10988      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10989      {
10990        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10991                              Object.get(), llvm::makeArrayRef(Args, NumArgs),
10992                              CandidateSet);
10993      }
10994    }
10995  }
10996
10997  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10998
10999  // Perform overload resolution.
11000  OverloadCandidateSet::iterator Best;
11001  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11002                             Best)) {
11003  case OR_Success:
11004    // Overload resolution succeeded; we'll build the appropriate call
11005    // below.
11006    break;
11007
11008  case OR_No_Viable_Function:
11009    if (CandidateSet.empty())
11010      Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11011        << Object.get()->getType() << /*call*/ 1
11012        << Object.get()->getSourceRange();
11013    else
11014      Diag(Object.get()->getLocStart(),
11015           diag::err_ovl_no_viable_object_call)
11016        << Object.get()->getType() << Object.get()->getSourceRange();
11017    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11018                                llvm::makeArrayRef(Args, NumArgs));
11019    break;
11020
11021  case OR_Ambiguous:
11022    Diag(Object.get()->getLocStart(),
11023         diag::err_ovl_ambiguous_object_call)
11024      << Object.get()->getType() << Object.get()->getSourceRange();
11025    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
11026                                llvm::makeArrayRef(Args, NumArgs));
11027    break;
11028
11029  case OR_Deleted:
11030    Diag(Object.get()->getLocStart(),
11031         diag::err_ovl_deleted_object_call)
11032      << Best->Function->isDeleted()
11033      << Object.get()->getType()
11034      << getDeletedOrUnavailableSuffix(Best->Function)
11035      << Object.get()->getSourceRange();
11036    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11037                                llvm::makeArrayRef(Args, NumArgs));
11038    break;
11039  }
11040
11041  if (Best == CandidateSet.end())
11042    return true;
11043
11044  UnbridgedCasts.restore();
11045
11046  if (Best->Function == 0) {
11047    // Since there is no function declaration, this is one of the
11048    // surrogate candidates. Dig out the conversion function.
11049    CXXConversionDecl *Conv
11050      = cast<CXXConversionDecl>(
11051                         Best->Conversions[0].UserDefined.ConversionFunction);
11052
11053    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11054    DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
11055
11056    // We selected one of the surrogate functions that converts the
11057    // object parameter to a function pointer. Perform the conversion
11058    // on the object argument, then let ActOnCallExpr finish the job.
11059
11060    // Create an implicit member expr to refer to the conversion operator.
11061    // and then call it.
11062    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11063                                             Conv, HadMultipleCandidates);
11064    if (Call.isInvalid())
11065      return ExprError();
11066    // Record usage of conversion in an implicit cast.
11067    Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11068                                          CK_UserDefinedConversion,
11069                                          Call.get(), 0, VK_RValue));
11070
11071    return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
11072                         RParenLoc);
11073  }
11074
11075  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11076
11077  // We found an overloaded operator(). Build a CXXOperatorCallExpr
11078  // that calls this method, using Object for the implicit object
11079  // parameter and passing along the remaining arguments.
11080  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11081
11082  // An error diagnostic has already been printed when parsing the declaration.
11083  if (Method->isInvalidDecl())
11084    return ExprError();
11085
11086  const FunctionProtoType *Proto =
11087    Method->getType()->getAs<FunctionProtoType>();
11088
11089  unsigned NumArgsInProto = Proto->getNumArgs();
11090  unsigned NumArgsToCheck = NumArgs;
11091
11092  // Build the full argument list for the method call (the
11093  // implicit object parameter is placed at the beginning of the
11094  // list).
11095  Expr **MethodArgs;
11096  if (NumArgs < NumArgsInProto) {
11097    NumArgsToCheck = NumArgsInProto;
11098    MethodArgs = new Expr*[NumArgsInProto + 1];
11099  } else {
11100    MethodArgs = new Expr*[NumArgs + 1];
11101  }
11102  MethodArgs[0] = Object.get();
11103  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11104    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
11105
11106  DeclarationNameInfo OpLocInfo(
11107               Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11108  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11109  ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11110                                           HadMultipleCandidates,
11111                                           OpLocInfo.getLoc(),
11112                                           OpLocInfo.getInfo());
11113  if (NewFn.isInvalid())
11114    return true;
11115
11116  // Once we've built TheCall, all of the expressions are properly
11117  // owned.
11118  QualType ResultTy = Method->getResultType();
11119  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11120  ResultTy = ResultTy.getNonLValueExprType(Context);
11121
11122  CXXOperatorCallExpr *TheCall =
11123    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11124                                      llvm::makeArrayRef(MethodArgs, NumArgs+1),
11125                                      ResultTy, VK, RParenLoc, false);
11126  delete [] MethodArgs;
11127
11128  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11129                          Method))
11130    return true;
11131
11132  // We may have default arguments. If so, we need to allocate more
11133  // slots in the call for them.
11134  if (NumArgs < NumArgsInProto)
11135    TheCall->setNumArgs(Context, NumArgsInProto + 1);
11136  else if (NumArgs > NumArgsInProto)
11137    NumArgsToCheck = NumArgsInProto;
11138
11139  bool IsError = false;
11140
11141  // Initialize the implicit object parameter.
11142  ExprResult ObjRes =
11143    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11144                                        Best->FoundDecl, Method);
11145  if (ObjRes.isInvalid())
11146    IsError = true;
11147  else
11148    Object = ObjRes;
11149  TheCall->setArg(0, Object.take());
11150
11151  // Check the argument types.
11152  for (unsigned i = 0; i != NumArgsToCheck; i++) {
11153    Expr *Arg;
11154    if (i < NumArgs) {
11155      Arg = Args[i];
11156
11157      // Pass the argument.
11158
11159      ExprResult InputInit
11160        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11161                                                    Context,
11162                                                    Method->getParamDecl(i)),
11163                                    SourceLocation(), Arg);
11164
11165      IsError |= InputInit.isInvalid();
11166      Arg = InputInit.takeAs<Expr>();
11167    } else {
11168      ExprResult DefArg
11169        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11170      if (DefArg.isInvalid()) {
11171        IsError = true;
11172        break;
11173      }
11174
11175      Arg = DefArg.takeAs<Expr>();
11176    }
11177
11178    TheCall->setArg(i + 1, Arg);
11179  }
11180
11181  // If this is a variadic call, handle args passed through "...".
11182  if (Proto->isVariadic()) {
11183    // Promote the arguments (C99 6.5.2.2p7).
11184    for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
11185      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11186      IsError |= Arg.isInvalid();
11187      TheCall->setArg(i + 1, Arg.take());
11188    }
11189  }
11190
11191  if (IsError) return true;
11192
11193  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11194
11195  if (CheckFunctionCall(Method, TheCall, Proto))
11196    return true;
11197
11198  return MaybeBindToTemporary(TheCall);
11199}
11200
11201/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11202///  (if one exists), where @c Base is an expression of class type and
11203/// @c Member is the name of the member we're trying to find.
11204ExprResult
11205Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
11206  assert(Base->getType()->isRecordType() &&
11207         "left-hand side must have class type");
11208
11209  if (checkPlaceholderForOverload(*this, Base))
11210    return ExprError();
11211
11212  SourceLocation Loc = Base->getExprLoc();
11213
11214  // C++ [over.ref]p1:
11215  //
11216  //   [...] An expression x->m is interpreted as (x.operator->())->m
11217  //   for a class object x of type T if T::operator->() exists and if
11218  //   the operator is selected as the best match function by the
11219  //   overload resolution mechanism (13.3).
11220  DeclarationName OpName =
11221    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11222  OverloadCandidateSet CandidateSet(Loc);
11223  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11224
11225  if (RequireCompleteType(Loc, Base->getType(),
11226                          diag::err_typecheck_incomplete_tag, Base))
11227    return ExprError();
11228
11229  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11230  LookupQualifiedName(R, BaseRecord->getDecl());
11231  R.suppressDiagnostics();
11232
11233  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11234       Oper != OperEnd; ++Oper) {
11235    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11236                       0, 0, CandidateSet, /*SuppressUserConversions=*/false);
11237  }
11238
11239  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11240
11241  // Perform overload resolution.
11242  OverloadCandidateSet::iterator Best;
11243  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11244  case OR_Success:
11245    // Overload resolution succeeded; we'll build the call below.
11246    break;
11247
11248  case OR_No_Viable_Function:
11249    if (CandidateSet.empty())
11250      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11251        << Base->getType() << Base->getSourceRange();
11252    else
11253      Diag(OpLoc, diag::err_ovl_no_viable_oper)
11254        << "operator->" << Base->getSourceRange();
11255    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11256    return ExprError();
11257
11258  case OR_Ambiguous:
11259    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11260      << "->" << Base->getType() << Base->getSourceRange();
11261    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11262    return ExprError();
11263
11264  case OR_Deleted:
11265    Diag(OpLoc,  diag::err_ovl_deleted_oper)
11266      << Best->Function->isDeleted()
11267      << "->"
11268      << getDeletedOrUnavailableSuffix(Best->Function)
11269      << Base->getSourceRange();
11270    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11271    return ExprError();
11272  }
11273
11274  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11275
11276  // Convert the object parameter.
11277  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11278  ExprResult BaseResult =
11279    PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11280                                        Best->FoundDecl, Method);
11281  if (BaseResult.isInvalid())
11282    return ExprError();
11283  Base = BaseResult.take();
11284
11285  // Build the operator call.
11286  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11287                                            HadMultipleCandidates, OpLoc);
11288  if (FnExpr.isInvalid())
11289    return ExprError();
11290
11291  QualType ResultTy = Method->getResultType();
11292  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11293  ResultTy = ResultTy.getNonLValueExprType(Context);
11294  CXXOperatorCallExpr *TheCall =
11295    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11296                                      Base, ResultTy, VK, OpLoc, false);
11297
11298  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11299                          Method))
11300          return ExprError();
11301
11302  return MaybeBindToTemporary(TheCall);
11303}
11304
11305/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11306/// a literal operator described by the provided lookup results.
11307ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11308                                          DeclarationNameInfo &SuffixInfo,
11309                                          ArrayRef<Expr*> Args,
11310                                          SourceLocation LitEndLoc,
11311                                       TemplateArgumentListInfo *TemplateArgs) {
11312  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11313
11314  OverloadCandidateSet CandidateSet(UDSuffixLoc);
11315  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11316                        TemplateArgs);
11317
11318  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11319
11320  // Perform overload resolution. This will usually be trivial, but might need
11321  // to perform substitutions for a literal operator template.
11322  OverloadCandidateSet::iterator Best;
11323  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11324  case OR_Success:
11325  case OR_Deleted:
11326    break;
11327
11328  case OR_No_Viable_Function:
11329    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11330      << R.getLookupName();
11331    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11332    return ExprError();
11333
11334  case OR_Ambiguous:
11335    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11336    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11337    return ExprError();
11338  }
11339
11340  FunctionDecl *FD = Best->Function;
11341  ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11342                                        HadMultipleCandidates,
11343                                        SuffixInfo.getLoc(),
11344                                        SuffixInfo.getInfo());
11345  if (Fn.isInvalid())
11346    return true;
11347
11348  // Check the argument types. This should almost always be a no-op, except
11349  // that array-to-pointer decay is applied to string literals.
11350  Expr *ConvArgs[2];
11351  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11352    ExprResult InputInit = PerformCopyInitialization(
11353      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11354      SourceLocation(), Args[ArgIdx]);
11355    if (InputInit.isInvalid())
11356      return true;
11357    ConvArgs[ArgIdx] = InputInit.take();
11358  }
11359
11360  QualType ResultTy = FD->getResultType();
11361  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11362  ResultTy = ResultTy.getNonLValueExprType(Context);
11363
11364  UserDefinedLiteral *UDL =
11365    new (Context) UserDefinedLiteral(Context, Fn.take(),
11366                                     llvm::makeArrayRef(ConvArgs, Args.size()),
11367                                     ResultTy, VK, LitEndLoc, UDSuffixLoc);
11368
11369  if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11370    return ExprError();
11371
11372  if (CheckFunctionCall(FD, UDL, NULL))
11373    return ExprError();
11374
11375  return MaybeBindToTemporary(UDL);
11376}
11377
11378/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11379/// given LookupResult is non-empty, it is assumed to describe a member which
11380/// will be invoked. Otherwise, the function will be found via argument
11381/// dependent lookup.
11382/// CallExpr is set to a valid expression and FRS_Success returned on success,
11383/// otherwise CallExpr is set to ExprError() and some non-success value
11384/// is returned.
11385Sema::ForRangeStatus
11386Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11387                                SourceLocation RangeLoc, VarDecl *Decl,
11388                                BeginEndFunction BEF,
11389                                const DeclarationNameInfo &NameInfo,
11390                                LookupResult &MemberLookup,
11391                                OverloadCandidateSet *CandidateSet,
11392                                Expr *Range, ExprResult *CallExpr) {
11393  CandidateSet->clear();
11394  if (!MemberLookup.empty()) {
11395    ExprResult MemberRef =
11396        BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11397                                 /*IsPtr=*/false, CXXScopeSpec(),
11398                                 /*TemplateKWLoc=*/SourceLocation(),
11399                                 /*FirstQualifierInScope=*/0,
11400                                 MemberLookup,
11401                                 /*TemplateArgs=*/0);
11402    if (MemberRef.isInvalid()) {
11403      *CallExpr = ExprError();
11404      Diag(Range->getLocStart(), diag::note_in_for_range)
11405          << RangeLoc << BEF << Range->getType();
11406      return FRS_DiagnosticIssued;
11407    }
11408    *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11409    if (CallExpr->isInvalid()) {
11410      *CallExpr = ExprError();
11411      Diag(Range->getLocStart(), diag::note_in_for_range)
11412          << RangeLoc << BEF << Range->getType();
11413      return FRS_DiagnosticIssued;
11414    }
11415  } else {
11416    UnresolvedSet<0> FoundNames;
11417    UnresolvedLookupExpr *Fn =
11418      UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11419                                   NestedNameSpecifierLoc(), NameInfo,
11420                                   /*NeedsADL=*/true, /*Overloaded=*/false,
11421                                   FoundNames.begin(), FoundNames.end());
11422
11423    bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11424                                                    CandidateSet, CallExpr);
11425    if (CandidateSet->empty() || CandidateSetError) {
11426      *CallExpr = ExprError();
11427      return FRS_NoViableFunction;
11428    }
11429    OverloadCandidateSet::iterator Best;
11430    OverloadingResult OverloadResult =
11431        CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11432
11433    if (OverloadResult == OR_No_Viable_Function) {
11434      *CallExpr = ExprError();
11435      return FRS_NoViableFunction;
11436    }
11437    *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11438                                         Loc, 0, CandidateSet, &Best,
11439                                         OverloadResult,
11440                                         /*AllowTypoCorrection=*/false);
11441    if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11442      *CallExpr = ExprError();
11443      Diag(Range->getLocStart(), diag::note_in_for_range)
11444          << RangeLoc << BEF << Range->getType();
11445      return FRS_DiagnosticIssued;
11446    }
11447  }
11448  return FRS_Success;
11449}
11450
11451
11452/// FixOverloadedFunctionReference - E is an expression that refers to
11453/// a C++ overloaded function (possibly with some parentheses and
11454/// perhaps a '&' around it). We have resolved the overloaded function
11455/// to the function declaration Fn, so patch up the expression E to
11456/// refer (possibly indirectly) to Fn. Returns the new expr.
11457Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11458                                           FunctionDecl *Fn) {
11459  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11460    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11461                                                   Found, Fn);
11462    if (SubExpr == PE->getSubExpr())
11463      return PE;
11464
11465    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11466  }
11467
11468  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11469    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11470                                                   Found, Fn);
11471    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11472                               SubExpr->getType()) &&
11473           "Implicit cast type cannot be determined from overload");
11474    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11475    if (SubExpr == ICE->getSubExpr())
11476      return ICE;
11477
11478    return ImplicitCastExpr::Create(Context, ICE->getType(),
11479                                    ICE->getCastKind(),
11480                                    SubExpr, 0,
11481                                    ICE->getValueKind());
11482  }
11483
11484  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11485    assert(UnOp->getOpcode() == UO_AddrOf &&
11486           "Can only take the address of an overloaded function");
11487    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11488      if (Method->isStatic()) {
11489        // Do nothing: static member functions aren't any different
11490        // from non-member functions.
11491      } else {
11492        // Fix the sub expression, which really has to be an
11493        // UnresolvedLookupExpr holding an overloaded member function
11494        // or template.
11495        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11496                                                       Found, Fn);
11497        if (SubExpr == UnOp->getSubExpr())
11498          return UnOp;
11499
11500        assert(isa<DeclRefExpr>(SubExpr)
11501               && "fixed to something other than a decl ref");
11502        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11503               && "fixed to a member ref with no nested name qualifier");
11504
11505        // We have taken the address of a pointer to member
11506        // function. Perform the computation here so that we get the
11507        // appropriate pointer to member type.
11508        QualType ClassType
11509          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11510        QualType MemPtrType
11511          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11512
11513        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11514                                           VK_RValue, OK_Ordinary,
11515                                           UnOp->getOperatorLoc());
11516      }
11517    }
11518    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11519                                                   Found, Fn);
11520    if (SubExpr == UnOp->getSubExpr())
11521      return UnOp;
11522
11523    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11524                                     Context.getPointerType(SubExpr->getType()),
11525                                       VK_RValue, OK_Ordinary,
11526                                       UnOp->getOperatorLoc());
11527  }
11528
11529  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11530    // FIXME: avoid copy.
11531    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11532    if (ULE->hasExplicitTemplateArgs()) {
11533      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11534      TemplateArgs = &TemplateArgsBuffer;
11535    }
11536
11537    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11538                                           ULE->getQualifierLoc(),
11539                                           ULE->getTemplateKeywordLoc(),
11540                                           Fn,
11541                                           /*enclosing*/ false, // FIXME?
11542                                           ULE->getNameLoc(),
11543                                           Fn->getType(),
11544                                           VK_LValue,
11545                                           Found.getDecl(),
11546                                           TemplateArgs);
11547    MarkDeclRefReferenced(DRE);
11548    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11549    return DRE;
11550  }
11551
11552  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11553    // FIXME: avoid copy.
11554    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11555    if (MemExpr->hasExplicitTemplateArgs()) {
11556      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11557      TemplateArgs = &TemplateArgsBuffer;
11558    }
11559
11560    Expr *Base;
11561
11562    // If we're filling in a static method where we used to have an
11563    // implicit member access, rewrite to a simple decl ref.
11564    if (MemExpr->isImplicitAccess()) {
11565      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11566        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11567                                               MemExpr->getQualifierLoc(),
11568                                               MemExpr->getTemplateKeywordLoc(),
11569                                               Fn,
11570                                               /*enclosing*/ false,
11571                                               MemExpr->getMemberLoc(),
11572                                               Fn->getType(),
11573                                               VK_LValue,
11574                                               Found.getDecl(),
11575                                               TemplateArgs);
11576        MarkDeclRefReferenced(DRE);
11577        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11578        return DRE;
11579      } else {
11580        SourceLocation Loc = MemExpr->getMemberLoc();
11581        if (MemExpr->getQualifier())
11582          Loc = MemExpr->getQualifierLoc().getBeginLoc();
11583        CheckCXXThisCapture(Loc);
11584        Base = new (Context) CXXThisExpr(Loc,
11585                                         MemExpr->getBaseType(),
11586                                         /*isImplicit=*/true);
11587      }
11588    } else
11589      Base = MemExpr->getBase();
11590
11591    ExprValueKind valueKind;
11592    QualType type;
11593    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11594      valueKind = VK_LValue;
11595      type = Fn->getType();
11596    } else {
11597      valueKind = VK_RValue;
11598      type = Context.BoundMemberTy;
11599    }
11600
11601    MemberExpr *ME = MemberExpr::Create(Context, Base,
11602                                        MemExpr->isArrow(),
11603                                        MemExpr->getQualifierLoc(),
11604                                        MemExpr->getTemplateKeywordLoc(),
11605                                        Fn,
11606                                        Found,
11607                                        MemExpr->getMemberNameInfo(),
11608                                        TemplateArgs,
11609                                        type, valueKind, OK_Ordinary);
11610    ME->setHadMultipleCandidates(true);
11611    MarkMemberReferenced(ME);
11612    return ME;
11613  }
11614
11615  llvm_unreachable("Invalid reference to overloaded function");
11616}
11617
11618ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11619                                                DeclAccessPair Found,
11620                                                FunctionDecl *Fn) {
11621  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11622}
11623
11624} // end namespace clang
11625