SemaOverload.cpp revision 80ad52f327b532bded5c5b0ee38779d841c6cd35
1//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/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
40/// function.
41static ExprResult
42CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, 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  ExprResult E = S.Owned(DRE);
50  E = S.DefaultFunctionArrayConversion(E.take());
51  if (E.isInvalid())
52    return ExprError();
53  return E;
54}
55
56static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
57                                 bool InOverloadResolution,
58                                 StandardConversionSequence &SCS,
59                                 bool CStyle,
60                                 bool AllowObjCWritebackConversion);
61
62static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
63                                                 QualType &ToType,
64                                                 bool InOverloadResolution,
65                                                 StandardConversionSequence &SCS,
66                                                 bool CStyle);
67static OverloadingResult
68IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
69                        UserDefinedConversionSequence& User,
70                        OverloadCandidateSet& Conversions,
71                        bool AllowExplicit);
72
73
74static ImplicitConversionSequence::CompareKind
75CompareStandardConversionSequences(Sema &S,
76                                   const StandardConversionSequence& SCS1,
77                                   const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareQualificationConversions(Sema &S,
81                                const StandardConversionSequence& SCS1,
82                                const StandardConversionSequence& SCS2);
83
84static ImplicitConversionSequence::CompareKind
85CompareDerivedToBaseConversions(Sema &S,
86                                const StandardConversionSequence& SCS1,
87                                const StandardConversionSequence& SCS2);
88
89
90
91/// GetConversionCategory - Retrieve the implicit conversion
92/// category corresponding to the given implicit conversion kind.
93ImplicitConversionCategory
94GetConversionCategory(ImplicitConversionKind Kind) {
95  static const ImplicitConversionCategory
96    Category[(int)ICK_Num_Conversion_Kinds] = {
97    ICC_Identity,
98    ICC_Lvalue_Transformation,
99    ICC_Lvalue_Transformation,
100    ICC_Lvalue_Transformation,
101    ICC_Identity,
102    ICC_Qualification_Adjustment,
103    ICC_Promotion,
104    ICC_Promotion,
105    ICC_Promotion,
106    ICC_Conversion,
107    ICC_Conversion,
108    ICC_Conversion,
109    ICC_Conversion,
110    ICC_Conversion,
111    ICC_Conversion,
112    ICC_Conversion,
113    ICC_Conversion,
114    ICC_Conversion,
115    ICC_Conversion,
116    ICC_Conversion,
117    ICC_Conversion,
118    ICC_Conversion
119  };
120  return Category[(int)Kind];
121}
122
123/// GetConversionRank - Retrieve the implicit conversion rank
124/// corresponding to the given implicit conversion kind.
125ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
126  static const ImplicitConversionRank
127    Rank[(int)ICK_Num_Conversion_Kinds] = {
128    ICR_Exact_Match,
129    ICR_Exact_Match,
130    ICR_Exact_Match,
131    ICR_Exact_Match,
132    ICR_Exact_Match,
133    ICR_Exact_Match,
134    ICR_Promotion,
135    ICR_Promotion,
136    ICR_Promotion,
137    ICR_Conversion,
138    ICR_Conversion,
139    ICR_Conversion,
140    ICR_Conversion,
141    ICR_Conversion,
142    ICR_Conversion,
143    ICR_Conversion,
144    ICR_Conversion,
145    ICR_Conversion,
146    ICR_Conversion,
147    ICR_Conversion,
148    ICR_Complex_Real_Conversion,
149    ICR_Conversion,
150    ICR_Conversion,
151    ICR_Writeback_Conversion
152  };
153  return Rank[(int)Kind];
154}
155
156/// GetImplicitConversionName - Return the name of this kind of
157/// implicit conversion.
158const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
159  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
160    "No conversion",
161    "Lvalue-to-rvalue",
162    "Array-to-pointer",
163    "Function-to-pointer",
164    "Noreturn adjustment",
165    "Qualification",
166    "Integral promotion",
167    "Floating point promotion",
168    "Complex promotion",
169    "Integral conversion",
170    "Floating conversion",
171    "Complex conversion",
172    "Floating-integral conversion",
173    "Pointer conversion",
174    "Pointer-to-member conversion",
175    "Boolean conversion",
176    "Compatible-types conversion",
177    "Derived-to-base conversion",
178    "Vector conversion",
179    "Vector splat",
180    "Complex-real conversion",
181    "Block Pointer conversion",
182    "Transparent Union Conversion"
183    "Writeback conversion"
184  };
185  return Name[Kind];
186}
187
188/// StandardConversionSequence - Set the standard conversion
189/// sequence to the identity conversion.
190void StandardConversionSequence::setAsIdentityConversion() {
191  First = ICK_Identity;
192  Second = ICK_Identity;
193  Third = ICK_Identity;
194  DeprecatedStringLiteralToCharPtr = false;
195  QualificationIncludesObjCLifetime = false;
196  ReferenceBinding = false;
197  DirectBinding = false;
198  IsLvalueReference = true;
199  BindsToFunctionLvalue = false;
200  BindsToRvalue = false;
201  BindsImplicitObjectArgumentWithoutRefQualifier = false;
202  ObjCLifetimeConversionBinding = false;
203  CopyConstructor = 0;
204}
205
206/// getRank - Retrieve the rank of this standard conversion sequence
207/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
208/// implicit conversions.
209ImplicitConversionRank StandardConversionSequence::getRank() const {
210  ImplicitConversionRank Rank = ICR_Exact_Match;
211  if  (GetConversionRank(First) > Rank)
212    Rank = GetConversionRank(First);
213  if  (GetConversionRank(Second) > Rank)
214    Rank = GetConversionRank(Second);
215  if  (GetConversionRank(Third) > Rank)
216    Rank = GetConversionRank(Third);
217  return Rank;
218}
219
220/// isPointerConversionToBool - Determines whether this conversion is
221/// a conversion of a pointer or pointer-to-member to bool. This is
222/// used as part of the ranking of standard conversion sequences
223/// (C++ 13.3.3.2p4).
224bool StandardConversionSequence::isPointerConversionToBool() const {
225  // Note that FromType has not necessarily been transformed by the
226  // array-to-pointer or function-to-pointer implicit conversions, so
227  // check for their presence as well as checking whether FromType is
228  // a pointer.
229  if (getToType(1)->isBooleanType() &&
230      (getFromType()->isPointerType() ||
231       getFromType()->isObjCObjectPointerType() ||
232       getFromType()->isBlockPointerType() ||
233       getFromType()->isNullPtrType() ||
234       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235    return true;
236
237  return false;
238}
239
240/// isPointerConversionToVoidPointer - Determines whether this
241/// conversion is a conversion of a pointer to a void pointer. This is
242/// used as part of the ranking of standard conversion sequences (C++
243/// 13.3.3.2p4).
244bool
245StandardConversionSequence::
246isPointerConversionToVoidPointer(ASTContext& Context) const {
247  QualType FromType = getFromType();
248  QualType ToType = getToType(1);
249
250  // Note that FromType has not necessarily been transformed by the
251  // array-to-pointer implicit conversion, so check for its presence
252  // and redo the conversion to get a pointer.
253  if (First == ICK_Array_To_Pointer)
254    FromType = Context.getArrayDecayedType(FromType);
255
256  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
257    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
258      return ToPtrType->getPointeeType()->isVoidType();
259
260  return false;
261}
262
263/// Skip any implicit casts which could be either part of a narrowing conversion
264/// or after one in an implicit conversion.
265static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
266  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
267    switch (ICE->getCastKind()) {
268    case CK_NoOp:
269    case CK_IntegralCast:
270    case CK_IntegralToBoolean:
271    case CK_IntegralToFloating:
272    case CK_FloatingToIntegral:
273    case CK_FloatingToBoolean:
274    case CK_FloatingCast:
275      Converted = ICE->getSubExpr();
276      continue;
277
278    default:
279      return Converted;
280    }
281  }
282
283  return Converted;
284}
285
286/// Check if this standard conversion sequence represents a narrowing
287/// conversion, according to C++11 [dcl.init.list]p7.
288///
289/// \param Ctx  The AST context.
290/// \param Converted  The result of applying this standard conversion sequence.
291/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
292///        value of the expression prior to the narrowing conversion.
293/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
294///        type of the expression prior to the narrowing conversion.
295NarrowingKind
296StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
297                                             const Expr *Converted,
298                                             APValue &ConstantValue,
299                                             QualType &ConstantType) const {
300  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
301
302  // C++11 [dcl.init.list]p7:
303  //   A narrowing conversion is an implicit conversion ...
304  QualType FromType = getToType(0);
305  QualType ToType = getToType(1);
306  switch (Second) {
307  // -- from a floating-point type to an integer type, or
308  //
309  // -- from an integer type or unscoped enumeration type to a floating-point
310  //    type, except where the source is a constant expression and the actual
311  //    value after conversion will fit into the target type and will produce
312  //    the original value when converted back to the original type, or
313  case ICK_Floating_Integral:
314    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
315      return NK_Type_Narrowing;
316    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
317      llvm::APSInt IntConstantValue;
318      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
319      if (Initializer &&
320          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
321        // Convert the integer to the floating type.
322        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
323        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
324                                llvm::APFloat::rmNearestTiesToEven);
325        // And back.
326        llvm::APSInt ConvertedValue = IntConstantValue;
327        bool ignored;
328        Result.convertToInteger(ConvertedValue,
329                                llvm::APFloat::rmTowardZero, &ignored);
330        // If the resulting value is different, this was a narrowing conversion.
331        if (IntConstantValue != ConvertedValue) {
332          ConstantValue = APValue(IntConstantValue);
333          ConstantType = Initializer->getType();
334          return NK_Constant_Narrowing;
335        }
336      } else {
337        // Variables are always narrowings.
338        return NK_Variable_Narrowing;
339      }
340    }
341    return NK_Not_Narrowing;
342
343  // -- from long double to double or float, or from double to float, except
344  //    where the source is a constant expression and the actual value after
345  //    conversion is within the range of values that can be represented (even
346  //    if it cannot be represented exactly), or
347  case ICK_Floating_Conversion:
348    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
349        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
350      // FromType is larger than ToType.
351      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
352      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
353        // Constant!
354        assert(ConstantValue.isFloat());
355        llvm::APFloat FloatVal = ConstantValue.getFloat();
356        // Convert the source value into the target type.
357        bool ignored;
358        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
359          Ctx.getFloatTypeSemantics(ToType),
360          llvm::APFloat::rmNearestTiesToEven, &ignored);
361        // If there was no overflow, the source value is within the range of
362        // values that can be represented.
363        if (ConvertStatus & llvm::APFloat::opOverflow) {
364          ConstantType = Initializer->getType();
365          return NK_Constant_Narrowing;
366        }
367      } else {
368        return NK_Variable_Narrowing;
369      }
370    }
371    return NK_Not_Narrowing;
372
373  // -- from an integer type or unscoped enumeration type to an integer type
374  //    that cannot represent all the values of the original type, except where
375  //    the source is a constant expression and the actual value after
376  //    conversion will fit into the target type and will produce the original
377  //    value when converted back to the original type.
378  case ICK_Boolean_Conversion:  // Bools are integers too.
379    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
380      // Boolean conversions can be from pointers and pointers to members
381      // [conv.bool], and those aren't considered narrowing conversions.
382      return NK_Not_Narrowing;
383    }  // Otherwise, fall through to the integral case.
384  case ICK_Integral_Conversion: {
385    assert(FromType->isIntegralOrUnscopedEnumerationType());
386    assert(ToType->isIntegralOrUnscopedEnumerationType());
387    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
388    const unsigned FromWidth = Ctx.getIntWidth(FromType);
389    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
390    const unsigned ToWidth = Ctx.getIntWidth(ToType);
391
392    if (FromWidth > ToWidth ||
393        (FromWidth == ToWidth && FromSigned != ToSigned) ||
394        (FromSigned && !ToSigned)) {
395      // Not all values of FromType can be represented in ToType.
396      llvm::APSInt InitializerValue;
397      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
398      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
399        // Such conversions on variables are always narrowing.
400        return NK_Variable_Narrowing;
401      }
402      bool Narrowing = false;
403      if (FromWidth < ToWidth) {
404        // Negative -> unsigned is narrowing. Otherwise, more bits is never
405        // narrowing.
406        if (InitializerValue.isSigned() && InitializerValue.isNegative())
407          Narrowing = true;
408      } else {
409        // Add a bit to the InitializerValue so we don't have to worry about
410        // signed vs. unsigned comparisons.
411        InitializerValue = InitializerValue.extend(
412          InitializerValue.getBitWidth() + 1);
413        // Convert the initializer to and from the target width and signed-ness.
414        llvm::APSInt ConvertedValue = InitializerValue;
415        ConvertedValue = ConvertedValue.trunc(ToWidth);
416        ConvertedValue.setIsSigned(ToSigned);
417        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
418        ConvertedValue.setIsSigned(InitializerValue.isSigned());
419        // If the result is different, this was a narrowing conversion.
420        if (ConvertedValue != InitializerValue)
421          Narrowing = true;
422      }
423      if (Narrowing) {
424        ConstantType = Initializer->getType();
425        ConstantValue = APValue(InitializerValue);
426        return NK_Constant_Narrowing;
427      }
428    }
429    return NK_Not_Narrowing;
430  }
431
432  default:
433    // Other kinds of conversions are not narrowings.
434    return NK_Not_Narrowing;
435  }
436}
437
438/// DebugPrint - Print this standard conversion sequence to standard
439/// error. Useful for debugging overloading issues.
440void StandardConversionSequence::DebugPrint() const {
441  raw_ostream &OS = llvm::errs();
442  bool PrintedSomething = false;
443  if (First != ICK_Identity) {
444    OS << GetImplicitConversionName(First);
445    PrintedSomething = true;
446  }
447
448  if (Second != ICK_Identity) {
449    if (PrintedSomething) {
450      OS << " -> ";
451    }
452    OS << GetImplicitConversionName(Second);
453
454    if (CopyConstructor) {
455      OS << " (by copy constructor)";
456    } else if (DirectBinding) {
457      OS << " (direct reference binding)";
458    } else if (ReferenceBinding) {
459      OS << " (reference binding)";
460    }
461    PrintedSomething = true;
462  }
463
464  if (Third != ICK_Identity) {
465    if (PrintedSomething) {
466      OS << " -> ";
467    }
468    OS << GetImplicitConversionName(Third);
469    PrintedSomething = true;
470  }
471
472  if (!PrintedSomething) {
473    OS << "No conversions required";
474  }
475}
476
477/// DebugPrint - Print this user-defined conversion sequence to standard
478/// error. Useful for debugging overloading issues.
479void UserDefinedConversionSequence::DebugPrint() const {
480  raw_ostream &OS = llvm::errs();
481  if (Before.First || Before.Second || Before.Third) {
482    Before.DebugPrint();
483    OS << " -> ";
484  }
485  if (ConversionFunction)
486    OS << '\'' << *ConversionFunction << '\'';
487  else
488    OS << "aggregate initialization";
489  if (After.First || After.Second || After.Third) {
490    OS << " -> ";
491    After.DebugPrint();
492  }
493}
494
495/// DebugPrint - Print this implicit conversion sequence to standard
496/// error. Useful for debugging overloading issues.
497void ImplicitConversionSequence::DebugPrint() const {
498  raw_ostream &OS = llvm::errs();
499  switch (ConversionKind) {
500  case StandardConversion:
501    OS << "Standard conversion: ";
502    Standard.DebugPrint();
503    break;
504  case UserDefinedConversion:
505    OS << "User-defined conversion: ";
506    UserDefined.DebugPrint();
507    break;
508  case EllipsisConversion:
509    OS << "Ellipsis conversion";
510    break;
511  case AmbiguousConversion:
512    OS << "Ambiguous conversion";
513    break;
514  case BadConversion:
515    OS << "Bad conversion";
516    break;
517  }
518
519  OS << "\n";
520}
521
522void AmbiguousConversionSequence::construct() {
523  new (&conversions()) ConversionSet();
524}
525
526void AmbiguousConversionSequence::destruct() {
527  conversions().~ConversionSet();
528}
529
530void
531AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
532  FromTypePtr = O.FromTypePtr;
533  ToTypePtr = O.ToTypePtr;
534  new (&conversions()) ConversionSet(O.conversions());
535}
536
537namespace {
538  // Structure used by OverloadCandidate::DeductionFailureInfo to store
539  // template parameter and template argument information.
540  struct DFIParamWithArguments {
541    TemplateParameter Param;
542    TemplateArgument FirstArg;
543    TemplateArgument SecondArg;
544  };
545}
546
547/// \brief Convert from Sema's representation of template deduction information
548/// to the form used in overload-candidate information.
549OverloadCandidate::DeductionFailureInfo
550static MakeDeductionFailureInfo(ASTContext &Context,
551                                Sema::TemplateDeductionResult TDK,
552                                TemplateDeductionInfo &Info) {
553  OverloadCandidate::DeductionFailureInfo Result;
554  Result.Result = static_cast<unsigned>(TDK);
555  Result.HasDiagnostic = false;
556  Result.Data = 0;
557  switch (TDK) {
558  case Sema::TDK_Success:
559  case Sema::TDK_Invalid:
560  case Sema::TDK_InstantiationDepth:
561  case Sema::TDK_TooManyArguments:
562  case Sema::TDK_TooFewArguments:
563    break;
564
565  case Sema::TDK_Incomplete:
566  case Sema::TDK_InvalidExplicitArguments:
567    Result.Data = Info.Param.getOpaqueValue();
568    break;
569
570  case Sema::TDK_Inconsistent:
571  case Sema::TDK_Underqualified: {
572    // FIXME: Should allocate from normal heap so that we can free this later.
573    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
574    Saved->Param = Info.Param;
575    Saved->FirstArg = Info.FirstArg;
576    Saved->SecondArg = Info.SecondArg;
577    Result.Data = Saved;
578    break;
579  }
580
581  case Sema::TDK_SubstitutionFailure:
582    Result.Data = Info.take();
583    if (Info.hasSFINAEDiagnostic()) {
584      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
585          SourceLocation(), PartialDiagnostic::NullDiagnostic());
586      Info.takeSFINAEDiagnostic(*Diag);
587      Result.HasDiagnostic = true;
588    }
589    break;
590
591  case Sema::TDK_NonDeducedMismatch:
592  case Sema::TDK_FailedOverloadResolution:
593    break;
594  }
595
596  return Result;
597}
598
599void OverloadCandidate::DeductionFailureInfo::Destroy() {
600  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601  case Sema::TDK_Success:
602  case Sema::TDK_Invalid:
603  case Sema::TDK_InstantiationDepth:
604  case Sema::TDK_Incomplete:
605  case Sema::TDK_TooManyArguments:
606  case Sema::TDK_TooFewArguments:
607  case Sema::TDK_InvalidExplicitArguments:
608    break;
609
610  case Sema::TDK_Inconsistent:
611  case Sema::TDK_Underqualified:
612    // FIXME: Destroy the data?
613    Data = 0;
614    break;
615
616  case Sema::TDK_SubstitutionFailure:
617    // FIXME: Destroy the template argument list?
618    Data = 0;
619    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
620      Diag->~PartialDiagnosticAt();
621      HasDiagnostic = false;
622    }
623    break;
624
625  // Unhandled
626  case Sema::TDK_NonDeducedMismatch:
627  case Sema::TDK_FailedOverloadResolution:
628    break;
629  }
630}
631
632PartialDiagnosticAt *
633OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
634  if (HasDiagnostic)
635    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
636  return 0;
637}
638
639TemplateParameter
640OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
641  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
642  case Sema::TDK_Success:
643  case Sema::TDK_Invalid:
644  case Sema::TDK_InstantiationDepth:
645  case Sema::TDK_TooManyArguments:
646  case Sema::TDK_TooFewArguments:
647  case Sema::TDK_SubstitutionFailure:
648    return TemplateParameter();
649
650  case Sema::TDK_Incomplete:
651  case Sema::TDK_InvalidExplicitArguments:
652    return TemplateParameter::getFromOpaqueValue(Data);
653
654  case Sema::TDK_Inconsistent:
655  case Sema::TDK_Underqualified:
656    return static_cast<DFIParamWithArguments*>(Data)->Param;
657
658  // Unhandled
659  case Sema::TDK_NonDeducedMismatch:
660  case Sema::TDK_FailedOverloadResolution:
661    break;
662  }
663
664  return TemplateParameter();
665}
666
667TemplateArgumentList *
668OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
669  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
670    case Sema::TDK_Success:
671    case Sema::TDK_Invalid:
672    case Sema::TDK_InstantiationDepth:
673    case Sema::TDK_TooManyArguments:
674    case Sema::TDK_TooFewArguments:
675    case Sema::TDK_Incomplete:
676    case Sema::TDK_InvalidExplicitArguments:
677    case Sema::TDK_Inconsistent:
678    case Sema::TDK_Underqualified:
679      return 0;
680
681    case Sema::TDK_SubstitutionFailure:
682      return static_cast<TemplateArgumentList*>(Data);
683
684    // Unhandled
685    case Sema::TDK_NonDeducedMismatch:
686    case Sema::TDK_FailedOverloadResolution:
687      break;
688  }
689
690  return 0;
691}
692
693const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
694  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695  case Sema::TDK_Success:
696  case Sema::TDK_Invalid:
697  case Sema::TDK_InstantiationDepth:
698  case Sema::TDK_Incomplete:
699  case Sema::TDK_TooManyArguments:
700  case Sema::TDK_TooFewArguments:
701  case Sema::TDK_InvalidExplicitArguments:
702  case Sema::TDK_SubstitutionFailure:
703    return 0;
704
705  case Sema::TDK_Inconsistent:
706  case Sema::TDK_Underqualified:
707    return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
708
709  // Unhandled
710  case Sema::TDK_NonDeducedMismatch:
711  case Sema::TDK_FailedOverloadResolution:
712    break;
713  }
714
715  return 0;
716}
717
718const TemplateArgument *
719OverloadCandidate::DeductionFailureInfo::getSecondArg() {
720  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721  case Sema::TDK_Success:
722  case Sema::TDK_Invalid:
723  case Sema::TDK_InstantiationDepth:
724  case Sema::TDK_Incomplete:
725  case Sema::TDK_TooManyArguments:
726  case Sema::TDK_TooFewArguments:
727  case Sema::TDK_InvalidExplicitArguments:
728  case Sema::TDK_SubstitutionFailure:
729    return 0;
730
731  case Sema::TDK_Inconsistent:
732  case Sema::TDK_Underqualified:
733    return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
734
735  // Unhandled
736  case Sema::TDK_NonDeducedMismatch:
737  case Sema::TDK_FailedOverloadResolution:
738    break;
739  }
740
741  return 0;
742}
743
744void OverloadCandidateSet::destroyCandidates() {
745  for (iterator i = begin(), e = end(); i != e; ++i) {
746    for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
747      i->Conversions[ii].~ImplicitConversionSequence();
748    if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
749      i->DeductionFailure.Destroy();
750  }
751}
752
753void OverloadCandidateSet::clear() {
754  destroyCandidates();
755  NumInlineSequences = 0;
756  Candidates.clear();
757  Functions.clear();
758}
759
760namespace {
761  class UnbridgedCastsSet {
762    struct Entry {
763      Expr **Addr;
764      Expr *Saved;
765    };
766    SmallVector<Entry, 2> Entries;
767
768  public:
769    void save(Sema &S, Expr *&E) {
770      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
771      Entry entry = { &E, E };
772      Entries.push_back(entry);
773      E = S.stripARCUnbridgedCast(E);
774    }
775
776    void restore() {
777      for (SmallVectorImpl<Entry>::iterator
778             i = Entries.begin(), e = Entries.end(); i != e; ++i)
779        *i->Addr = i->Saved;
780    }
781  };
782}
783
784/// checkPlaceholderForOverload - Do any interesting placeholder-like
785/// preprocessing on the given expression.
786///
787/// \param unbridgedCasts a collection to which to add unbridged casts;
788///   without this, they will be immediately diagnosed as errors
789///
790/// Return true on unrecoverable error.
791static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
792                                        UnbridgedCastsSet *unbridgedCasts = 0) {
793  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
794    // We can't handle overloaded expressions here because overload
795    // resolution might reasonably tweak them.
796    if (placeholder->getKind() == BuiltinType::Overload) return false;
797
798    // If the context potentially accepts unbridged ARC casts, strip
799    // the unbridged cast and add it to the collection for later restoration.
800    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
801        unbridgedCasts) {
802      unbridgedCasts->save(S, E);
803      return false;
804    }
805
806    // Go ahead and check everything else.
807    ExprResult result = S.CheckPlaceholderExpr(E);
808    if (result.isInvalid())
809      return true;
810
811    E = result.take();
812    return false;
813  }
814
815  // Nothing to do.
816  return false;
817}
818
819/// checkArgPlaceholdersForOverload - Check a set of call operands for
820/// placeholders.
821static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
822                                            unsigned numArgs,
823                                            UnbridgedCastsSet &unbridged) {
824  for (unsigned i = 0; i != numArgs; ++i)
825    if (checkPlaceholderForOverload(S, args[i], &unbridged))
826      return true;
827
828  return false;
829}
830
831// IsOverload - Determine whether the given New declaration is an
832// overload of the declarations in Old. This routine returns false if
833// New and Old cannot be overloaded, e.g., if New has the same
834// signature as some function in Old (C++ 1.3.10) or if the Old
835// declarations aren't functions (or function templates) at all. When
836// it does return false, MatchedDecl will point to the decl that New
837// cannot be overloaded with.  This decl may be a UsingShadowDecl on
838// top of the underlying declaration.
839//
840// Example: Given the following input:
841//
842//   void f(int, float); // #1
843//   void f(int, int); // #2
844//   int f(int, int); // #3
845//
846// When we process #1, there is no previous declaration of "f",
847// so IsOverload will not be used.
848//
849// When we process #2, Old contains only the FunctionDecl for #1.  By
850// comparing the parameter types, we see that #1 and #2 are overloaded
851// (since they have different signatures), so this routine returns
852// false; MatchedDecl is unchanged.
853//
854// When we process #3, Old is an overload set containing #1 and #2. We
855// compare the signatures of #3 to #1 (they're overloaded, so we do
856// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
857// identical (return types of functions are not part of the
858// signature), IsOverload returns false and MatchedDecl will be set to
859// point to the FunctionDecl for #2.
860//
861// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
862// into a class by a using declaration.  The rules for whether to hide
863// shadow declarations ignore some properties which otherwise figure
864// into a function template's signature.
865Sema::OverloadKind
866Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
867                    NamedDecl *&Match, bool NewIsUsingDecl) {
868  for (LookupResult::iterator I = Old.begin(), E = Old.end();
869         I != E; ++I) {
870    NamedDecl *OldD = *I;
871
872    bool OldIsUsingDecl = false;
873    if (isa<UsingShadowDecl>(OldD)) {
874      OldIsUsingDecl = true;
875
876      // We can always introduce two using declarations into the same
877      // context, even if they have identical signatures.
878      if (NewIsUsingDecl) continue;
879
880      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
881    }
882
883    // If either declaration was introduced by a using declaration,
884    // we'll need to use slightly different rules for matching.
885    // Essentially, these rules are the normal rules, except that
886    // function templates hide function templates with different
887    // return types or template parameter lists.
888    bool UseMemberUsingDeclRules =
889      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
890
891    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
892      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
893        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
894          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
895          continue;
896        }
897
898        Match = *I;
899        return Ovl_Match;
900      }
901    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
902      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
903        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
904          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
905          continue;
906        }
907
908        Match = *I;
909        return Ovl_Match;
910      }
911    } else if (isa<UsingDecl>(OldD)) {
912      // We can overload with these, which can show up when doing
913      // redeclaration checks for UsingDecls.
914      assert(Old.getLookupKind() == LookupUsingDeclName);
915    } else if (isa<TagDecl>(OldD)) {
916      // We can always overload with tags by hiding them.
917    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
918      // Optimistically assume that an unresolved using decl will
919      // overload; if it doesn't, we'll have to diagnose during
920      // template instantiation.
921    } else {
922      // (C++ 13p1):
923      //   Only function declarations can be overloaded; object and type
924      //   declarations cannot be overloaded.
925      Match = *I;
926      return Ovl_NonFunction;
927    }
928  }
929
930  return Ovl_Overload;
931}
932
933static bool canBeOverloaded(const FunctionDecl &D) {
934  if (D.getAttr<OverloadableAttr>())
935    return true;
936  if (D.hasCLanguageLinkage())
937    return false;
938  return true;
939}
940
941bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
942                      bool UseUsingDeclRules) {
943  // If both of the functions are extern "C", then they are not
944  // overloads.
945  if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
946    return false;
947
948  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
949  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
950
951  // C++ [temp.fct]p2:
952  //   A function template can be overloaded with other function templates
953  //   and with normal (non-template) functions.
954  if ((OldTemplate == 0) != (NewTemplate == 0))
955    return true;
956
957  // Is the function New an overload of the function Old?
958  QualType OldQType = Context.getCanonicalType(Old->getType());
959  QualType NewQType = Context.getCanonicalType(New->getType());
960
961  // Compare the signatures (C++ 1.3.10) of the two functions to
962  // determine whether they are overloads. If we find any mismatch
963  // in the signature, they are overloads.
964
965  // If either of these functions is a K&R-style function (no
966  // prototype), then we consider them to have matching signatures.
967  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
968      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
969    return false;
970
971  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
972  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
973
974  // The signature of a function includes the types of its
975  // parameters (C++ 1.3.10), which includes the presence or absence
976  // of the ellipsis; see C++ DR 357).
977  if (OldQType != NewQType &&
978      (OldType->getNumArgs() != NewType->getNumArgs() ||
979       OldType->isVariadic() != NewType->isVariadic() ||
980       !FunctionArgTypesAreEqual(OldType, NewType)))
981    return true;
982
983  // C++ [temp.over.link]p4:
984  //   The signature of a function template consists of its function
985  //   signature, its return type and its template parameter list. The names
986  //   of the template parameters are significant only for establishing the
987  //   relationship between the template parameters and the rest of the
988  //   signature.
989  //
990  // We check the return type and template parameter lists for function
991  // templates first; the remaining checks follow.
992  //
993  // However, we don't consider either of these when deciding whether
994  // a member introduced by a shadow declaration is hidden.
995  if (!UseUsingDeclRules && NewTemplate &&
996      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
997                                       OldTemplate->getTemplateParameters(),
998                                       false, TPL_TemplateMatch) ||
999       OldType->getResultType() != NewType->getResultType()))
1000    return true;
1001
1002  // If the function is a class member, its signature includes the
1003  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1004  //
1005  // As part of this, also check whether one of the member functions
1006  // is static, in which case they are not overloads (C++
1007  // 13.1p2). While not part of the definition of the signature,
1008  // this check is important to determine whether these functions
1009  // can be overloaded.
1010  CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1011  CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1012  if (OldMethod && NewMethod &&
1013      !OldMethod->isStatic() && !NewMethod->isStatic() &&
1014      (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
1015       OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
1016    if (!UseUsingDeclRules &&
1017        OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
1018        (OldMethod->getRefQualifier() == RQ_None ||
1019         NewMethod->getRefQualifier() == RQ_None)) {
1020      // C++0x [over.load]p2:
1021      //   - Member function declarations with the same name and the same
1022      //     parameter-type-list as well as member function template
1023      //     declarations with the same name, the same parameter-type-list, and
1024      //     the same template parameter lists cannot be overloaded if any of
1025      //     them, but not all, have a ref-qualifier (8.3.5).
1026      Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1027        << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1028      Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1029    }
1030
1031    return true;
1032  }
1033
1034  // The signatures match; this is not an overload.
1035  return false;
1036}
1037
1038/// \brief Checks availability of the function depending on the current
1039/// function context. Inside an unavailable function, unavailability is ignored.
1040///
1041/// \returns true if \arg FD is unavailable and current context is inside
1042/// an available function, false otherwise.
1043bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1044  return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1045}
1046
1047/// \brief Tries a user-defined conversion from From to ToType.
1048///
1049/// Produces an implicit conversion sequence for when a standard conversion
1050/// is not an option. See TryImplicitConversion for more information.
1051static ImplicitConversionSequence
1052TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1053                         bool SuppressUserConversions,
1054                         bool AllowExplicit,
1055                         bool InOverloadResolution,
1056                         bool CStyle,
1057                         bool AllowObjCWritebackConversion) {
1058  ImplicitConversionSequence ICS;
1059
1060  if (SuppressUserConversions) {
1061    // We're not in the case above, so there is no conversion that
1062    // we can perform.
1063    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1064    return ICS;
1065  }
1066
1067  // Attempt user-defined conversion.
1068  OverloadCandidateSet Conversions(From->getExprLoc());
1069  OverloadingResult UserDefResult
1070    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1071                              AllowExplicit);
1072
1073  if (UserDefResult == OR_Success) {
1074    ICS.setUserDefined();
1075    // C++ [over.ics.user]p4:
1076    //   A conversion of an expression of class type to the same class
1077    //   type is given Exact Match rank, and a conversion of an
1078    //   expression of class type to a base class of that type is
1079    //   given Conversion rank, in spite of the fact that a copy
1080    //   constructor (i.e., a user-defined conversion function) is
1081    //   called for those cases.
1082    if (CXXConstructorDecl *Constructor
1083          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1084      QualType FromCanon
1085        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1086      QualType ToCanon
1087        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1088      if (Constructor->isCopyConstructor() &&
1089          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1090        // Turn this into a "standard" conversion sequence, so that it
1091        // gets ranked with standard conversion sequences.
1092        ICS.setStandard();
1093        ICS.Standard.setAsIdentityConversion();
1094        ICS.Standard.setFromType(From->getType());
1095        ICS.Standard.setAllToTypes(ToType);
1096        ICS.Standard.CopyConstructor = Constructor;
1097        if (ToCanon != FromCanon)
1098          ICS.Standard.Second = ICK_Derived_To_Base;
1099      }
1100    }
1101
1102    // C++ [over.best.ics]p4:
1103    //   However, when considering the argument of a user-defined
1104    //   conversion function that is a candidate by 13.3.1.3 when
1105    //   invoked for the copying of the temporary in the second step
1106    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1107    //   13.3.1.6 in all cases, only standard conversion sequences and
1108    //   ellipsis conversion sequences are allowed.
1109    if (SuppressUserConversions && ICS.isUserDefined()) {
1110      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1111    }
1112  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1113    ICS.setAmbiguous();
1114    ICS.Ambiguous.setFromType(From->getType());
1115    ICS.Ambiguous.setToType(ToType);
1116    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1117         Cand != Conversions.end(); ++Cand)
1118      if (Cand->Viable)
1119        ICS.Ambiguous.addConversion(Cand->Function);
1120  } else {
1121    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1122  }
1123
1124  return ICS;
1125}
1126
1127/// TryImplicitConversion - Attempt to perform an implicit conversion
1128/// from the given expression (Expr) to the given type (ToType). This
1129/// function returns an implicit conversion sequence that can be used
1130/// to perform the initialization. Given
1131///
1132///   void f(float f);
1133///   void g(int i) { f(i); }
1134///
1135/// this routine would produce an implicit conversion sequence to
1136/// describe the initialization of f from i, which will be a standard
1137/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1138/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1139//
1140/// Note that this routine only determines how the conversion can be
1141/// performed; it does not actually perform the conversion. As such,
1142/// it will not produce any diagnostics if no conversion is available,
1143/// but will instead return an implicit conversion sequence of kind
1144/// "BadConversion".
1145///
1146/// If @p SuppressUserConversions, then user-defined conversions are
1147/// not permitted.
1148/// If @p AllowExplicit, then explicit user-defined conversions are
1149/// permitted.
1150///
1151/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1152/// writeback conversion, which allows __autoreleasing id* parameters to
1153/// be initialized with __strong id* or __weak id* arguments.
1154static ImplicitConversionSequence
1155TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1156                      bool SuppressUserConversions,
1157                      bool AllowExplicit,
1158                      bool InOverloadResolution,
1159                      bool CStyle,
1160                      bool AllowObjCWritebackConversion) {
1161  ImplicitConversionSequence ICS;
1162  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1163                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1164    ICS.setStandard();
1165    return ICS;
1166  }
1167
1168  if (!S.getLangOpts().CPlusPlus) {
1169    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1170    return ICS;
1171  }
1172
1173  // C++ [over.ics.user]p4:
1174  //   A conversion of an expression of class type to the same class
1175  //   type is given Exact Match rank, and a conversion of an
1176  //   expression of class type to a base class of that type is
1177  //   given Conversion rank, in spite of the fact that a copy/move
1178  //   constructor (i.e., a user-defined conversion function) is
1179  //   called for those cases.
1180  QualType FromType = From->getType();
1181  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1182      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1183       S.IsDerivedFrom(FromType, ToType))) {
1184    ICS.setStandard();
1185    ICS.Standard.setAsIdentityConversion();
1186    ICS.Standard.setFromType(FromType);
1187    ICS.Standard.setAllToTypes(ToType);
1188
1189    // We don't actually check at this point whether there is a valid
1190    // copy/move constructor, since overloading just assumes that it
1191    // exists. When we actually perform initialization, we'll find the
1192    // appropriate constructor to copy the returned object, if needed.
1193    ICS.Standard.CopyConstructor = 0;
1194
1195    // Determine whether this is considered a derived-to-base conversion.
1196    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1197      ICS.Standard.Second = ICK_Derived_To_Base;
1198
1199    return ICS;
1200  }
1201
1202  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1203                                  AllowExplicit, InOverloadResolution, CStyle,
1204                                  AllowObjCWritebackConversion);
1205}
1206
1207ImplicitConversionSequence
1208Sema::TryImplicitConversion(Expr *From, QualType ToType,
1209                            bool SuppressUserConversions,
1210                            bool AllowExplicit,
1211                            bool InOverloadResolution,
1212                            bool CStyle,
1213                            bool AllowObjCWritebackConversion) {
1214  return clang::TryImplicitConversion(*this, From, ToType,
1215                                      SuppressUserConversions, AllowExplicit,
1216                                      InOverloadResolution, CStyle,
1217                                      AllowObjCWritebackConversion);
1218}
1219
1220/// PerformImplicitConversion - Perform an implicit conversion of the
1221/// expression From to the type ToType. Returns the
1222/// converted expression. Flavor is the kind of conversion we're
1223/// performing, used in the error message. If @p AllowExplicit,
1224/// explicit user-defined conversions are permitted.
1225ExprResult
1226Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1227                                AssignmentAction Action, bool AllowExplicit) {
1228  ImplicitConversionSequence ICS;
1229  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1230}
1231
1232ExprResult
1233Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1234                                AssignmentAction Action, bool AllowExplicit,
1235                                ImplicitConversionSequence& ICS) {
1236  if (checkPlaceholderForOverload(*this, From))
1237    return ExprError();
1238
1239  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1240  bool AllowObjCWritebackConversion
1241    = getLangOpts().ObjCAutoRefCount &&
1242      (Action == AA_Passing || Action == AA_Sending);
1243
1244  ICS = clang::TryImplicitConversion(*this, From, ToType,
1245                                     /*SuppressUserConversions=*/false,
1246                                     AllowExplicit,
1247                                     /*InOverloadResolution=*/false,
1248                                     /*CStyle=*/false,
1249                                     AllowObjCWritebackConversion);
1250  return PerformImplicitConversion(From, ToType, ICS, Action);
1251}
1252
1253/// \brief Determine whether the conversion from FromType to ToType is a valid
1254/// conversion that strips "noreturn" off the nested function type.
1255bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1256                                QualType &ResultTy) {
1257  if (Context.hasSameUnqualifiedType(FromType, ToType))
1258    return false;
1259
1260  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1261  // where F adds one of the following at most once:
1262  //   - a pointer
1263  //   - a member pointer
1264  //   - a block pointer
1265  CanQualType CanTo = Context.getCanonicalType(ToType);
1266  CanQualType CanFrom = Context.getCanonicalType(FromType);
1267  Type::TypeClass TyClass = CanTo->getTypeClass();
1268  if (TyClass != CanFrom->getTypeClass()) return false;
1269  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1270    if (TyClass == Type::Pointer) {
1271      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1272      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1273    } else if (TyClass == Type::BlockPointer) {
1274      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1275      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1276    } else if (TyClass == Type::MemberPointer) {
1277      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1278      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1279    } else {
1280      return false;
1281    }
1282
1283    TyClass = CanTo->getTypeClass();
1284    if (TyClass != CanFrom->getTypeClass()) return false;
1285    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1286      return false;
1287  }
1288
1289  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1290  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1291  if (!EInfo.getNoReturn()) return false;
1292
1293  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1294  assert(QualType(FromFn, 0).isCanonical());
1295  if (QualType(FromFn, 0) != CanTo) return false;
1296
1297  ResultTy = ToType;
1298  return true;
1299}
1300
1301/// \brief Determine whether the conversion from FromType to ToType is a valid
1302/// vector conversion.
1303///
1304/// \param ICK Will be set to the vector conversion kind, if this is a vector
1305/// conversion.
1306static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1307                               QualType ToType, ImplicitConversionKind &ICK) {
1308  // We need at least one of these types to be a vector type to have a vector
1309  // conversion.
1310  if (!ToType->isVectorType() && !FromType->isVectorType())
1311    return false;
1312
1313  // Identical types require no conversions.
1314  if (Context.hasSameUnqualifiedType(FromType, ToType))
1315    return false;
1316
1317  // There are no conversions between extended vector types, only identity.
1318  if (ToType->isExtVectorType()) {
1319    // There are no conversions between extended vector types other than the
1320    // identity conversion.
1321    if (FromType->isExtVectorType())
1322      return false;
1323
1324    // Vector splat from any arithmetic type to a vector.
1325    if (FromType->isArithmeticType()) {
1326      ICK = ICK_Vector_Splat;
1327      return true;
1328    }
1329  }
1330
1331  // We can perform the conversion between vector types in the following cases:
1332  // 1)vector types are equivalent AltiVec and GCC vector types
1333  // 2)lax vector conversions are permitted and the vector types are of the
1334  //   same size
1335  if (ToType->isVectorType() && FromType->isVectorType()) {
1336    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1337        (Context.getLangOpts().LaxVectorConversions &&
1338         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1339      ICK = ICK_Vector_Conversion;
1340      return true;
1341    }
1342  }
1343
1344  return false;
1345}
1346
1347static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1348                                bool InOverloadResolution,
1349                                StandardConversionSequence &SCS,
1350                                bool CStyle);
1351
1352/// IsStandardConversion - Determines whether there is a standard
1353/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1354/// expression From to the type ToType. Standard conversion sequences
1355/// only consider non-class types; for conversions that involve class
1356/// types, use TryImplicitConversion. If a conversion exists, SCS will
1357/// contain the standard conversion sequence required to perform this
1358/// conversion and this routine will return true. Otherwise, this
1359/// routine will return false and the value of SCS is unspecified.
1360static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1361                                 bool InOverloadResolution,
1362                                 StandardConversionSequence &SCS,
1363                                 bool CStyle,
1364                                 bool AllowObjCWritebackConversion) {
1365  QualType FromType = From->getType();
1366
1367  // Standard conversions (C++ [conv])
1368  SCS.setAsIdentityConversion();
1369  SCS.DeprecatedStringLiteralToCharPtr = false;
1370  SCS.IncompatibleObjC = false;
1371  SCS.setFromType(FromType);
1372  SCS.CopyConstructor = 0;
1373
1374  // There are no standard conversions for class types in C++, so
1375  // abort early. When overloading in C, however, we do permit
1376  if (FromType->isRecordType() || ToType->isRecordType()) {
1377    if (S.getLangOpts().CPlusPlus)
1378      return false;
1379
1380    // When we're overloading in C, we allow, as standard conversions,
1381  }
1382
1383  // The first conversion can be an lvalue-to-rvalue conversion,
1384  // array-to-pointer conversion, or function-to-pointer conversion
1385  // (C++ 4p1).
1386
1387  if (FromType == S.Context.OverloadTy) {
1388    DeclAccessPair AccessPair;
1389    if (FunctionDecl *Fn
1390          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1391                                                 AccessPair)) {
1392      // We were able to resolve the address of the overloaded function,
1393      // so we can convert to the type of that function.
1394      FromType = Fn->getType();
1395
1396      // we can sometimes resolve &foo<int> regardless of ToType, so check
1397      // if the type matches (identity) or we are converting to bool
1398      if (!S.Context.hasSameUnqualifiedType(
1399                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1400        QualType resultTy;
1401        // if the function type matches except for [[noreturn]], it's ok
1402        if (!S.IsNoReturnConversion(FromType,
1403              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1404          // otherwise, only a boolean conversion is standard
1405          if (!ToType->isBooleanType())
1406            return false;
1407      }
1408
1409      // Check if the "from" expression is taking the address of an overloaded
1410      // function and recompute the FromType accordingly. Take advantage of the
1411      // fact that non-static member functions *must* have such an address-of
1412      // expression.
1413      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1414      if (Method && !Method->isStatic()) {
1415        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1416               "Non-unary operator on non-static member address");
1417        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1418               == UO_AddrOf &&
1419               "Non-address-of operator on non-static member address");
1420        const Type *ClassType
1421          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1422        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1423      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1424        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1425               UO_AddrOf &&
1426               "Non-address-of operator for overloaded function expression");
1427        FromType = S.Context.getPointerType(FromType);
1428      }
1429
1430      // Check that we've computed the proper type after overload resolution.
1431      assert(S.Context.hasSameType(
1432        FromType,
1433        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1434    } else {
1435      return false;
1436    }
1437  }
1438  // Lvalue-to-rvalue conversion (C++11 4.1):
1439  //   A glvalue (3.10) of a non-function, non-array type T can
1440  //   be converted to a prvalue.
1441  bool argIsLValue = From->isGLValue();
1442  if (argIsLValue &&
1443      !FromType->isFunctionType() && !FromType->isArrayType() &&
1444      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1445    SCS.First = ICK_Lvalue_To_Rvalue;
1446
1447    // C11 6.3.2.1p2:
1448    //   ... if the lvalue has atomic type, the value has the non-atomic version
1449    //   of the type of the lvalue ...
1450    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1451      FromType = Atomic->getValueType();
1452
1453    // If T is a non-class type, the type of the rvalue is the
1454    // cv-unqualified version of T. Otherwise, the type of the rvalue
1455    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1456    // just strip the qualifiers because they don't matter.
1457    FromType = FromType.getUnqualifiedType();
1458  } else if (FromType->isArrayType()) {
1459    // Array-to-pointer conversion (C++ 4.2)
1460    SCS.First = ICK_Array_To_Pointer;
1461
1462    // An lvalue or rvalue of type "array of N T" or "array of unknown
1463    // bound of T" can be converted to an rvalue of type "pointer to
1464    // T" (C++ 4.2p1).
1465    FromType = S.Context.getArrayDecayedType(FromType);
1466
1467    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1468      // This conversion is deprecated. (C++ D.4).
1469      SCS.DeprecatedStringLiteralToCharPtr = true;
1470
1471      // For the purpose of ranking in overload resolution
1472      // (13.3.3.1.1), this conversion is considered an
1473      // array-to-pointer conversion followed by a qualification
1474      // conversion (4.4). (C++ 4.2p2)
1475      SCS.Second = ICK_Identity;
1476      SCS.Third = ICK_Qualification;
1477      SCS.QualificationIncludesObjCLifetime = false;
1478      SCS.setAllToTypes(FromType);
1479      return true;
1480    }
1481  } else if (FromType->isFunctionType() && argIsLValue) {
1482    // Function-to-pointer conversion (C++ 4.3).
1483    SCS.First = ICK_Function_To_Pointer;
1484
1485    // An lvalue of function type T can be converted to an rvalue of
1486    // type "pointer to T." The result is a pointer to the
1487    // function. (C++ 4.3p1).
1488    FromType = S.Context.getPointerType(FromType);
1489  } else {
1490    // We don't require any conversions for the first step.
1491    SCS.First = ICK_Identity;
1492  }
1493  SCS.setToType(0, FromType);
1494
1495  // The second conversion can be an integral promotion, floating
1496  // point promotion, integral conversion, floating point conversion,
1497  // floating-integral conversion, pointer conversion,
1498  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1499  // For overloading in C, this can also be a "compatible-type"
1500  // conversion.
1501  bool IncompatibleObjC = false;
1502  ImplicitConversionKind SecondICK = ICK_Identity;
1503  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1504    // The unqualified versions of the types are the same: there's no
1505    // conversion to do.
1506    SCS.Second = ICK_Identity;
1507  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1508    // Integral promotion (C++ 4.5).
1509    SCS.Second = ICK_Integral_Promotion;
1510    FromType = ToType.getUnqualifiedType();
1511  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1512    // Floating point promotion (C++ 4.6).
1513    SCS.Second = ICK_Floating_Promotion;
1514    FromType = ToType.getUnqualifiedType();
1515  } else if (S.IsComplexPromotion(FromType, ToType)) {
1516    // Complex promotion (Clang extension)
1517    SCS.Second = ICK_Complex_Promotion;
1518    FromType = ToType.getUnqualifiedType();
1519  } else if (ToType->isBooleanType() &&
1520             (FromType->isArithmeticType() ||
1521              FromType->isAnyPointerType() ||
1522              FromType->isBlockPointerType() ||
1523              FromType->isMemberPointerType() ||
1524              FromType->isNullPtrType())) {
1525    // Boolean conversions (C++ 4.12).
1526    SCS.Second = ICK_Boolean_Conversion;
1527    FromType = S.Context.BoolTy;
1528  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1529             ToType->isIntegralType(S.Context)) {
1530    // Integral conversions (C++ 4.7).
1531    SCS.Second = ICK_Integral_Conversion;
1532    FromType = ToType.getUnqualifiedType();
1533  } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1534    // Complex conversions (C99 6.3.1.6)
1535    SCS.Second = ICK_Complex_Conversion;
1536    FromType = ToType.getUnqualifiedType();
1537  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1538             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1539    // Complex-real conversions (C99 6.3.1.7)
1540    SCS.Second = ICK_Complex_Real;
1541    FromType = ToType.getUnqualifiedType();
1542  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1543    // Floating point conversions (C++ 4.8).
1544    SCS.Second = ICK_Floating_Conversion;
1545    FromType = ToType.getUnqualifiedType();
1546  } else if ((FromType->isRealFloatingType() &&
1547              ToType->isIntegralType(S.Context)) ||
1548             (FromType->isIntegralOrUnscopedEnumerationType() &&
1549              ToType->isRealFloatingType())) {
1550    // Floating-integral conversions (C++ 4.9).
1551    SCS.Second = ICK_Floating_Integral;
1552    FromType = ToType.getUnqualifiedType();
1553  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1554    SCS.Second = ICK_Block_Pointer_Conversion;
1555  } else if (AllowObjCWritebackConversion &&
1556             S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1557    SCS.Second = ICK_Writeback_Conversion;
1558  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1559                                   FromType, IncompatibleObjC)) {
1560    // Pointer conversions (C++ 4.10).
1561    SCS.Second = ICK_Pointer_Conversion;
1562    SCS.IncompatibleObjC = IncompatibleObjC;
1563    FromType = FromType.getUnqualifiedType();
1564  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1565                                         InOverloadResolution, FromType)) {
1566    // Pointer to member conversions (4.11).
1567    SCS.Second = ICK_Pointer_Member;
1568  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1569    SCS.Second = SecondICK;
1570    FromType = ToType.getUnqualifiedType();
1571  } else if (!S.getLangOpts().CPlusPlus &&
1572             S.Context.typesAreCompatible(ToType, FromType)) {
1573    // Compatible conversions (Clang extension for C function overloading)
1574    SCS.Second = ICK_Compatible_Conversion;
1575    FromType = ToType.getUnqualifiedType();
1576  } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1577    // Treat a conversion that strips "noreturn" as an identity conversion.
1578    SCS.Second = ICK_NoReturn_Adjustment;
1579  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1580                                             InOverloadResolution,
1581                                             SCS, CStyle)) {
1582    SCS.Second = ICK_TransparentUnionConversion;
1583    FromType = ToType;
1584  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1585                                 CStyle)) {
1586    // tryAtomicConversion has updated the standard conversion sequence
1587    // appropriately.
1588    return true;
1589  } else {
1590    // No second conversion required.
1591    SCS.Second = ICK_Identity;
1592  }
1593  SCS.setToType(1, FromType);
1594
1595  QualType CanonFrom;
1596  QualType CanonTo;
1597  // The third conversion can be a qualification conversion (C++ 4p1).
1598  bool ObjCLifetimeConversion;
1599  if (S.IsQualificationConversion(FromType, ToType, CStyle,
1600                                  ObjCLifetimeConversion)) {
1601    SCS.Third = ICK_Qualification;
1602    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1603    FromType = ToType;
1604    CanonFrom = S.Context.getCanonicalType(FromType);
1605    CanonTo = S.Context.getCanonicalType(ToType);
1606  } else {
1607    // No conversion required
1608    SCS.Third = ICK_Identity;
1609
1610    // C++ [over.best.ics]p6:
1611    //   [...] Any difference in top-level cv-qualification is
1612    //   subsumed by the initialization itself and does not constitute
1613    //   a conversion. [...]
1614    CanonFrom = S.Context.getCanonicalType(FromType);
1615    CanonTo = S.Context.getCanonicalType(ToType);
1616    if (CanonFrom.getLocalUnqualifiedType()
1617                                       == CanonTo.getLocalUnqualifiedType() &&
1618        (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1619         || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1620         || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
1621      FromType = ToType;
1622      CanonFrom = CanonTo;
1623    }
1624  }
1625  SCS.setToType(2, FromType);
1626
1627  // If we have not converted the argument type to the parameter type,
1628  // this is a bad conversion sequence.
1629  if (CanonFrom != CanonTo)
1630    return false;
1631
1632  return true;
1633}
1634
1635static bool
1636IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1637                                     QualType &ToType,
1638                                     bool InOverloadResolution,
1639                                     StandardConversionSequence &SCS,
1640                                     bool CStyle) {
1641
1642  const RecordType *UT = ToType->getAsUnionType();
1643  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1644    return false;
1645  // The field to initialize within the transparent union.
1646  RecordDecl *UD = UT->getDecl();
1647  // It's compatible if the expression matches any of the fields.
1648  for (RecordDecl::field_iterator it = UD->field_begin(),
1649       itend = UD->field_end();
1650       it != itend; ++it) {
1651    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1652                             CStyle, /*ObjCWritebackConversion=*/false)) {
1653      ToType = it->getType();
1654      return true;
1655    }
1656  }
1657  return false;
1658}
1659
1660/// IsIntegralPromotion - Determines whether the conversion from the
1661/// expression From (whose potentially-adjusted type is FromType) to
1662/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1663/// sets PromotedType to the promoted type.
1664bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1665  const BuiltinType *To = ToType->getAs<BuiltinType>();
1666  // All integers are built-in.
1667  if (!To) {
1668    return false;
1669  }
1670
1671  // An rvalue of type char, signed char, unsigned char, short int, or
1672  // unsigned short int can be converted to an rvalue of type int if
1673  // int can represent all the values of the source type; otherwise,
1674  // the source rvalue can be converted to an rvalue of type unsigned
1675  // int (C++ 4.5p1).
1676  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1677      !FromType->isEnumeralType()) {
1678    if (// We can promote any signed, promotable integer type to an int
1679        (FromType->isSignedIntegerType() ||
1680         // We can promote any unsigned integer type whose size is
1681         // less than int to an int.
1682         (!FromType->isSignedIntegerType() &&
1683          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1684      return To->getKind() == BuiltinType::Int;
1685    }
1686
1687    return To->getKind() == BuiltinType::UInt;
1688  }
1689
1690  // C++11 [conv.prom]p3:
1691  //   A prvalue of an unscoped enumeration type whose underlying type is not
1692  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1693  //   following types that can represent all the values of the enumeration
1694  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1695  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1696  //   long long int. If none of the types in that list can represent all the
1697  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1698  //   type can be converted to an rvalue a prvalue of the extended integer type
1699  //   with lowest integer conversion rank (4.13) greater than the rank of long
1700  //   long in which all the values of the enumeration can be represented. If
1701  //   there are two such extended types, the signed one is chosen.
1702  // C++11 [conv.prom]p4:
1703  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1704  //   can be converted to a prvalue of its underlying type. Moreover, if
1705  //   integral promotion can be applied to its underlying type, a prvalue of an
1706  //   unscoped enumeration type whose underlying type is fixed can also be
1707  //   converted to a prvalue of the promoted underlying type.
1708  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1709    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1710    // provided for a scoped enumeration.
1711    if (FromEnumType->getDecl()->isScoped())
1712      return false;
1713
1714    // We can perform an integral promotion to the underlying type of the enum,
1715    // even if that's not the promoted type.
1716    if (FromEnumType->getDecl()->isFixed()) {
1717      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1718      return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1719             IsIntegralPromotion(From, Underlying, ToType);
1720    }
1721
1722    // We have already pre-calculated the promotion type, so this is trivial.
1723    if (ToType->isIntegerType() &&
1724        !RequireCompleteType(From->getLocStart(), FromType, 0))
1725      return Context.hasSameUnqualifiedType(ToType,
1726                                FromEnumType->getDecl()->getPromotionType());
1727  }
1728
1729  // C++0x [conv.prom]p2:
1730  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1731  //   to an rvalue a prvalue of the first of the following types that can
1732  //   represent all the values of its underlying type: int, unsigned int,
1733  //   long int, unsigned long int, long long int, or unsigned long long int.
1734  //   If none of the types in that list can represent all the values of its
1735  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1736  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1737  //   type.
1738  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1739      ToType->isIntegerType()) {
1740    // Determine whether the type we're converting from is signed or
1741    // unsigned.
1742    bool FromIsSigned = FromType->isSignedIntegerType();
1743    uint64_t FromSize = Context.getTypeSize(FromType);
1744
1745    // The types we'll try to promote to, in the appropriate
1746    // order. Try each of these types.
1747    QualType PromoteTypes[6] = {
1748      Context.IntTy, Context.UnsignedIntTy,
1749      Context.LongTy, Context.UnsignedLongTy ,
1750      Context.LongLongTy, Context.UnsignedLongLongTy
1751    };
1752    for (int Idx = 0; Idx < 6; ++Idx) {
1753      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1754      if (FromSize < ToSize ||
1755          (FromSize == ToSize &&
1756           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1757        // We found the type that we can promote to. If this is the
1758        // type we wanted, we have a promotion. Otherwise, no
1759        // promotion.
1760        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1761      }
1762    }
1763  }
1764
1765  // An rvalue for an integral bit-field (9.6) can be converted to an
1766  // rvalue of type int if int can represent all the values of the
1767  // bit-field; otherwise, it can be converted to unsigned int if
1768  // unsigned int can represent all the values of the bit-field. If
1769  // the bit-field is larger yet, no integral promotion applies to
1770  // it. If the bit-field has an enumerated type, it is treated as any
1771  // other value of that type for promotion purposes (C++ 4.5p3).
1772  // FIXME: We should delay checking of bit-fields until we actually perform the
1773  // conversion.
1774  using llvm::APSInt;
1775  if (From)
1776    if (FieldDecl *MemberDecl = From->getBitField()) {
1777      APSInt BitWidth;
1778      if (FromType->isIntegralType(Context) &&
1779          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1780        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1781        ToSize = Context.getTypeSize(ToType);
1782
1783        // Are we promoting to an int from a bitfield that fits in an int?
1784        if (BitWidth < ToSize ||
1785            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1786          return To->getKind() == BuiltinType::Int;
1787        }
1788
1789        // Are we promoting to an unsigned int from an unsigned bitfield
1790        // that fits into an unsigned int?
1791        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1792          return To->getKind() == BuiltinType::UInt;
1793        }
1794
1795        return false;
1796      }
1797    }
1798
1799  // An rvalue of type bool can be converted to an rvalue of type int,
1800  // with false becoming zero and true becoming one (C++ 4.5p4).
1801  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1802    return true;
1803  }
1804
1805  return false;
1806}
1807
1808/// IsFloatingPointPromotion - Determines whether the conversion from
1809/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1810/// returns true and sets PromotedType to the promoted type.
1811bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1812  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1813    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1814      /// An rvalue of type float can be converted to an rvalue of type
1815      /// double. (C++ 4.6p1).
1816      if (FromBuiltin->getKind() == BuiltinType::Float &&
1817          ToBuiltin->getKind() == BuiltinType::Double)
1818        return true;
1819
1820      // C99 6.3.1.5p1:
1821      //   When a float is promoted to double or long double, or a
1822      //   double is promoted to long double [...].
1823      if (!getLangOpts().CPlusPlus &&
1824          (FromBuiltin->getKind() == BuiltinType::Float ||
1825           FromBuiltin->getKind() == BuiltinType::Double) &&
1826          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1827        return true;
1828
1829      // Half can be promoted to float.
1830      if (FromBuiltin->getKind() == BuiltinType::Half &&
1831          ToBuiltin->getKind() == BuiltinType::Float)
1832        return true;
1833    }
1834
1835  return false;
1836}
1837
1838/// \brief Determine if a conversion is a complex promotion.
1839///
1840/// A complex promotion is defined as a complex -> complex conversion
1841/// where the conversion between the underlying real types is a
1842/// floating-point or integral promotion.
1843bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1844  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1845  if (!FromComplex)
1846    return false;
1847
1848  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1849  if (!ToComplex)
1850    return false;
1851
1852  return IsFloatingPointPromotion(FromComplex->getElementType(),
1853                                  ToComplex->getElementType()) ||
1854    IsIntegralPromotion(0, FromComplex->getElementType(),
1855                        ToComplex->getElementType());
1856}
1857
1858/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1859/// the pointer type FromPtr to a pointer to type ToPointee, with the
1860/// same type qualifiers as FromPtr has on its pointee type. ToType,
1861/// if non-empty, will be a pointer to ToType that may or may not have
1862/// the right set of qualifiers on its pointee.
1863///
1864static QualType
1865BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1866                                   QualType ToPointee, QualType ToType,
1867                                   ASTContext &Context,
1868                                   bool StripObjCLifetime = false) {
1869  assert((FromPtr->getTypeClass() == Type::Pointer ||
1870          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1871         "Invalid similarly-qualified pointer type");
1872
1873  /// Conversions to 'id' subsume cv-qualifier conversions.
1874  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1875    return ToType.getUnqualifiedType();
1876
1877  QualType CanonFromPointee
1878    = Context.getCanonicalType(FromPtr->getPointeeType());
1879  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1880  Qualifiers Quals = CanonFromPointee.getQualifiers();
1881
1882  if (StripObjCLifetime)
1883    Quals.removeObjCLifetime();
1884
1885  // Exact qualifier match -> return the pointer type we're converting to.
1886  if (CanonToPointee.getLocalQualifiers() == Quals) {
1887    // ToType is exactly what we need. Return it.
1888    if (!ToType.isNull())
1889      return ToType.getUnqualifiedType();
1890
1891    // Build a pointer to ToPointee. It has the right qualifiers
1892    // already.
1893    if (isa<ObjCObjectPointerType>(ToType))
1894      return Context.getObjCObjectPointerType(ToPointee);
1895    return Context.getPointerType(ToPointee);
1896  }
1897
1898  // Just build a canonical type that has the right qualifiers.
1899  QualType QualifiedCanonToPointee
1900    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1901
1902  if (isa<ObjCObjectPointerType>(ToType))
1903    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1904  return Context.getPointerType(QualifiedCanonToPointee);
1905}
1906
1907static bool isNullPointerConstantForConversion(Expr *Expr,
1908                                               bool InOverloadResolution,
1909                                               ASTContext &Context) {
1910  // Handle value-dependent integral null pointer constants correctly.
1911  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1912  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1913      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1914    return !InOverloadResolution;
1915
1916  return Expr->isNullPointerConstant(Context,
1917                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1918                                        : Expr::NPC_ValueDependentIsNull);
1919}
1920
1921/// IsPointerConversion - Determines whether the conversion of the
1922/// expression From, which has the (possibly adjusted) type FromType,
1923/// can be converted to the type ToType via a pointer conversion (C++
1924/// 4.10). If so, returns true and places the converted type (that
1925/// might differ from ToType in its cv-qualifiers at some level) into
1926/// ConvertedType.
1927///
1928/// This routine also supports conversions to and from block pointers
1929/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1930/// pointers to interfaces. FIXME: Once we've determined the
1931/// appropriate overloading rules for Objective-C, we may want to
1932/// split the Objective-C checks into a different routine; however,
1933/// GCC seems to consider all of these conversions to be pointer
1934/// conversions, so for now they live here. IncompatibleObjC will be
1935/// set if the conversion is an allowed Objective-C conversion that
1936/// should result in a warning.
1937bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1938                               bool InOverloadResolution,
1939                               QualType& ConvertedType,
1940                               bool &IncompatibleObjC) {
1941  IncompatibleObjC = false;
1942  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1943                              IncompatibleObjC))
1944    return true;
1945
1946  // Conversion from a null pointer constant to any Objective-C pointer type.
1947  if (ToType->isObjCObjectPointerType() &&
1948      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1949    ConvertedType = ToType;
1950    return true;
1951  }
1952
1953  // Blocks: Block pointers can be converted to void*.
1954  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1955      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1956    ConvertedType = ToType;
1957    return true;
1958  }
1959  // Blocks: A null pointer constant can be converted to a block
1960  // pointer type.
1961  if (ToType->isBlockPointerType() &&
1962      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1963    ConvertedType = ToType;
1964    return true;
1965  }
1966
1967  // If the left-hand-side is nullptr_t, the right side can be a null
1968  // pointer constant.
1969  if (ToType->isNullPtrType() &&
1970      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1971    ConvertedType = ToType;
1972    return true;
1973  }
1974
1975  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1976  if (!ToTypePtr)
1977    return false;
1978
1979  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1980  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1981    ConvertedType = ToType;
1982    return true;
1983  }
1984
1985  // Beyond this point, both types need to be pointers
1986  // , including objective-c pointers.
1987  QualType ToPointeeType = ToTypePtr->getPointeeType();
1988  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1989      !getLangOpts().ObjCAutoRefCount) {
1990    ConvertedType = BuildSimilarlyQualifiedPointerType(
1991                                      FromType->getAs<ObjCObjectPointerType>(),
1992                                                       ToPointeeType,
1993                                                       ToType, Context);
1994    return true;
1995  }
1996  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1997  if (!FromTypePtr)
1998    return false;
1999
2000  QualType FromPointeeType = FromTypePtr->getPointeeType();
2001
2002  // If the unqualified pointee types are the same, this can't be a
2003  // pointer conversion, so don't do all of the work below.
2004  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2005    return false;
2006
2007  // An rvalue of type "pointer to cv T," where T is an object type,
2008  // can be converted to an rvalue of type "pointer to cv void" (C++
2009  // 4.10p2).
2010  if (FromPointeeType->isIncompleteOrObjectType() &&
2011      ToPointeeType->isVoidType()) {
2012    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2013                                                       ToPointeeType,
2014                                                       ToType, Context,
2015                                                   /*StripObjCLifetime=*/true);
2016    return true;
2017  }
2018
2019  // MSVC allows implicit function to void* type conversion.
2020  if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2021      ToPointeeType->isVoidType()) {
2022    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2023                                                       ToPointeeType,
2024                                                       ToType, Context);
2025    return true;
2026  }
2027
2028  // When we're overloading in C, we allow a special kind of pointer
2029  // conversion for compatible-but-not-identical pointee types.
2030  if (!getLangOpts().CPlusPlus &&
2031      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2032    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2033                                                       ToPointeeType,
2034                                                       ToType, Context);
2035    return true;
2036  }
2037
2038  // C++ [conv.ptr]p3:
2039  //
2040  //   An rvalue of type "pointer to cv D," where D is a class type,
2041  //   can be converted to an rvalue of type "pointer to cv B," where
2042  //   B is a base class (clause 10) of D. If B is an inaccessible
2043  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2044  //   necessitates this conversion is ill-formed. The result of the
2045  //   conversion is a pointer to the base class sub-object of the
2046  //   derived class object. The null pointer value is converted to
2047  //   the null pointer value of the destination type.
2048  //
2049  // Note that we do not check for ambiguity or inaccessibility
2050  // here. That is handled by CheckPointerConversion.
2051  if (getLangOpts().CPlusPlus &&
2052      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2053      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2054      !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2055      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2056    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2057                                                       ToPointeeType,
2058                                                       ToType, Context);
2059    return true;
2060  }
2061
2062  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2063      Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2064    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2065                                                       ToPointeeType,
2066                                                       ToType, Context);
2067    return true;
2068  }
2069
2070  return false;
2071}
2072
2073/// \brief Adopt the given qualifiers for the given type.
2074static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2075  Qualifiers TQs = T.getQualifiers();
2076
2077  // Check whether qualifiers already match.
2078  if (TQs == Qs)
2079    return T;
2080
2081  if (Qs.compatiblyIncludes(TQs))
2082    return Context.getQualifiedType(T, Qs);
2083
2084  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2085}
2086
2087/// isObjCPointerConversion - Determines whether this is an
2088/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2089/// with the same arguments and return values.
2090bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2091                                   QualType& ConvertedType,
2092                                   bool &IncompatibleObjC) {
2093  if (!getLangOpts().ObjC1)
2094    return false;
2095
2096  // The set of qualifiers on the type we're converting from.
2097  Qualifiers FromQualifiers = FromType.getQualifiers();
2098
2099  // First, we handle all conversions on ObjC object pointer types.
2100  const ObjCObjectPointerType* ToObjCPtr =
2101    ToType->getAs<ObjCObjectPointerType>();
2102  const ObjCObjectPointerType *FromObjCPtr =
2103    FromType->getAs<ObjCObjectPointerType>();
2104
2105  if (ToObjCPtr && FromObjCPtr) {
2106    // If the pointee types are the same (ignoring qualifications),
2107    // then this is not a pointer conversion.
2108    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2109                                       FromObjCPtr->getPointeeType()))
2110      return false;
2111
2112    // Check for compatible
2113    // Objective C++: We're able to convert between "id" or "Class" and a
2114    // pointer to any interface (in both directions).
2115    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2116      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2117      return true;
2118    }
2119    // Conversions with Objective-C's id<...>.
2120    if ((FromObjCPtr->isObjCQualifiedIdType() ||
2121         ToObjCPtr->isObjCQualifiedIdType()) &&
2122        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2123                                                  /*compare=*/false)) {
2124      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2125      return true;
2126    }
2127    // Objective C++: We're able to convert from a pointer to an
2128    // interface to a pointer to a different interface.
2129    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2130      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2131      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2132      if (getLangOpts().CPlusPlus && LHS && RHS &&
2133          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2134                                                FromObjCPtr->getPointeeType()))
2135        return false;
2136      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2137                                                   ToObjCPtr->getPointeeType(),
2138                                                         ToType, Context);
2139      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2140      return true;
2141    }
2142
2143    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2144      // Okay: this is some kind of implicit downcast of Objective-C
2145      // interfaces, which is permitted. However, we're going to
2146      // complain about it.
2147      IncompatibleObjC = true;
2148      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2149                                                   ToObjCPtr->getPointeeType(),
2150                                                         ToType, Context);
2151      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2152      return true;
2153    }
2154  }
2155  // Beyond this point, both types need to be C pointers or block pointers.
2156  QualType ToPointeeType;
2157  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2158    ToPointeeType = ToCPtr->getPointeeType();
2159  else if (const BlockPointerType *ToBlockPtr =
2160            ToType->getAs<BlockPointerType>()) {
2161    // Objective C++: We're able to convert from a pointer to any object
2162    // to a block pointer type.
2163    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2164      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2165      return true;
2166    }
2167    ToPointeeType = ToBlockPtr->getPointeeType();
2168  }
2169  else if (FromType->getAs<BlockPointerType>() &&
2170           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2171    // Objective C++: We're able to convert from a block pointer type to a
2172    // pointer to any object.
2173    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2174    return true;
2175  }
2176  else
2177    return false;
2178
2179  QualType FromPointeeType;
2180  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2181    FromPointeeType = FromCPtr->getPointeeType();
2182  else if (const BlockPointerType *FromBlockPtr =
2183           FromType->getAs<BlockPointerType>())
2184    FromPointeeType = FromBlockPtr->getPointeeType();
2185  else
2186    return false;
2187
2188  // If we have pointers to pointers, recursively check whether this
2189  // is an Objective-C conversion.
2190  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2191      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2192                              IncompatibleObjC)) {
2193    // We always complain about this conversion.
2194    IncompatibleObjC = true;
2195    ConvertedType = Context.getPointerType(ConvertedType);
2196    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2197    return true;
2198  }
2199  // Allow conversion of pointee being objective-c pointer to another one;
2200  // as in I* to id.
2201  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2202      ToPointeeType->getAs<ObjCObjectPointerType>() &&
2203      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2204                              IncompatibleObjC)) {
2205
2206    ConvertedType = Context.getPointerType(ConvertedType);
2207    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2208    return true;
2209  }
2210
2211  // If we have pointers to functions or blocks, check whether the only
2212  // differences in the argument and result types are in Objective-C
2213  // pointer conversions. If so, we permit the conversion (but
2214  // complain about it).
2215  const FunctionProtoType *FromFunctionType
2216    = FromPointeeType->getAs<FunctionProtoType>();
2217  const FunctionProtoType *ToFunctionType
2218    = ToPointeeType->getAs<FunctionProtoType>();
2219  if (FromFunctionType && ToFunctionType) {
2220    // If the function types are exactly the same, this isn't an
2221    // Objective-C pointer conversion.
2222    if (Context.getCanonicalType(FromPointeeType)
2223          == Context.getCanonicalType(ToPointeeType))
2224      return false;
2225
2226    // Perform the quick checks that will tell us whether these
2227    // function types are obviously different.
2228    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2229        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2230        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2231      return false;
2232
2233    bool HasObjCConversion = false;
2234    if (Context.getCanonicalType(FromFunctionType->getResultType())
2235          == Context.getCanonicalType(ToFunctionType->getResultType())) {
2236      // Okay, the types match exactly. Nothing to do.
2237    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2238                                       ToFunctionType->getResultType(),
2239                                       ConvertedType, IncompatibleObjC)) {
2240      // Okay, we have an Objective-C pointer conversion.
2241      HasObjCConversion = true;
2242    } else {
2243      // Function types are too different. Abort.
2244      return false;
2245    }
2246
2247    // Check argument types.
2248    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2249         ArgIdx != NumArgs; ++ArgIdx) {
2250      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2251      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2252      if (Context.getCanonicalType(FromArgType)
2253            == Context.getCanonicalType(ToArgType)) {
2254        // Okay, the types match exactly. Nothing to do.
2255      } else if (isObjCPointerConversion(FromArgType, ToArgType,
2256                                         ConvertedType, IncompatibleObjC)) {
2257        // Okay, we have an Objective-C pointer conversion.
2258        HasObjCConversion = true;
2259      } else {
2260        // Argument types are too different. Abort.
2261        return false;
2262      }
2263    }
2264
2265    if (HasObjCConversion) {
2266      // We had an Objective-C conversion. Allow this pointer
2267      // conversion, but complain about it.
2268      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2269      IncompatibleObjC = true;
2270      return true;
2271    }
2272  }
2273
2274  return false;
2275}
2276
2277/// \brief Determine whether this is an Objective-C writeback conversion,
2278/// used for parameter passing when performing automatic reference counting.
2279///
2280/// \param FromType The type we're converting form.
2281///
2282/// \param ToType The type we're converting to.
2283///
2284/// \param ConvertedType The type that will be produced after applying
2285/// this conversion.
2286bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2287                                     QualType &ConvertedType) {
2288  if (!getLangOpts().ObjCAutoRefCount ||
2289      Context.hasSameUnqualifiedType(FromType, ToType))
2290    return false;
2291
2292  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2293  QualType ToPointee;
2294  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2295    ToPointee = ToPointer->getPointeeType();
2296  else
2297    return false;
2298
2299  Qualifiers ToQuals = ToPointee.getQualifiers();
2300  if (!ToPointee->isObjCLifetimeType() ||
2301      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2302      !ToQuals.withoutObjCLifetime().empty())
2303    return false;
2304
2305  // Argument must be a pointer to __strong to __weak.
2306  QualType FromPointee;
2307  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2308    FromPointee = FromPointer->getPointeeType();
2309  else
2310    return false;
2311
2312  Qualifiers FromQuals = FromPointee.getQualifiers();
2313  if (!FromPointee->isObjCLifetimeType() ||
2314      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2315       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2316    return false;
2317
2318  // Make sure that we have compatible qualifiers.
2319  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2320  if (!ToQuals.compatiblyIncludes(FromQuals))
2321    return false;
2322
2323  // Remove qualifiers from the pointee type we're converting from; they
2324  // aren't used in the compatibility check belong, and we'll be adding back
2325  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2326  FromPointee = FromPointee.getUnqualifiedType();
2327
2328  // The unqualified form of the pointee types must be compatible.
2329  ToPointee = ToPointee.getUnqualifiedType();
2330  bool IncompatibleObjC;
2331  if (Context.typesAreCompatible(FromPointee, ToPointee))
2332    FromPointee = ToPointee;
2333  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2334                                    IncompatibleObjC))
2335    return false;
2336
2337  /// \brief Construct the type we're converting to, which is a pointer to
2338  /// __autoreleasing pointee.
2339  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2340  ConvertedType = Context.getPointerType(FromPointee);
2341  return true;
2342}
2343
2344bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2345                                    QualType& ConvertedType) {
2346  QualType ToPointeeType;
2347  if (const BlockPointerType *ToBlockPtr =
2348        ToType->getAs<BlockPointerType>())
2349    ToPointeeType = ToBlockPtr->getPointeeType();
2350  else
2351    return false;
2352
2353  QualType FromPointeeType;
2354  if (const BlockPointerType *FromBlockPtr =
2355      FromType->getAs<BlockPointerType>())
2356    FromPointeeType = FromBlockPtr->getPointeeType();
2357  else
2358    return false;
2359  // We have pointer to blocks, check whether the only
2360  // differences in the argument and result types are in Objective-C
2361  // pointer conversions. If so, we permit the conversion.
2362
2363  const FunctionProtoType *FromFunctionType
2364    = FromPointeeType->getAs<FunctionProtoType>();
2365  const FunctionProtoType *ToFunctionType
2366    = ToPointeeType->getAs<FunctionProtoType>();
2367
2368  if (!FromFunctionType || !ToFunctionType)
2369    return false;
2370
2371  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2372    return true;
2373
2374  // Perform the quick checks that will tell us whether these
2375  // function types are obviously different.
2376  if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2377      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2378    return false;
2379
2380  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2381  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2382  if (FromEInfo != ToEInfo)
2383    return false;
2384
2385  bool IncompatibleObjC = false;
2386  if (Context.hasSameType(FromFunctionType->getResultType(),
2387                          ToFunctionType->getResultType())) {
2388    // Okay, the types match exactly. Nothing to do.
2389  } else {
2390    QualType RHS = FromFunctionType->getResultType();
2391    QualType LHS = ToFunctionType->getResultType();
2392    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2393        !RHS.hasQualifiers() && LHS.hasQualifiers())
2394       LHS = LHS.getUnqualifiedType();
2395
2396     if (Context.hasSameType(RHS,LHS)) {
2397       // OK exact match.
2398     } else if (isObjCPointerConversion(RHS, LHS,
2399                                        ConvertedType, IncompatibleObjC)) {
2400     if (IncompatibleObjC)
2401       return false;
2402     // Okay, we have an Objective-C pointer conversion.
2403     }
2404     else
2405       return false;
2406   }
2407
2408   // Check argument types.
2409   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2410        ArgIdx != NumArgs; ++ArgIdx) {
2411     IncompatibleObjC = false;
2412     QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2413     QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2414     if (Context.hasSameType(FromArgType, ToArgType)) {
2415       // Okay, the types match exactly. Nothing to do.
2416     } else if (isObjCPointerConversion(ToArgType, FromArgType,
2417                                        ConvertedType, IncompatibleObjC)) {
2418       if (IncompatibleObjC)
2419         return false;
2420       // Okay, we have an Objective-C pointer conversion.
2421     } else
2422       // Argument types are too different. Abort.
2423       return false;
2424   }
2425   if (LangOpts.ObjCAutoRefCount &&
2426       !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2427                                                    ToFunctionType))
2428     return false;
2429
2430   ConvertedType = ToType;
2431   return true;
2432}
2433
2434enum {
2435  ft_default,
2436  ft_different_class,
2437  ft_parameter_arity,
2438  ft_parameter_mismatch,
2439  ft_return_type,
2440  ft_qualifer_mismatch
2441};
2442
2443/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2444/// function types.  Catches different number of parameter, mismatch in
2445/// parameter types, and different return types.
2446void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2447                                      QualType FromType, QualType ToType) {
2448  // If either type is not valid, include no extra info.
2449  if (FromType.isNull() || ToType.isNull()) {
2450    PDiag << ft_default;
2451    return;
2452  }
2453
2454  // Get the function type from the pointers.
2455  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2456    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2457                            *ToMember = ToType->getAs<MemberPointerType>();
2458    if (FromMember->getClass() != ToMember->getClass()) {
2459      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2460            << QualType(FromMember->getClass(), 0);
2461      return;
2462    }
2463    FromType = FromMember->getPointeeType();
2464    ToType = ToMember->getPointeeType();
2465  }
2466
2467  if (FromType->isPointerType())
2468    FromType = FromType->getPointeeType();
2469  if (ToType->isPointerType())
2470    ToType = ToType->getPointeeType();
2471
2472  // Remove references.
2473  FromType = FromType.getNonReferenceType();
2474  ToType = ToType.getNonReferenceType();
2475
2476  // Don't print extra info for non-specialized template functions.
2477  if (FromType->isInstantiationDependentType() &&
2478      !FromType->getAs<TemplateSpecializationType>()) {
2479    PDiag << ft_default;
2480    return;
2481  }
2482
2483  // No extra info for same types.
2484  if (Context.hasSameType(FromType, ToType)) {
2485    PDiag << ft_default;
2486    return;
2487  }
2488
2489  const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2490                          *ToFunction = ToType->getAs<FunctionProtoType>();
2491
2492  // Both types need to be function types.
2493  if (!FromFunction || !ToFunction) {
2494    PDiag << ft_default;
2495    return;
2496  }
2497
2498  if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2499    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2500          << FromFunction->getNumArgs();
2501    return;
2502  }
2503
2504  // Handle different parameter types.
2505  unsigned ArgPos;
2506  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2507    PDiag << ft_parameter_mismatch << ArgPos + 1
2508          << ToFunction->getArgType(ArgPos)
2509          << FromFunction->getArgType(ArgPos);
2510    return;
2511  }
2512
2513  // Handle different return type.
2514  if (!Context.hasSameType(FromFunction->getResultType(),
2515                           ToFunction->getResultType())) {
2516    PDiag << ft_return_type << ToFunction->getResultType()
2517          << FromFunction->getResultType();
2518    return;
2519  }
2520
2521  unsigned FromQuals = FromFunction->getTypeQuals(),
2522           ToQuals = ToFunction->getTypeQuals();
2523  if (FromQuals != ToQuals) {
2524    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2525    return;
2526  }
2527
2528  // Unable to find a difference, so add no extra info.
2529  PDiag << ft_default;
2530}
2531
2532/// FunctionArgTypesAreEqual - This routine checks two function proto types
2533/// for equality of their argument types. Caller has already checked that
2534/// they have same number of arguments. This routine assumes that Objective-C
2535/// pointer types which only differ in their protocol qualifiers are equal.
2536/// If the parameters are different, ArgPos will have the parameter index
2537/// of the first different parameter.
2538bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2539                                    const FunctionProtoType *NewType,
2540                                    unsigned *ArgPos) {
2541  if (!getLangOpts().ObjC1) {
2542    for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2543         N = NewType->arg_type_begin(),
2544         E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2545      if (!Context.hasSameType(*O, *N)) {
2546        if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2547        return false;
2548      }
2549    }
2550    return true;
2551  }
2552
2553  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2554       N = NewType->arg_type_begin(),
2555       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2556    QualType ToType = (*O);
2557    QualType FromType = (*N);
2558    if (!Context.hasSameType(ToType, FromType)) {
2559      if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2560        if (const PointerType *PTFr = FromType->getAs<PointerType>())
2561          if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2562               PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2563              (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2564               PTFr->getPointeeType()->isObjCQualifiedClassType()))
2565            continue;
2566      }
2567      else if (const ObjCObjectPointerType *PTTo =
2568                 ToType->getAs<ObjCObjectPointerType>()) {
2569        if (const ObjCObjectPointerType *PTFr =
2570              FromType->getAs<ObjCObjectPointerType>())
2571          if (Context.hasSameUnqualifiedType(
2572                PTTo->getObjectType()->getBaseType(),
2573                PTFr->getObjectType()->getBaseType()))
2574            continue;
2575      }
2576      if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2577      return false;
2578    }
2579  }
2580  return true;
2581}
2582
2583/// CheckPointerConversion - Check the pointer conversion from the
2584/// expression From to the type ToType. This routine checks for
2585/// ambiguous or inaccessible derived-to-base pointer
2586/// conversions for which IsPointerConversion has already returned
2587/// true. It returns true and produces a diagnostic if there was an
2588/// error, or returns false otherwise.
2589bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2590                                  CastKind &Kind,
2591                                  CXXCastPath& BasePath,
2592                                  bool IgnoreBaseAccess) {
2593  QualType FromType = From->getType();
2594  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2595
2596  Kind = CK_BitCast;
2597
2598  if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2599      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2600      Expr::NPCK_ZeroExpression) {
2601    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2602      DiagRuntimeBehavior(From->getExprLoc(), From,
2603                          PDiag(diag::warn_impcast_bool_to_null_pointer)
2604                            << ToType << From->getSourceRange());
2605    else if (!isUnevaluatedContext())
2606      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2607        << ToType << From->getSourceRange();
2608  }
2609  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2610    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2611      QualType FromPointeeType = FromPtrType->getPointeeType(),
2612               ToPointeeType   = ToPtrType->getPointeeType();
2613
2614      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2615          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2616        // We must have a derived-to-base conversion. Check an
2617        // ambiguous or inaccessible conversion.
2618        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2619                                         From->getExprLoc(),
2620                                         From->getSourceRange(), &BasePath,
2621                                         IgnoreBaseAccess))
2622          return true;
2623
2624        // The conversion was successful.
2625        Kind = CK_DerivedToBase;
2626      }
2627    }
2628  } else if (const ObjCObjectPointerType *ToPtrType =
2629               ToType->getAs<ObjCObjectPointerType>()) {
2630    if (const ObjCObjectPointerType *FromPtrType =
2631          FromType->getAs<ObjCObjectPointerType>()) {
2632      // Objective-C++ conversions are always okay.
2633      // FIXME: We should have a different class of conversions for the
2634      // Objective-C++ implicit conversions.
2635      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2636        return false;
2637    } else if (FromType->isBlockPointerType()) {
2638      Kind = CK_BlockPointerToObjCPointerCast;
2639    } else {
2640      Kind = CK_CPointerToObjCPointerCast;
2641    }
2642  } else if (ToType->isBlockPointerType()) {
2643    if (!FromType->isBlockPointerType())
2644      Kind = CK_AnyPointerToBlockPointerCast;
2645  }
2646
2647  // We shouldn't fall into this case unless it's valid for other
2648  // reasons.
2649  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2650    Kind = CK_NullToPointer;
2651
2652  return false;
2653}
2654
2655/// IsMemberPointerConversion - Determines whether the conversion of the
2656/// expression From, which has the (possibly adjusted) type FromType, can be
2657/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2658/// If so, returns true and places the converted type (that might differ from
2659/// ToType in its cv-qualifiers at some level) into ConvertedType.
2660bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2661                                     QualType ToType,
2662                                     bool InOverloadResolution,
2663                                     QualType &ConvertedType) {
2664  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2665  if (!ToTypePtr)
2666    return false;
2667
2668  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2669  if (From->isNullPointerConstant(Context,
2670                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2671                                        : Expr::NPC_ValueDependentIsNull)) {
2672    ConvertedType = ToType;
2673    return true;
2674  }
2675
2676  // Otherwise, both types have to be member pointers.
2677  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2678  if (!FromTypePtr)
2679    return false;
2680
2681  // A pointer to member of B can be converted to a pointer to member of D,
2682  // where D is derived from B (C++ 4.11p2).
2683  QualType FromClass(FromTypePtr->getClass(), 0);
2684  QualType ToClass(ToTypePtr->getClass(), 0);
2685
2686  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2687      !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2688      IsDerivedFrom(ToClass, FromClass)) {
2689    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2690                                                 ToClass.getTypePtr());
2691    return true;
2692  }
2693
2694  return false;
2695}
2696
2697/// CheckMemberPointerConversion - Check the member pointer conversion from the
2698/// expression From to the type ToType. This routine checks for ambiguous or
2699/// virtual or inaccessible base-to-derived member pointer conversions
2700/// for which IsMemberPointerConversion has already returned true. It returns
2701/// true and produces a diagnostic if there was an error, or returns false
2702/// otherwise.
2703bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2704                                        CastKind &Kind,
2705                                        CXXCastPath &BasePath,
2706                                        bool IgnoreBaseAccess) {
2707  QualType FromType = From->getType();
2708  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2709  if (!FromPtrType) {
2710    // This must be a null pointer to member pointer conversion
2711    assert(From->isNullPointerConstant(Context,
2712                                       Expr::NPC_ValueDependentIsNull) &&
2713           "Expr must be null pointer constant!");
2714    Kind = CK_NullToMemberPointer;
2715    return false;
2716  }
2717
2718  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2719  assert(ToPtrType && "No member pointer cast has a target type "
2720                      "that is not a member pointer.");
2721
2722  QualType FromClass = QualType(FromPtrType->getClass(), 0);
2723  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2724
2725  // FIXME: What about dependent types?
2726  assert(FromClass->isRecordType() && "Pointer into non-class.");
2727  assert(ToClass->isRecordType() && "Pointer into non-class.");
2728
2729  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2730                     /*DetectVirtual=*/true);
2731  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2732  assert(DerivationOkay &&
2733         "Should not have been called if derivation isn't OK.");
2734  (void)DerivationOkay;
2735
2736  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2737                                  getUnqualifiedType())) {
2738    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2739    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2740      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2741    return true;
2742  }
2743
2744  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2745    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2746      << FromClass << ToClass << QualType(VBase, 0)
2747      << From->getSourceRange();
2748    return true;
2749  }
2750
2751  if (!IgnoreBaseAccess)
2752    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2753                         Paths.front(),
2754                         diag::err_downcast_from_inaccessible_base);
2755
2756  // Must be a base to derived member conversion.
2757  BuildBasePathArray(Paths, BasePath);
2758  Kind = CK_BaseToDerivedMemberPointer;
2759  return false;
2760}
2761
2762/// IsQualificationConversion - Determines whether the conversion from
2763/// an rvalue of type FromType to ToType is a qualification conversion
2764/// (C++ 4.4).
2765///
2766/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2767/// when the qualification conversion involves a change in the Objective-C
2768/// object lifetime.
2769bool
2770Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2771                                bool CStyle, bool &ObjCLifetimeConversion) {
2772  FromType = Context.getCanonicalType(FromType);
2773  ToType = Context.getCanonicalType(ToType);
2774  ObjCLifetimeConversion = false;
2775
2776  // If FromType and ToType are the same type, this is not a
2777  // qualification conversion.
2778  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2779    return false;
2780
2781  // (C++ 4.4p4):
2782  //   A conversion can add cv-qualifiers at levels other than the first
2783  //   in multi-level pointers, subject to the following rules: [...]
2784  bool PreviousToQualsIncludeConst = true;
2785  bool UnwrappedAnyPointer = false;
2786  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2787    // Within each iteration of the loop, we check the qualifiers to
2788    // determine if this still looks like a qualification
2789    // conversion. Then, if all is well, we unwrap one more level of
2790    // pointers or pointers-to-members and do it all again
2791    // until there are no more pointers or pointers-to-members left to
2792    // unwrap.
2793    UnwrappedAnyPointer = true;
2794
2795    Qualifiers FromQuals = FromType.getQualifiers();
2796    Qualifiers ToQuals = ToType.getQualifiers();
2797
2798    // Objective-C ARC:
2799    //   Check Objective-C lifetime conversions.
2800    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2801        UnwrappedAnyPointer) {
2802      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2803        ObjCLifetimeConversion = true;
2804        FromQuals.removeObjCLifetime();
2805        ToQuals.removeObjCLifetime();
2806      } else {
2807        // Qualification conversions cannot cast between different
2808        // Objective-C lifetime qualifiers.
2809        return false;
2810      }
2811    }
2812
2813    // Allow addition/removal of GC attributes but not changing GC attributes.
2814    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2815        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2816      FromQuals.removeObjCGCAttr();
2817      ToQuals.removeObjCGCAttr();
2818    }
2819
2820    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2821    //      2,j, and similarly for volatile.
2822    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2823      return false;
2824
2825    //   -- if the cv 1,j and cv 2,j are different, then const is in
2826    //      every cv for 0 < k < j.
2827    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2828        && !PreviousToQualsIncludeConst)
2829      return false;
2830
2831    // Keep track of whether all prior cv-qualifiers in the "to" type
2832    // include const.
2833    PreviousToQualsIncludeConst
2834      = PreviousToQualsIncludeConst && ToQuals.hasConst();
2835  }
2836
2837  // We are left with FromType and ToType being the pointee types
2838  // after unwrapping the original FromType and ToType the same number
2839  // of types. If we unwrapped any pointers, and if FromType and
2840  // ToType have the same unqualified type (since we checked
2841  // qualifiers above), then this is a qualification conversion.
2842  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2843}
2844
2845/// \brief - Determine whether this is a conversion from a scalar type to an
2846/// atomic type.
2847///
2848/// If successful, updates \c SCS's second and third steps in the conversion
2849/// sequence to finish the conversion.
2850static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2851                                bool InOverloadResolution,
2852                                StandardConversionSequence &SCS,
2853                                bool CStyle) {
2854  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2855  if (!ToAtomic)
2856    return false;
2857
2858  StandardConversionSequence InnerSCS;
2859  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2860                            InOverloadResolution, InnerSCS,
2861                            CStyle, /*AllowObjCWritebackConversion=*/false))
2862    return false;
2863
2864  SCS.Second = InnerSCS.Second;
2865  SCS.setToType(1, InnerSCS.getToType(1));
2866  SCS.Third = InnerSCS.Third;
2867  SCS.QualificationIncludesObjCLifetime
2868    = InnerSCS.QualificationIncludesObjCLifetime;
2869  SCS.setToType(2, InnerSCS.getToType(2));
2870  return true;
2871}
2872
2873static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2874                                              CXXConstructorDecl *Constructor,
2875                                              QualType Type) {
2876  const FunctionProtoType *CtorType =
2877      Constructor->getType()->getAs<FunctionProtoType>();
2878  if (CtorType->getNumArgs() > 0) {
2879    QualType FirstArg = CtorType->getArgType(0);
2880    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2881      return true;
2882  }
2883  return false;
2884}
2885
2886static OverloadingResult
2887IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2888                                       CXXRecordDecl *To,
2889                                       UserDefinedConversionSequence &User,
2890                                       OverloadCandidateSet &CandidateSet,
2891                                       bool AllowExplicit) {
2892  DeclContext::lookup_result R = S.LookupConstructors(To);
2893  for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2894       Con != ConEnd; ++Con) {
2895    NamedDecl *D = *Con;
2896    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2897
2898    // Find the constructor (which may be a template).
2899    CXXConstructorDecl *Constructor = 0;
2900    FunctionTemplateDecl *ConstructorTmpl
2901      = dyn_cast<FunctionTemplateDecl>(D);
2902    if (ConstructorTmpl)
2903      Constructor
2904        = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2905    else
2906      Constructor = cast<CXXConstructorDecl>(D);
2907
2908    bool Usable = !Constructor->isInvalidDecl() &&
2909                  S.isInitListConstructor(Constructor) &&
2910                  (AllowExplicit || !Constructor->isExplicit());
2911    if (Usable) {
2912      // If the first argument is (a reference to) the target type,
2913      // suppress conversions.
2914      bool SuppressUserConversions =
2915          isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2916      if (ConstructorTmpl)
2917        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2918                                       /*ExplicitArgs*/ 0,
2919                                       From, CandidateSet,
2920                                       SuppressUserConversions);
2921      else
2922        S.AddOverloadCandidate(Constructor, FoundDecl,
2923                               From, CandidateSet,
2924                               SuppressUserConversions);
2925    }
2926  }
2927
2928  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2929
2930  OverloadCandidateSet::iterator Best;
2931  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2932  case OR_Success: {
2933    // Record the standard conversion we used and the conversion function.
2934    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2935    QualType ThisType = Constructor->getThisType(S.Context);
2936    // Initializer lists don't have conversions as such.
2937    User.Before.setAsIdentityConversion();
2938    User.HadMultipleCandidates = HadMultipleCandidates;
2939    User.ConversionFunction = Constructor;
2940    User.FoundConversionFunction = Best->FoundDecl;
2941    User.After.setAsIdentityConversion();
2942    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2943    User.After.setAllToTypes(ToType);
2944    return OR_Success;
2945  }
2946
2947  case OR_No_Viable_Function:
2948    return OR_No_Viable_Function;
2949  case OR_Deleted:
2950    return OR_Deleted;
2951  case OR_Ambiguous:
2952    return OR_Ambiguous;
2953  }
2954
2955  llvm_unreachable("Invalid OverloadResult!");
2956}
2957
2958/// Determines whether there is a user-defined conversion sequence
2959/// (C++ [over.ics.user]) that converts expression From to the type
2960/// ToType. If such a conversion exists, User will contain the
2961/// user-defined conversion sequence that performs such a conversion
2962/// and this routine will return true. Otherwise, this routine returns
2963/// false and User is unspecified.
2964///
2965/// \param AllowExplicit  true if the conversion should consider C++0x
2966/// "explicit" conversion functions as well as non-explicit conversion
2967/// functions (C++0x [class.conv.fct]p2).
2968static OverloadingResult
2969IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2970                        UserDefinedConversionSequence &User,
2971                        OverloadCandidateSet &CandidateSet,
2972                        bool AllowExplicit) {
2973  // Whether we will only visit constructors.
2974  bool ConstructorsOnly = false;
2975
2976  // If the type we are conversion to is a class type, enumerate its
2977  // constructors.
2978  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2979    // C++ [over.match.ctor]p1:
2980    //   When objects of class type are direct-initialized (8.5), or
2981    //   copy-initialized from an expression of the same or a
2982    //   derived class type (8.5), overload resolution selects the
2983    //   constructor. [...] For copy-initialization, the candidate
2984    //   functions are all the converting constructors (12.3.1) of
2985    //   that class. The argument list is the expression-list within
2986    //   the parentheses of the initializer.
2987    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2988        (From->getType()->getAs<RecordType>() &&
2989         S.IsDerivedFrom(From->getType(), ToType)))
2990      ConstructorsOnly = true;
2991
2992    S.RequireCompleteType(From->getExprLoc(), ToType, 0);
2993    // RequireCompleteType may have returned true due to some invalid decl
2994    // during template instantiation, but ToType may be complete enough now
2995    // to try to recover.
2996    if (ToType->isIncompleteType()) {
2997      // We're not going to find any constructors.
2998    } else if (CXXRecordDecl *ToRecordDecl
2999                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3000
3001      Expr **Args = &From;
3002      unsigned NumArgs = 1;
3003      bool ListInitializing = false;
3004      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3005        // But first, see if there is an init-list-contructor that will work.
3006        OverloadingResult Result = IsInitializerListConstructorConversion(
3007            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3008        if (Result != OR_No_Viable_Function)
3009          return Result;
3010        // Never mind.
3011        CandidateSet.clear();
3012
3013        // If we're list-initializing, we pass the individual elements as
3014        // arguments, not the entire list.
3015        Args = InitList->getInits();
3016        NumArgs = InitList->getNumInits();
3017        ListInitializing = true;
3018      }
3019
3020      DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3021      for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3022           Con != ConEnd; ++Con) {
3023        NamedDecl *D = *Con;
3024        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3025
3026        // Find the constructor (which may be a template).
3027        CXXConstructorDecl *Constructor = 0;
3028        FunctionTemplateDecl *ConstructorTmpl
3029          = dyn_cast<FunctionTemplateDecl>(D);
3030        if (ConstructorTmpl)
3031          Constructor
3032            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3033        else
3034          Constructor = cast<CXXConstructorDecl>(D);
3035
3036        bool Usable = !Constructor->isInvalidDecl();
3037        if (ListInitializing)
3038          Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3039        else
3040          Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3041        if (Usable) {
3042          bool SuppressUserConversions = !ConstructorsOnly;
3043          if (SuppressUserConversions && ListInitializing) {
3044            SuppressUserConversions = false;
3045            if (NumArgs == 1) {
3046              // If the first argument is (a reference to) the target type,
3047              // suppress conversions.
3048              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3049                                                S.Context, Constructor, ToType);
3050            }
3051          }
3052          if (ConstructorTmpl)
3053            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3054                                           /*ExplicitArgs*/ 0,
3055                                           llvm::makeArrayRef(Args, NumArgs),
3056                                           CandidateSet, SuppressUserConversions);
3057          else
3058            // Allow one user-defined conversion when user specifies a
3059            // From->ToType conversion via an static cast (c-style, etc).
3060            S.AddOverloadCandidate(Constructor, FoundDecl,
3061                                   llvm::makeArrayRef(Args, NumArgs),
3062                                   CandidateSet, SuppressUserConversions);
3063        }
3064      }
3065    }
3066  }
3067
3068  // Enumerate conversion functions, if we're allowed to.
3069  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3070  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3071    // No conversion functions from incomplete types.
3072  } else if (const RecordType *FromRecordType
3073                                   = From->getType()->getAs<RecordType>()) {
3074    if (CXXRecordDecl *FromRecordDecl
3075         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3076      // Add all of the conversion functions as candidates.
3077      std::pair<CXXRecordDecl::conversion_iterator,
3078                CXXRecordDecl::conversion_iterator>
3079        Conversions = FromRecordDecl->getVisibleConversionFunctions();
3080      for (CXXRecordDecl::conversion_iterator
3081             I = Conversions.first, E = Conversions.second; I != E; ++I) {
3082        DeclAccessPair FoundDecl = I.getPair();
3083        NamedDecl *D = FoundDecl.getDecl();
3084        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3085        if (isa<UsingShadowDecl>(D))
3086          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3087
3088        CXXConversionDecl *Conv;
3089        FunctionTemplateDecl *ConvTemplate;
3090        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3091          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3092        else
3093          Conv = cast<CXXConversionDecl>(D);
3094
3095        if (AllowExplicit || !Conv->isExplicit()) {
3096          if (ConvTemplate)
3097            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3098                                             ActingContext, From, ToType,
3099                                             CandidateSet);
3100          else
3101            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3102                                     From, ToType, CandidateSet);
3103        }
3104      }
3105    }
3106  }
3107
3108  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3109
3110  OverloadCandidateSet::iterator Best;
3111  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3112  case OR_Success:
3113    // Record the standard conversion we used and the conversion function.
3114    if (CXXConstructorDecl *Constructor
3115          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3116      // C++ [over.ics.user]p1:
3117      //   If the user-defined conversion is specified by a
3118      //   constructor (12.3.1), the initial standard conversion
3119      //   sequence converts the source type to the type required by
3120      //   the argument of the constructor.
3121      //
3122      QualType ThisType = Constructor->getThisType(S.Context);
3123      if (isa<InitListExpr>(From)) {
3124        // Initializer lists don't have conversions as such.
3125        User.Before.setAsIdentityConversion();
3126      } else {
3127        if (Best->Conversions[0].isEllipsis())
3128          User.EllipsisConversion = true;
3129        else {
3130          User.Before = Best->Conversions[0].Standard;
3131          User.EllipsisConversion = false;
3132        }
3133      }
3134      User.HadMultipleCandidates = HadMultipleCandidates;
3135      User.ConversionFunction = Constructor;
3136      User.FoundConversionFunction = Best->FoundDecl;
3137      User.After.setAsIdentityConversion();
3138      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3139      User.After.setAllToTypes(ToType);
3140      return OR_Success;
3141    }
3142    if (CXXConversionDecl *Conversion
3143                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3144      // C++ [over.ics.user]p1:
3145      //
3146      //   [...] If the user-defined conversion is specified by a
3147      //   conversion function (12.3.2), the initial standard
3148      //   conversion sequence converts the source type to the
3149      //   implicit object parameter of the conversion function.
3150      User.Before = Best->Conversions[0].Standard;
3151      User.HadMultipleCandidates = HadMultipleCandidates;
3152      User.ConversionFunction = Conversion;
3153      User.FoundConversionFunction = Best->FoundDecl;
3154      User.EllipsisConversion = false;
3155
3156      // C++ [over.ics.user]p2:
3157      //   The second standard conversion sequence converts the
3158      //   result of the user-defined conversion to the target type
3159      //   for the sequence. Since an implicit conversion sequence
3160      //   is an initialization, the special rules for
3161      //   initialization by user-defined conversion apply when
3162      //   selecting the best user-defined conversion for a
3163      //   user-defined conversion sequence (see 13.3.3 and
3164      //   13.3.3.1).
3165      User.After = Best->FinalConversion;
3166      return OR_Success;
3167    }
3168    llvm_unreachable("Not a constructor or conversion function?");
3169
3170  case OR_No_Viable_Function:
3171    return OR_No_Viable_Function;
3172  case OR_Deleted:
3173    // No conversion here! We're done.
3174    return OR_Deleted;
3175
3176  case OR_Ambiguous:
3177    return OR_Ambiguous;
3178  }
3179
3180  llvm_unreachable("Invalid OverloadResult!");
3181}
3182
3183bool
3184Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3185  ImplicitConversionSequence ICS;
3186  OverloadCandidateSet CandidateSet(From->getExprLoc());
3187  OverloadingResult OvResult =
3188    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3189                            CandidateSet, false);
3190  if (OvResult == OR_Ambiguous)
3191    Diag(From->getLocStart(),
3192         diag::err_typecheck_ambiguous_condition)
3193          << From->getType() << ToType << From->getSourceRange();
3194  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3195    Diag(From->getLocStart(),
3196         diag::err_typecheck_nonviable_condition)
3197    << From->getType() << ToType << From->getSourceRange();
3198  else
3199    return false;
3200  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3201  return true;
3202}
3203
3204/// \brief Compare the user-defined conversion functions or constructors
3205/// of two user-defined conversion sequences to determine whether any ordering
3206/// is possible.
3207static ImplicitConversionSequence::CompareKind
3208compareConversionFunctions(Sema &S,
3209                           FunctionDecl *Function1,
3210                           FunctionDecl *Function2) {
3211  if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3212    return ImplicitConversionSequence::Indistinguishable;
3213
3214  // Objective-C++:
3215  //   If both conversion functions are implicitly-declared conversions from
3216  //   a lambda closure type to a function pointer and a block pointer,
3217  //   respectively, always prefer the conversion to a function pointer,
3218  //   because the function pointer is more lightweight and is more likely
3219  //   to keep code working.
3220  CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3221  if (!Conv1)
3222    return ImplicitConversionSequence::Indistinguishable;
3223
3224  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3225  if (!Conv2)
3226    return ImplicitConversionSequence::Indistinguishable;
3227
3228  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3229    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3230    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3231    if (Block1 != Block2)
3232      return Block1? ImplicitConversionSequence::Worse
3233                   : ImplicitConversionSequence::Better;
3234  }
3235
3236  return ImplicitConversionSequence::Indistinguishable;
3237}
3238
3239/// CompareImplicitConversionSequences - Compare two implicit
3240/// conversion sequences to determine whether one is better than the
3241/// other or if they are indistinguishable (C++ 13.3.3.2).
3242static ImplicitConversionSequence::CompareKind
3243CompareImplicitConversionSequences(Sema &S,
3244                                   const ImplicitConversionSequence& ICS1,
3245                                   const ImplicitConversionSequence& ICS2)
3246{
3247  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3248  // conversion sequences (as defined in 13.3.3.1)
3249  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3250  //      conversion sequence than a user-defined conversion sequence or
3251  //      an ellipsis conversion sequence, and
3252  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3253  //      conversion sequence than an ellipsis conversion sequence
3254  //      (13.3.3.1.3).
3255  //
3256  // C++0x [over.best.ics]p10:
3257  //   For the purpose of ranking implicit conversion sequences as
3258  //   described in 13.3.3.2, the ambiguous conversion sequence is
3259  //   treated as a user-defined sequence that is indistinguishable
3260  //   from any other user-defined conversion sequence.
3261  if (ICS1.getKindRank() < ICS2.getKindRank())
3262    return ImplicitConversionSequence::Better;
3263  if (ICS2.getKindRank() < ICS1.getKindRank())
3264    return ImplicitConversionSequence::Worse;
3265
3266  // The following checks require both conversion sequences to be of
3267  // the same kind.
3268  if (ICS1.getKind() != ICS2.getKind())
3269    return ImplicitConversionSequence::Indistinguishable;
3270
3271  ImplicitConversionSequence::CompareKind Result =
3272      ImplicitConversionSequence::Indistinguishable;
3273
3274  // Two implicit conversion sequences of the same form are
3275  // indistinguishable conversion sequences unless one of the
3276  // following rules apply: (C++ 13.3.3.2p3):
3277  if (ICS1.isStandard())
3278    Result = CompareStandardConversionSequences(S,
3279                                                ICS1.Standard, ICS2.Standard);
3280  else if (ICS1.isUserDefined()) {
3281    // User-defined conversion sequence U1 is a better conversion
3282    // sequence than another user-defined conversion sequence U2 if
3283    // they contain the same user-defined conversion function or
3284    // constructor and if the second standard conversion sequence of
3285    // U1 is better than the second standard conversion sequence of
3286    // U2 (C++ 13.3.3.2p3).
3287    if (ICS1.UserDefined.ConversionFunction ==
3288          ICS2.UserDefined.ConversionFunction)
3289      Result = CompareStandardConversionSequences(S,
3290                                                  ICS1.UserDefined.After,
3291                                                  ICS2.UserDefined.After);
3292    else
3293      Result = compareConversionFunctions(S,
3294                                          ICS1.UserDefined.ConversionFunction,
3295                                          ICS2.UserDefined.ConversionFunction);
3296  }
3297
3298  // List-initialization sequence L1 is a better conversion sequence than
3299  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3300  // for some X and L2 does not.
3301  if (Result == ImplicitConversionSequence::Indistinguishable &&
3302      !ICS1.isBad() &&
3303      ICS1.isListInitializationSequence() &&
3304      ICS2.isListInitializationSequence()) {
3305    if (ICS1.isStdInitializerListElement() &&
3306        !ICS2.isStdInitializerListElement())
3307      return ImplicitConversionSequence::Better;
3308    if (!ICS1.isStdInitializerListElement() &&
3309        ICS2.isStdInitializerListElement())
3310      return ImplicitConversionSequence::Worse;
3311  }
3312
3313  return Result;
3314}
3315
3316static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3317  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3318    Qualifiers Quals;
3319    T1 = Context.getUnqualifiedArrayType(T1, Quals);
3320    T2 = Context.getUnqualifiedArrayType(T2, Quals);
3321  }
3322
3323  return Context.hasSameUnqualifiedType(T1, T2);
3324}
3325
3326// Per 13.3.3.2p3, compare the given standard conversion sequences to
3327// determine if one is a proper subset of the other.
3328static ImplicitConversionSequence::CompareKind
3329compareStandardConversionSubsets(ASTContext &Context,
3330                                 const StandardConversionSequence& SCS1,
3331                                 const StandardConversionSequence& SCS2) {
3332  ImplicitConversionSequence::CompareKind Result
3333    = ImplicitConversionSequence::Indistinguishable;
3334
3335  // the identity conversion sequence is considered to be a subsequence of
3336  // any non-identity conversion sequence
3337  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3338    return ImplicitConversionSequence::Better;
3339  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3340    return ImplicitConversionSequence::Worse;
3341
3342  if (SCS1.Second != SCS2.Second) {
3343    if (SCS1.Second == ICK_Identity)
3344      Result = ImplicitConversionSequence::Better;
3345    else if (SCS2.Second == ICK_Identity)
3346      Result = ImplicitConversionSequence::Worse;
3347    else
3348      return ImplicitConversionSequence::Indistinguishable;
3349  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3350    return ImplicitConversionSequence::Indistinguishable;
3351
3352  if (SCS1.Third == SCS2.Third) {
3353    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3354                             : ImplicitConversionSequence::Indistinguishable;
3355  }
3356
3357  if (SCS1.Third == ICK_Identity)
3358    return Result == ImplicitConversionSequence::Worse
3359             ? ImplicitConversionSequence::Indistinguishable
3360             : ImplicitConversionSequence::Better;
3361
3362  if (SCS2.Third == ICK_Identity)
3363    return Result == ImplicitConversionSequence::Better
3364             ? ImplicitConversionSequence::Indistinguishable
3365             : ImplicitConversionSequence::Worse;
3366
3367  return ImplicitConversionSequence::Indistinguishable;
3368}
3369
3370/// \brief Determine whether one of the given reference bindings is better
3371/// than the other based on what kind of bindings they are.
3372static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3373                                       const StandardConversionSequence &SCS2) {
3374  // C++0x [over.ics.rank]p3b4:
3375  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3376  //      implicit object parameter of a non-static member function declared
3377  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3378  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3379  //      lvalue reference to a function lvalue and S2 binds an rvalue
3380  //      reference*.
3381  //
3382  // FIXME: Rvalue references. We're going rogue with the above edits,
3383  // because the semantics in the current C++0x working paper (N3225 at the
3384  // time of this writing) break the standard definition of std::forward
3385  // and std::reference_wrapper when dealing with references to functions.
3386  // Proposed wording changes submitted to CWG for consideration.
3387  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3388      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3389    return false;
3390
3391  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3392          SCS2.IsLvalueReference) ||
3393         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3394          !SCS2.IsLvalueReference);
3395}
3396
3397/// CompareStandardConversionSequences - Compare two standard
3398/// conversion sequences to determine whether one is better than the
3399/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3400static ImplicitConversionSequence::CompareKind
3401CompareStandardConversionSequences(Sema &S,
3402                                   const StandardConversionSequence& SCS1,
3403                                   const StandardConversionSequence& SCS2)
3404{
3405  // Standard conversion sequence S1 is a better conversion sequence
3406  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3407
3408  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3409  //     sequences in the canonical form defined by 13.3.3.1.1,
3410  //     excluding any Lvalue Transformation; the identity conversion
3411  //     sequence is considered to be a subsequence of any
3412  //     non-identity conversion sequence) or, if not that,
3413  if (ImplicitConversionSequence::CompareKind CK
3414        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3415    return CK;
3416
3417  //  -- the rank of S1 is better than the rank of S2 (by the rules
3418  //     defined below), or, if not that,
3419  ImplicitConversionRank Rank1 = SCS1.getRank();
3420  ImplicitConversionRank Rank2 = SCS2.getRank();
3421  if (Rank1 < Rank2)
3422    return ImplicitConversionSequence::Better;
3423  else if (Rank2 < Rank1)
3424    return ImplicitConversionSequence::Worse;
3425
3426  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3427  // are indistinguishable unless one of the following rules
3428  // applies:
3429
3430  //   A conversion that is not a conversion of a pointer, or
3431  //   pointer to member, to bool is better than another conversion
3432  //   that is such a conversion.
3433  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3434    return SCS2.isPointerConversionToBool()
3435             ? ImplicitConversionSequence::Better
3436             : ImplicitConversionSequence::Worse;
3437
3438  // C++ [over.ics.rank]p4b2:
3439  //
3440  //   If class B is derived directly or indirectly from class A,
3441  //   conversion of B* to A* is better than conversion of B* to
3442  //   void*, and conversion of A* to void* is better than conversion
3443  //   of B* to void*.
3444  bool SCS1ConvertsToVoid
3445    = SCS1.isPointerConversionToVoidPointer(S.Context);
3446  bool SCS2ConvertsToVoid
3447    = SCS2.isPointerConversionToVoidPointer(S.Context);
3448  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3449    // Exactly one of the conversion sequences is a conversion to
3450    // a void pointer; it's the worse conversion.
3451    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3452                              : ImplicitConversionSequence::Worse;
3453  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3454    // Neither conversion sequence converts to a void pointer; compare
3455    // their derived-to-base conversions.
3456    if (ImplicitConversionSequence::CompareKind DerivedCK
3457          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3458      return DerivedCK;
3459  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3460             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3461    // Both conversion sequences are conversions to void
3462    // pointers. Compare the source types to determine if there's an
3463    // inheritance relationship in their sources.
3464    QualType FromType1 = SCS1.getFromType();
3465    QualType FromType2 = SCS2.getFromType();
3466
3467    // Adjust the types we're converting from via the array-to-pointer
3468    // conversion, if we need to.
3469    if (SCS1.First == ICK_Array_To_Pointer)
3470      FromType1 = S.Context.getArrayDecayedType(FromType1);
3471    if (SCS2.First == ICK_Array_To_Pointer)
3472      FromType2 = S.Context.getArrayDecayedType(FromType2);
3473
3474    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3475    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3476
3477    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3478      return ImplicitConversionSequence::Better;
3479    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3480      return ImplicitConversionSequence::Worse;
3481
3482    // Objective-C++: If one interface is more specific than the
3483    // other, it is the better one.
3484    const ObjCObjectPointerType* FromObjCPtr1
3485      = FromType1->getAs<ObjCObjectPointerType>();
3486    const ObjCObjectPointerType* FromObjCPtr2
3487      = FromType2->getAs<ObjCObjectPointerType>();
3488    if (FromObjCPtr1 && FromObjCPtr2) {
3489      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3490                                                          FromObjCPtr2);
3491      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3492                                                           FromObjCPtr1);
3493      if (AssignLeft != AssignRight) {
3494        return AssignLeft? ImplicitConversionSequence::Better
3495                         : ImplicitConversionSequence::Worse;
3496      }
3497    }
3498  }
3499
3500  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3501  // bullet 3).
3502  if (ImplicitConversionSequence::CompareKind QualCK
3503        = CompareQualificationConversions(S, SCS1, SCS2))
3504    return QualCK;
3505
3506  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3507    // Check for a better reference binding based on the kind of bindings.
3508    if (isBetterReferenceBindingKind(SCS1, SCS2))
3509      return ImplicitConversionSequence::Better;
3510    else if (isBetterReferenceBindingKind(SCS2, SCS1))
3511      return ImplicitConversionSequence::Worse;
3512
3513    // C++ [over.ics.rank]p3b4:
3514    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3515    //      which the references refer are the same type except for
3516    //      top-level cv-qualifiers, and the type to which the reference
3517    //      initialized by S2 refers is more cv-qualified than the type
3518    //      to which the reference initialized by S1 refers.
3519    QualType T1 = SCS1.getToType(2);
3520    QualType T2 = SCS2.getToType(2);
3521    T1 = S.Context.getCanonicalType(T1);
3522    T2 = S.Context.getCanonicalType(T2);
3523    Qualifiers T1Quals, T2Quals;
3524    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3525    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3526    if (UnqualT1 == UnqualT2) {
3527      // Objective-C++ ARC: If the references refer to objects with different
3528      // lifetimes, prefer bindings that don't change lifetime.
3529      if (SCS1.ObjCLifetimeConversionBinding !=
3530                                          SCS2.ObjCLifetimeConversionBinding) {
3531        return SCS1.ObjCLifetimeConversionBinding
3532                                           ? ImplicitConversionSequence::Worse
3533                                           : ImplicitConversionSequence::Better;
3534      }
3535
3536      // If the type is an array type, promote the element qualifiers to the
3537      // type for comparison.
3538      if (isa<ArrayType>(T1) && T1Quals)
3539        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3540      if (isa<ArrayType>(T2) && T2Quals)
3541        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3542      if (T2.isMoreQualifiedThan(T1))
3543        return ImplicitConversionSequence::Better;
3544      else if (T1.isMoreQualifiedThan(T2))
3545        return ImplicitConversionSequence::Worse;
3546    }
3547  }
3548
3549  // In Microsoft mode, prefer an integral conversion to a
3550  // floating-to-integral conversion if the integral conversion
3551  // is between types of the same size.
3552  // For example:
3553  // void f(float);
3554  // void f(int);
3555  // int main {
3556  //    long a;
3557  //    f(a);
3558  // }
3559  // Here, MSVC will call f(int) instead of generating a compile error
3560  // as clang will do in standard mode.
3561  if (S.getLangOpts().MicrosoftMode &&
3562      SCS1.Second == ICK_Integral_Conversion &&
3563      SCS2.Second == ICK_Floating_Integral &&
3564      S.Context.getTypeSize(SCS1.getFromType()) ==
3565      S.Context.getTypeSize(SCS1.getToType(2)))
3566    return ImplicitConversionSequence::Better;
3567
3568  return ImplicitConversionSequence::Indistinguishable;
3569}
3570
3571/// CompareQualificationConversions - Compares two standard conversion
3572/// sequences to determine whether they can be ranked based on their
3573/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3574ImplicitConversionSequence::CompareKind
3575CompareQualificationConversions(Sema &S,
3576                                const StandardConversionSequence& SCS1,
3577                                const StandardConversionSequence& SCS2) {
3578  // C++ 13.3.3.2p3:
3579  //  -- S1 and S2 differ only in their qualification conversion and
3580  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3581  //     cv-qualification signature of type T1 is a proper subset of
3582  //     the cv-qualification signature of type T2, and S1 is not the
3583  //     deprecated string literal array-to-pointer conversion (4.2).
3584  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3585      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3586    return ImplicitConversionSequence::Indistinguishable;
3587
3588  // FIXME: the example in the standard doesn't use a qualification
3589  // conversion (!)
3590  QualType T1 = SCS1.getToType(2);
3591  QualType T2 = SCS2.getToType(2);
3592  T1 = S.Context.getCanonicalType(T1);
3593  T2 = S.Context.getCanonicalType(T2);
3594  Qualifiers T1Quals, T2Quals;
3595  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3596  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3597
3598  // If the types are the same, we won't learn anything by unwrapped
3599  // them.
3600  if (UnqualT1 == UnqualT2)
3601    return ImplicitConversionSequence::Indistinguishable;
3602
3603  // If the type is an array type, promote the element qualifiers to the type
3604  // for comparison.
3605  if (isa<ArrayType>(T1) && T1Quals)
3606    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3607  if (isa<ArrayType>(T2) && T2Quals)
3608    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3609
3610  ImplicitConversionSequence::CompareKind Result
3611    = ImplicitConversionSequence::Indistinguishable;
3612
3613  // Objective-C++ ARC:
3614  //   Prefer qualification conversions not involving a change in lifetime
3615  //   to qualification conversions that do not change lifetime.
3616  if (SCS1.QualificationIncludesObjCLifetime !=
3617                                      SCS2.QualificationIncludesObjCLifetime) {
3618    Result = SCS1.QualificationIncludesObjCLifetime
3619               ? ImplicitConversionSequence::Worse
3620               : ImplicitConversionSequence::Better;
3621  }
3622
3623  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3624    // Within each iteration of the loop, we check the qualifiers to
3625    // determine if this still looks like a qualification
3626    // conversion. Then, if all is well, we unwrap one more level of
3627    // pointers or pointers-to-members and do it all again
3628    // until there are no more pointers or pointers-to-members left
3629    // to unwrap. This essentially mimics what
3630    // IsQualificationConversion does, but here we're checking for a
3631    // strict subset of qualifiers.
3632    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3633      // The qualifiers are the same, so this doesn't tell us anything
3634      // about how the sequences rank.
3635      ;
3636    else if (T2.isMoreQualifiedThan(T1)) {
3637      // T1 has fewer qualifiers, so it could be the better sequence.
3638      if (Result == ImplicitConversionSequence::Worse)
3639        // Neither has qualifiers that are a subset of the other's
3640        // qualifiers.
3641        return ImplicitConversionSequence::Indistinguishable;
3642
3643      Result = ImplicitConversionSequence::Better;
3644    } else if (T1.isMoreQualifiedThan(T2)) {
3645      // T2 has fewer qualifiers, so it could be the better sequence.
3646      if (Result == ImplicitConversionSequence::Better)
3647        // Neither has qualifiers that are a subset of the other's
3648        // qualifiers.
3649        return ImplicitConversionSequence::Indistinguishable;
3650
3651      Result = ImplicitConversionSequence::Worse;
3652    } else {
3653      // Qualifiers are disjoint.
3654      return ImplicitConversionSequence::Indistinguishable;
3655    }
3656
3657    // If the types after this point are equivalent, we're done.
3658    if (S.Context.hasSameUnqualifiedType(T1, T2))
3659      break;
3660  }
3661
3662  // Check that the winning standard conversion sequence isn't using
3663  // the deprecated string literal array to pointer conversion.
3664  switch (Result) {
3665  case ImplicitConversionSequence::Better:
3666    if (SCS1.DeprecatedStringLiteralToCharPtr)
3667      Result = ImplicitConversionSequence::Indistinguishable;
3668    break;
3669
3670  case ImplicitConversionSequence::Indistinguishable:
3671    break;
3672
3673  case ImplicitConversionSequence::Worse:
3674    if (SCS2.DeprecatedStringLiteralToCharPtr)
3675      Result = ImplicitConversionSequence::Indistinguishable;
3676    break;
3677  }
3678
3679  return Result;
3680}
3681
3682/// CompareDerivedToBaseConversions - Compares two standard conversion
3683/// sequences to determine whether they can be ranked based on their
3684/// various kinds of derived-to-base conversions (C++
3685/// [over.ics.rank]p4b3).  As part of these checks, we also look at
3686/// conversions between Objective-C interface types.
3687ImplicitConversionSequence::CompareKind
3688CompareDerivedToBaseConversions(Sema &S,
3689                                const StandardConversionSequence& SCS1,
3690                                const StandardConversionSequence& SCS2) {
3691  QualType FromType1 = SCS1.getFromType();
3692  QualType ToType1 = SCS1.getToType(1);
3693  QualType FromType2 = SCS2.getFromType();
3694  QualType ToType2 = SCS2.getToType(1);
3695
3696  // Adjust the types we're converting from via the array-to-pointer
3697  // conversion, if we need to.
3698  if (SCS1.First == ICK_Array_To_Pointer)
3699    FromType1 = S.Context.getArrayDecayedType(FromType1);
3700  if (SCS2.First == ICK_Array_To_Pointer)
3701    FromType2 = S.Context.getArrayDecayedType(FromType2);
3702
3703  // Canonicalize all of the types.
3704  FromType1 = S.Context.getCanonicalType(FromType1);
3705  ToType1 = S.Context.getCanonicalType(ToType1);
3706  FromType2 = S.Context.getCanonicalType(FromType2);
3707  ToType2 = S.Context.getCanonicalType(ToType2);
3708
3709  // C++ [over.ics.rank]p4b3:
3710  //
3711  //   If class B is derived directly or indirectly from class A and
3712  //   class C is derived directly or indirectly from B,
3713  //
3714  // Compare based on pointer conversions.
3715  if (SCS1.Second == ICK_Pointer_Conversion &&
3716      SCS2.Second == ICK_Pointer_Conversion &&
3717      /*FIXME: Remove if Objective-C id conversions get their own rank*/
3718      FromType1->isPointerType() && FromType2->isPointerType() &&
3719      ToType1->isPointerType() && ToType2->isPointerType()) {
3720    QualType FromPointee1
3721      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3722    QualType ToPointee1
3723      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3724    QualType FromPointee2
3725      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3726    QualType ToPointee2
3727      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3728
3729    //   -- conversion of C* to B* is better than conversion of C* to A*,
3730    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3731      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3732        return ImplicitConversionSequence::Better;
3733      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3734        return ImplicitConversionSequence::Worse;
3735    }
3736
3737    //   -- conversion of B* to A* is better than conversion of C* to A*,
3738    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3739      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3740        return ImplicitConversionSequence::Better;
3741      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3742        return ImplicitConversionSequence::Worse;
3743    }
3744  } else if (SCS1.Second == ICK_Pointer_Conversion &&
3745             SCS2.Second == ICK_Pointer_Conversion) {
3746    const ObjCObjectPointerType *FromPtr1
3747      = FromType1->getAs<ObjCObjectPointerType>();
3748    const ObjCObjectPointerType *FromPtr2
3749      = FromType2->getAs<ObjCObjectPointerType>();
3750    const ObjCObjectPointerType *ToPtr1
3751      = ToType1->getAs<ObjCObjectPointerType>();
3752    const ObjCObjectPointerType *ToPtr2
3753      = ToType2->getAs<ObjCObjectPointerType>();
3754
3755    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3756      // Apply the same conversion ranking rules for Objective-C pointer types
3757      // that we do for C++ pointers to class types. However, we employ the
3758      // Objective-C pseudo-subtyping relationship used for assignment of
3759      // Objective-C pointer types.
3760      bool FromAssignLeft
3761        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3762      bool FromAssignRight
3763        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3764      bool ToAssignLeft
3765        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3766      bool ToAssignRight
3767        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3768
3769      // A conversion to an a non-id object pointer type or qualified 'id'
3770      // type is better than a conversion to 'id'.
3771      if (ToPtr1->isObjCIdType() &&
3772          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3773        return ImplicitConversionSequence::Worse;
3774      if (ToPtr2->isObjCIdType() &&
3775          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3776        return ImplicitConversionSequence::Better;
3777
3778      // A conversion to a non-id object pointer type is better than a
3779      // conversion to a qualified 'id' type
3780      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3781        return ImplicitConversionSequence::Worse;
3782      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3783        return ImplicitConversionSequence::Better;
3784
3785      // A conversion to an a non-Class object pointer type or qualified 'Class'
3786      // type is better than a conversion to 'Class'.
3787      if (ToPtr1->isObjCClassType() &&
3788          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3789        return ImplicitConversionSequence::Worse;
3790      if (ToPtr2->isObjCClassType() &&
3791          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3792        return ImplicitConversionSequence::Better;
3793
3794      // A conversion to a non-Class object pointer type is better than a
3795      // conversion to a qualified 'Class' type.
3796      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3797        return ImplicitConversionSequence::Worse;
3798      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3799        return ImplicitConversionSequence::Better;
3800
3801      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3802      if (S.Context.hasSameType(FromType1, FromType2) &&
3803          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3804          (ToAssignLeft != ToAssignRight))
3805        return ToAssignLeft? ImplicitConversionSequence::Worse
3806                           : ImplicitConversionSequence::Better;
3807
3808      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3809      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3810          (FromAssignLeft != FromAssignRight))
3811        return FromAssignLeft? ImplicitConversionSequence::Better
3812        : ImplicitConversionSequence::Worse;
3813    }
3814  }
3815
3816  // Ranking of member-pointer types.
3817  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3818      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3819      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3820    const MemberPointerType * FromMemPointer1 =
3821                                        FromType1->getAs<MemberPointerType>();
3822    const MemberPointerType * ToMemPointer1 =
3823                                          ToType1->getAs<MemberPointerType>();
3824    const MemberPointerType * FromMemPointer2 =
3825                                          FromType2->getAs<MemberPointerType>();
3826    const MemberPointerType * ToMemPointer2 =
3827                                          ToType2->getAs<MemberPointerType>();
3828    const Type *FromPointeeType1 = FromMemPointer1->getClass();
3829    const Type *ToPointeeType1 = ToMemPointer1->getClass();
3830    const Type *FromPointeeType2 = FromMemPointer2->getClass();
3831    const Type *ToPointeeType2 = ToMemPointer2->getClass();
3832    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3833    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3834    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3835    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3836    // conversion of A::* to B::* is better than conversion of A::* to C::*,
3837    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3838      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3839        return ImplicitConversionSequence::Worse;
3840      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3841        return ImplicitConversionSequence::Better;
3842    }
3843    // conversion of B::* to C::* is better than conversion of A::* to C::*
3844    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3845      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3846        return ImplicitConversionSequence::Better;
3847      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3848        return ImplicitConversionSequence::Worse;
3849    }
3850  }
3851
3852  if (SCS1.Second == ICK_Derived_To_Base) {
3853    //   -- conversion of C to B is better than conversion of C to A,
3854    //   -- binding of an expression of type C to a reference of type
3855    //      B& is better than binding an expression of type C to a
3856    //      reference of type A&,
3857    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3858        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3859      if (S.IsDerivedFrom(ToType1, ToType2))
3860        return ImplicitConversionSequence::Better;
3861      else if (S.IsDerivedFrom(ToType2, ToType1))
3862        return ImplicitConversionSequence::Worse;
3863    }
3864
3865    //   -- conversion of B to A is better than conversion of C to A.
3866    //   -- binding of an expression of type B to a reference of type
3867    //      A& is better than binding an expression of type C to a
3868    //      reference of type A&,
3869    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3870        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3871      if (S.IsDerivedFrom(FromType2, FromType1))
3872        return ImplicitConversionSequence::Better;
3873      else if (S.IsDerivedFrom(FromType1, FromType2))
3874        return ImplicitConversionSequence::Worse;
3875    }
3876  }
3877
3878  return ImplicitConversionSequence::Indistinguishable;
3879}
3880
3881/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3882/// determine whether they are reference-related,
3883/// reference-compatible, reference-compatible with added
3884/// qualification, or incompatible, for use in C++ initialization by
3885/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3886/// type, and the first type (T1) is the pointee type of the reference
3887/// type being initialized.
3888Sema::ReferenceCompareResult
3889Sema::CompareReferenceRelationship(SourceLocation Loc,
3890                                   QualType OrigT1, QualType OrigT2,
3891                                   bool &DerivedToBase,
3892                                   bool &ObjCConversion,
3893                                   bool &ObjCLifetimeConversion) {
3894  assert(!OrigT1->isReferenceType() &&
3895    "T1 must be the pointee type of the reference type");
3896  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3897
3898  QualType T1 = Context.getCanonicalType(OrigT1);
3899  QualType T2 = Context.getCanonicalType(OrigT2);
3900  Qualifiers T1Quals, T2Quals;
3901  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3902  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3903
3904  // C++ [dcl.init.ref]p4:
3905  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3906  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3907  //   T1 is a base class of T2.
3908  DerivedToBase = false;
3909  ObjCConversion = false;
3910  ObjCLifetimeConversion = false;
3911  if (UnqualT1 == UnqualT2) {
3912    // Nothing to do.
3913  } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3914           IsDerivedFrom(UnqualT2, UnqualT1))
3915    DerivedToBase = true;
3916  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3917           UnqualT2->isObjCObjectOrInterfaceType() &&
3918           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3919    ObjCConversion = true;
3920  else
3921    return Ref_Incompatible;
3922
3923  // At this point, we know that T1 and T2 are reference-related (at
3924  // least).
3925
3926  // If the type is an array type, promote the element qualifiers to the type
3927  // for comparison.
3928  if (isa<ArrayType>(T1) && T1Quals)
3929    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3930  if (isa<ArrayType>(T2) && T2Quals)
3931    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3932
3933  // C++ [dcl.init.ref]p4:
3934  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3935  //   reference-related to T2 and cv1 is the same cv-qualification
3936  //   as, or greater cv-qualification than, cv2. For purposes of
3937  //   overload resolution, cases for which cv1 is greater
3938  //   cv-qualification than cv2 are identified as
3939  //   reference-compatible with added qualification (see 13.3.3.2).
3940  //
3941  // Note that we also require equivalence of Objective-C GC and address-space
3942  // qualifiers when performing these computations, so that e.g., an int in
3943  // address space 1 is not reference-compatible with an int in address
3944  // space 2.
3945  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3946      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3947    T1Quals.removeObjCLifetime();
3948    T2Quals.removeObjCLifetime();
3949    ObjCLifetimeConversion = true;
3950  }
3951
3952  if (T1Quals == T2Quals)
3953    return Ref_Compatible;
3954  else if (T1Quals.compatiblyIncludes(T2Quals))
3955    return Ref_Compatible_With_Added_Qualification;
3956  else
3957    return Ref_Related;
3958}
3959
3960/// \brief Look for a user-defined conversion to an value reference-compatible
3961///        with DeclType. Return true if something definite is found.
3962static bool
3963FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3964                         QualType DeclType, SourceLocation DeclLoc,
3965                         Expr *Init, QualType T2, bool AllowRvalues,
3966                         bool AllowExplicit) {
3967  assert(T2->isRecordType() && "Can only find conversions of record types.");
3968  CXXRecordDecl *T2RecordDecl
3969    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3970
3971  OverloadCandidateSet CandidateSet(DeclLoc);
3972  std::pair<CXXRecordDecl::conversion_iterator,
3973            CXXRecordDecl::conversion_iterator>
3974    Conversions = T2RecordDecl->getVisibleConversionFunctions();
3975  for (CXXRecordDecl::conversion_iterator
3976         I = Conversions.first, E = Conversions.second; I != E; ++I) {
3977    NamedDecl *D = *I;
3978    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3979    if (isa<UsingShadowDecl>(D))
3980      D = cast<UsingShadowDecl>(D)->getTargetDecl();
3981
3982    FunctionTemplateDecl *ConvTemplate
3983      = dyn_cast<FunctionTemplateDecl>(D);
3984    CXXConversionDecl *Conv;
3985    if (ConvTemplate)
3986      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3987    else
3988      Conv = cast<CXXConversionDecl>(D);
3989
3990    // If this is an explicit conversion, and we're not allowed to consider
3991    // explicit conversions, skip it.
3992    if (!AllowExplicit && Conv->isExplicit())
3993      continue;
3994
3995    if (AllowRvalues) {
3996      bool DerivedToBase = false;
3997      bool ObjCConversion = false;
3998      bool ObjCLifetimeConversion = false;
3999
4000      // If we are initializing an rvalue reference, don't permit conversion
4001      // functions that return lvalues.
4002      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4003        const ReferenceType *RefType
4004          = Conv->getConversionType()->getAs<LValueReferenceType>();
4005        if (RefType && !RefType->getPointeeType()->isFunctionType())
4006          continue;
4007      }
4008
4009      if (!ConvTemplate &&
4010          S.CompareReferenceRelationship(
4011            DeclLoc,
4012            Conv->getConversionType().getNonReferenceType()
4013              .getUnqualifiedType(),
4014            DeclType.getNonReferenceType().getUnqualifiedType(),
4015            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4016          Sema::Ref_Incompatible)
4017        continue;
4018    } else {
4019      // If the conversion function doesn't return a reference type,
4020      // it can't be considered for this conversion. An rvalue reference
4021      // is only acceptable if its referencee is a function type.
4022
4023      const ReferenceType *RefType =
4024        Conv->getConversionType()->getAs<ReferenceType>();
4025      if (!RefType ||
4026          (!RefType->isLValueReferenceType() &&
4027           !RefType->getPointeeType()->isFunctionType()))
4028        continue;
4029    }
4030
4031    if (ConvTemplate)
4032      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4033                                       Init, DeclType, CandidateSet);
4034    else
4035      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4036                               DeclType, CandidateSet);
4037  }
4038
4039  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4040
4041  OverloadCandidateSet::iterator Best;
4042  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4043  case OR_Success:
4044    // C++ [over.ics.ref]p1:
4045    //
4046    //   [...] If the parameter binds directly to the result of
4047    //   applying a conversion function to the argument
4048    //   expression, the implicit conversion sequence is a
4049    //   user-defined conversion sequence (13.3.3.1.2), with the
4050    //   second standard conversion sequence either an identity
4051    //   conversion or, if the conversion function returns an
4052    //   entity of a type that is a derived class of the parameter
4053    //   type, a derived-to-base Conversion.
4054    if (!Best->FinalConversion.DirectBinding)
4055      return false;
4056
4057    ICS.setUserDefined();
4058    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4059    ICS.UserDefined.After = Best->FinalConversion;
4060    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4061    ICS.UserDefined.ConversionFunction = Best->Function;
4062    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4063    ICS.UserDefined.EllipsisConversion = false;
4064    assert(ICS.UserDefined.After.ReferenceBinding &&
4065           ICS.UserDefined.After.DirectBinding &&
4066           "Expected a direct reference binding!");
4067    return true;
4068
4069  case OR_Ambiguous:
4070    ICS.setAmbiguous();
4071    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4072         Cand != CandidateSet.end(); ++Cand)
4073      if (Cand->Viable)
4074        ICS.Ambiguous.addConversion(Cand->Function);
4075    return true;
4076
4077  case OR_No_Viable_Function:
4078  case OR_Deleted:
4079    // There was no suitable conversion, or we found a deleted
4080    // conversion; continue with other checks.
4081    return false;
4082  }
4083
4084  llvm_unreachable("Invalid OverloadResult!");
4085}
4086
4087/// \brief Compute an implicit conversion sequence for reference
4088/// initialization.
4089static ImplicitConversionSequence
4090TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4091                 SourceLocation DeclLoc,
4092                 bool SuppressUserConversions,
4093                 bool AllowExplicit) {
4094  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4095
4096  // Most paths end in a failed conversion.
4097  ImplicitConversionSequence ICS;
4098  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4099
4100  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4101  QualType T2 = Init->getType();
4102
4103  // If the initializer is the address of an overloaded function, try
4104  // to resolve the overloaded function. If all goes well, T2 is the
4105  // type of the resulting function.
4106  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4107    DeclAccessPair Found;
4108    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4109                                                                false, Found))
4110      T2 = Fn->getType();
4111  }
4112
4113  // Compute some basic properties of the types and the initializer.
4114  bool isRValRef = DeclType->isRValueReferenceType();
4115  bool DerivedToBase = false;
4116  bool ObjCConversion = false;
4117  bool ObjCLifetimeConversion = false;
4118  Expr::Classification InitCategory = Init->Classify(S.Context);
4119  Sema::ReferenceCompareResult RefRelationship
4120    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4121                                     ObjCConversion, ObjCLifetimeConversion);
4122
4123
4124  // C++0x [dcl.init.ref]p5:
4125  //   A reference to type "cv1 T1" is initialized by an expression
4126  //   of type "cv2 T2" as follows:
4127
4128  //     -- If reference is an lvalue reference and the initializer expression
4129  if (!isRValRef) {
4130    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4131    //        reference-compatible with "cv2 T2," or
4132    //
4133    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4134    if (InitCategory.isLValue() &&
4135        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4136      // C++ [over.ics.ref]p1:
4137      //   When a parameter of reference type binds directly (8.5.3)
4138      //   to an argument expression, the implicit conversion sequence
4139      //   is the identity conversion, unless the argument expression
4140      //   has a type that is a derived class of the parameter type,
4141      //   in which case the implicit conversion sequence is a
4142      //   derived-to-base Conversion (13.3.3.1).
4143      ICS.setStandard();
4144      ICS.Standard.First = ICK_Identity;
4145      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4146                         : ObjCConversion? ICK_Compatible_Conversion
4147                         : ICK_Identity;
4148      ICS.Standard.Third = ICK_Identity;
4149      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4150      ICS.Standard.setToType(0, T2);
4151      ICS.Standard.setToType(1, T1);
4152      ICS.Standard.setToType(2, T1);
4153      ICS.Standard.ReferenceBinding = true;
4154      ICS.Standard.DirectBinding = true;
4155      ICS.Standard.IsLvalueReference = !isRValRef;
4156      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4157      ICS.Standard.BindsToRvalue = false;
4158      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4159      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4160      ICS.Standard.CopyConstructor = 0;
4161
4162      // Nothing more to do: the inaccessibility/ambiguity check for
4163      // derived-to-base conversions is suppressed when we're
4164      // computing the implicit conversion sequence (C++
4165      // [over.best.ics]p2).
4166      return ICS;
4167    }
4168
4169    //       -- has a class type (i.e., T2 is a class type), where T1 is
4170    //          not reference-related to T2, and can be implicitly
4171    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4172    //          is reference-compatible with "cv3 T3" 92) (this
4173    //          conversion is selected by enumerating the applicable
4174    //          conversion functions (13.3.1.6) and choosing the best
4175    //          one through overload resolution (13.3)),
4176    if (!SuppressUserConversions && T2->isRecordType() &&
4177        !S.RequireCompleteType(DeclLoc, T2, 0) &&
4178        RefRelationship == Sema::Ref_Incompatible) {
4179      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4180                                   Init, T2, /*AllowRvalues=*/false,
4181                                   AllowExplicit))
4182        return ICS;
4183    }
4184  }
4185
4186  //     -- Otherwise, the reference shall be an lvalue reference to a
4187  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4188  //        shall be an rvalue reference.
4189  //
4190  // We actually handle one oddity of C++ [over.ics.ref] at this
4191  // point, which is that, due to p2 (which short-circuits reference
4192  // binding by only attempting a simple conversion for non-direct
4193  // bindings) and p3's strange wording, we allow a const volatile
4194  // reference to bind to an rvalue. Hence the check for the presence
4195  // of "const" rather than checking for "const" being the only
4196  // qualifier.
4197  // This is also the point where rvalue references and lvalue inits no longer
4198  // go together.
4199  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4200    return ICS;
4201
4202  //       -- If the initializer expression
4203  //
4204  //            -- is an xvalue, class prvalue, array prvalue or function
4205  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4206  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4207      (InitCategory.isXValue() ||
4208      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4209      (InitCategory.isLValue() && T2->isFunctionType()))) {
4210    ICS.setStandard();
4211    ICS.Standard.First = ICK_Identity;
4212    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4213                      : ObjCConversion? ICK_Compatible_Conversion
4214                      : ICK_Identity;
4215    ICS.Standard.Third = ICK_Identity;
4216    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4217    ICS.Standard.setToType(0, T2);
4218    ICS.Standard.setToType(1, T1);
4219    ICS.Standard.setToType(2, T1);
4220    ICS.Standard.ReferenceBinding = true;
4221    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4222    // binding unless we're binding to a class prvalue.
4223    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4224    // allow the use of rvalue references in C++98/03 for the benefit of
4225    // standard library implementors; therefore, we need the xvalue check here.
4226    ICS.Standard.DirectBinding =
4227      S.getLangOpts().CPlusPlus11 ||
4228      (InitCategory.isPRValue() && !T2->isRecordType());
4229    ICS.Standard.IsLvalueReference = !isRValRef;
4230    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4231    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4232    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4233    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4234    ICS.Standard.CopyConstructor = 0;
4235    return ICS;
4236  }
4237
4238  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4239  //               reference-related to T2, and can be implicitly converted to
4240  //               an xvalue, class prvalue, or function lvalue of type
4241  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4242  //               "cv3 T3",
4243  //
4244  //          then the reference is bound to the value of the initializer
4245  //          expression in the first case and to the result of the conversion
4246  //          in the second case (or, in either case, to an appropriate base
4247  //          class subobject).
4248  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4249      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4250      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4251                               Init, T2, /*AllowRvalues=*/true,
4252                               AllowExplicit)) {
4253    // In the second case, if the reference is an rvalue reference
4254    // and the second standard conversion sequence of the
4255    // user-defined conversion sequence includes an lvalue-to-rvalue
4256    // conversion, the program is ill-formed.
4257    if (ICS.isUserDefined() && isRValRef &&
4258        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4259      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4260
4261    return ICS;
4262  }
4263
4264  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4265  //          initialized from the initializer expression using the
4266  //          rules for a non-reference copy initialization (8.5). The
4267  //          reference is then bound to the temporary. If T1 is
4268  //          reference-related to T2, cv1 must be the same
4269  //          cv-qualification as, or greater cv-qualification than,
4270  //          cv2; otherwise, the program is ill-formed.
4271  if (RefRelationship == Sema::Ref_Related) {
4272    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4273    // we would be reference-compatible or reference-compatible with
4274    // added qualification. But that wasn't the case, so the reference
4275    // initialization fails.
4276    //
4277    // Note that we only want to check address spaces and cvr-qualifiers here.
4278    // ObjC GC and lifetime qualifiers aren't important.
4279    Qualifiers T1Quals = T1.getQualifiers();
4280    Qualifiers T2Quals = T2.getQualifiers();
4281    T1Quals.removeObjCGCAttr();
4282    T1Quals.removeObjCLifetime();
4283    T2Quals.removeObjCGCAttr();
4284    T2Quals.removeObjCLifetime();
4285    if (!T1Quals.compatiblyIncludes(T2Quals))
4286      return ICS;
4287  }
4288
4289  // If at least one of the types is a class type, the types are not
4290  // related, and we aren't allowed any user conversions, the
4291  // reference binding fails. This case is important for breaking
4292  // recursion, since TryImplicitConversion below will attempt to
4293  // create a temporary through the use of a copy constructor.
4294  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4295      (T1->isRecordType() || T2->isRecordType()))
4296    return ICS;
4297
4298  // If T1 is reference-related to T2 and the reference is an rvalue
4299  // reference, the initializer expression shall not be an lvalue.
4300  if (RefRelationship >= Sema::Ref_Related &&
4301      isRValRef && Init->Classify(S.Context).isLValue())
4302    return ICS;
4303
4304  // C++ [over.ics.ref]p2:
4305  //   When a parameter of reference type is not bound directly to
4306  //   an argument expression, the conversion sequence is the one
4307  //   required to convert the argument expression to the
4308  //   underlying type of the reference according to
4309  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4310  //   to copy-initializing a temporary of the underlying type with
4311  //   the argument expression. Any difference in top-level
4312  //   cv-qualification is subsumed by the initialization itself
4313  //   and does not constitute a conversion.
4314  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4315                              /*AllowExplicit=*/false,
4316                              /*InOverloadResolution=*/false,
4317                              /*CStyle=*/false,
4318                              /*AllowObjCWritebackConversion=*/false);
4319
4320  // Of course, that's still a reference binding.
4321  if (ICS.isStandard()) {
4322    ICS.Standard.ReferenceBinding = true;
4323    ICS.Standard.IsLvalueReference = !isRValRef;
4324    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4325    ICS.Standard.BindsToRvalue = true;
4326    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4327    ICS.Standard.ObjCLifetimeConversionBinding = false;
4328  } else if (ICS.isUserDefined()) {
4329    // Don't allow rvalue references to bind to lvalues.
4330    if (DeclType->isRValueReferenceType()) {
4331      if (const ReferenceType *RefType
4332            = ICS.UserDefined.ConversionFunction->getResultType()
4333                ->getAs<LValueReferenceType>()) {
4334        if (!RefType->getPointeeType()->isFunctionType()) {
4335          ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4336                     DeclType);
4337          return ICS;
4338        }
4339      }
4340    }
4341
4342    ICS.UserDefined.After.ReferenceBinding = true;
4343    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4344    ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4345    ICS.UserDefined.After.BindsToRvalue = true;
4346    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4347    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4348  }
4349
4350  return ICS;
4351}
4352
4353static ImplicitConversionSequence
4354TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4355                      bool SuppressUserConversions,
4356                      bool InOverloadResolution,
4357                      bool AllowObjCWritebackConversion,
4358                      bool AllowExplicit = false);
4359
4360/// TryListConversion - Try to copy-initialize a value of type ToType from the
4361/// initializer list From.
4362static ImplicitConversionSequence
4363TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4364                  bool SuppressUserConversions,
4365                  bool InOverloadResolution,
4366                  bool AllowObjCWritebackConversion) {
4367  // C++11 [over.ics.list]p1:
4368  //   When an argument is an initializer list, it is not an expression and
4369  //   special rules apply for converting it to a parameter type.
4370
4371  ImplicitConversionSequence Result;
4372  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4373  Result.setListInitializationSequence();
4374
4375  // We need a complete type for what follows. Incomplete types can never be
4376  // initialized from init lists.
4377  if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4378    return Result;
4379
4380  // C++11 [over.ics.list]p2:
4381  //   If the parameter type is std::initializer_list<X> or "array of X" and
4382  //   all the elements can be implicitly converted to X, the implicit
4383  //   conversion sequence is the worst conversion necessary to convert an
4384  //   element of the list to X.
4385  bool toStdInitializerList = false;
4386  QualType X;
4387  if (ToType->isArrayType())
4388    X = S.Context.getAsArrayType(ToType)->getElementType();
4389  else
4390    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4391  if (!X.isNull()) {
4392    for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4393      Expr *Init = From->getInit(i);
4394      ImplicitConversionSequence ICS =
4395          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4396                                InOverloadResolution,
4397                                AllowObjCWritebackConversion);
4398      // If a single element isn't convertible, fail.
4399      if (ICS.isBad()) {
4400        Result = ICS;
4401        break;
4402      }
4403      // Otherwise, look for the worst conversion.
4404      if (Result.isBad() ||
4405          CompareImplicitConversionSequences(S, ICS, Result) ==
4406              ImplicitConversionSequence::Worse)
4407        Result = ICS;
4408    }
4409
4410    // For an empty list, we won't have computed any conversion sequence.
4411    // Introduce the identity conversion sequence.
4412    if (From->getNumInits() == 0) {
4413      Result.setStandard();
4414      Result.Standard.setAsIdentityConversion();
4415      Result.Standard.setFromType(ToType);
4416      Result.Standard.setAllToTypes(ToType);
4417    }
4418
4419    Result.setListInitializationSequence();
4420    Result.setStdInitializerListElement(toStdInitializerList);
4421    return Result;
4422  }
4423
4424  // C++11 [over.ics.list]p3:
4425  //   Otherwise, if the parameter is a non-aggregate class X and overload
4426  //   resolution chooses a single best constructor [...] the implicit
4427  //   conversion sequence is a user-defined conversion sequence. If multiple
4428  //   constructors are viable but none is better than the others, the
4429  //   implicit conversion sequence is a user-defined conversion sequence.
4430  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4431    // This function can deal with initializer lists.
4432    Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4433                                      /*AllowExplicit=*/false,
4434                                      InOverloadResolution, /*CStyle=*/false,
4435                                      AllowObjCWritebackConversion);
4436    Result.setListInitializationSequence();
4437    return Result;
4438  }
4439
4440  // C++11 [over.ics.list]p4:
4441  //   Otherwise, if the parameter has an aggregate type which can be
4442  //   initialized from the initializer list [...] the implicit conversion
4443  //   sequence is a user-defined conversion sequence.
4444  if (ToType->isAggregateType()) {
4445    // Type is an aggregate, argument is an init list. At this point it comes
4446    // down to checking whether the initialization works.
4447    // FIXME: Find out whether this parameter is consumed or not.
4448    InitializedEntity Entity =
4449        InitializedEntity::InitializeParameter(S.Context, ToType,
4450                                               /*Consumed=*/false);
4451    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4452      Result.setUserDefined();
4453      Result.UserDefined.Before.setAsIdentityConversion();
4454      // Initializer lists don't have a type.
4455      Result.UserDefined.Before.setFromType(QualType());
4456      Result.UserDefined.Before.setAllToTypes(QualType());
4457
4458      Result.UserDefined.After.setAsIdentityConversion();
4459      Result.UserDefined.After.setFromType(ToType);
4460      Result.UserDefined.After.setAllToTypes(ToType);
4461      Result.UserDefined.ConversionFunction = 0;
4462    }
4463    return Result;
4464  }
4465
4466  // C++11 [over.ics.list]p5:
4467  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4468  if (ToType->isReferenceType()) {
4469    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4470    // mention initializer lists in any way. So we go by what list-
4471    // initialization would do and try to extrapolate from that.
4472
4473    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4474
4475    // If the initializer list has a single element that is reference-related
4476    // to the parameter type, we initialize the reference from that.
4477    if (From->getNumInits() == 1) {
4478      Expr *Init = From->getInit(0);
4479
4480      QualType T2 = Init->getType();
4481
4482      // If the initializer is the address of an overloaded function, try
4483      // to resolve the overloaded function. If all goes well, T2 is the
4484      // type of the resulting function.
4485      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4486        DeclAccessPair Found;
4487        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4488                                   Init, ToType, false, Found))
4489          T2 = Fn->getType();
4490      }
4491
4492      // Compute some basic properties of the types and the initializer.
4493      bool dummy1 = false;
4494      bool dummy2 = false;
4495      bool dummy3 = false;
4496      Sema::ReferenceCompareResult RefRelationship
4497        = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4498                                         dummy2, dummy3);
4499
4500      if (RefRelationship >= Sema::Ref_Related)
4501        return TryReferenceInit(S, Init, ToType,
4502                                /*FIXME:*/From->getLocStart(),
4503                                SuppressUserConversions,
4504                                /*AllowExplicit=*/false);
4505    }
4506
4507    // Otherwise, we bind the reference to a temporary created from the
4508    // initializer list.
4509    Result = TryListConversion(S, From, T1, SuppressUserConversions,
4510                               InOverloadResolution,
4511                               AllowObjCWritebackConversion);
4512    if (Result.isFailure())
4513      return Result;
4514    assert(!Result.isEllipsis() &&
4515           "Sub-initialization cannot result in ellipsis conversion.");
4516
4517    // Can we even bind to a temporary?
4518    if (ToType->isRValueReferenceType() ||
4519        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4520      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4521                                            Result.UserDefined.After;
4522      SCS.ReferenceBinding = true;
4523      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4524      SCS.BindsToRvalue = true;
4525      SCS.BindsToFunctionLvalue = false;
4526      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4527      SCS.ObjCLifetimeConversionBinding = false;
4528    } else
4529      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4530                    From, ToType);
4531    return Result;
4532  }
4533
4534  // C++11 [over.ics.list]p6:
4535  //   Otherwise, if the parameter type is not a class:
4536  if (!ToType->isRecordType()) {
4537    //    - if the initializer list has one element, the implicit conversion
4538    //      sequence is the one required to convert the element to the
4539    //      parameter type.
4540    unsigned NumInits = From->getNumInits();
4541    if (NumInits == 1)
4542      Result = TryCopyInitialization(S, From->getInit(0), ToType,
4543                                     SuppressUserConversions,
4544                                     InOverloadResolution,
4545                                     AllowObjCWritebackConversion);
4546    //    - if the initializer list has no elements, the implicit conversion
4547    //      sequence is the identity conversion.
4548    else if (NumInits == 0) {
4549      Result.setStandard();
4550      Result.Standard.setAsIdentityConversion();
4551      Result.Standard.setFromType(ToType);
4552      Result.Standard.setAllToTypes(ToType);
4553    }
4554    Result.setListInitializationSequence();
4555    return Result;
4556  }
4557
4558  // C++11 [over.ics.list]p7:
4559  //   In all cases other than those enumerated above, no conversion is possible
4560  return Result;
4561}
4562
4563/// TryCopyInitialization - Try to copy-initialize a value of type
4564/// ToType from the expression From. Return the implicit conversion
4565/// sequence required to pass this argument, which may be a bad
4566/// conversion sequence (meaning that the argument cannot be passed to
4567/// a parameter of this type). If @p SuppressUserConversions, then we
4568/// do not permit any user-defined conversion sequences.
4569static ImplicitConversionSequence
4570TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4571                      bool SuppressUserConversions,
4572                      bool InOverloadResolution,
4573                      bool AllowObjCWritebackConversion,
4574                      bool AllowExplicit) {
4575  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4576    return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4577                             InOverloadResolution,AllowObjCWritebackConversion);
4578
4579  if (ToType->isReferenceType())
4580    return TryReferenceInit(S, From, ToType,
4581                            /*FIXME:*/From->getLocStart(),
4582                            SuppressUserConversions,
4583                            AllowExplicit);
4584
4585  return TryImplicitConversion(S, From, ToType,
4586                               SuppressUserConversions,
4587                               /*AllowExplicit=*/false,
4588                               InOverloadResolution,
4589                               /*CStyle=*/false,
4590                               AllowObjCWritebackConversion);
4591}
4592
4593static bool TryCopyInitialization(const CanQualType FromQTy,
4594                                  const CanQualType ToQTy,
4595                                  Sema &S,
4596                                  SourceLocation Loc,
4597                                  ExprValueKind FromVK) {
4598  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4599  ImplicitConversionSequence ICS =
4600    TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4601
4602  return !ICS.isBad();
4603}
4604
4605/// TryObjectArgumentInitialization - Try to initialize the object
4606/// parameter of the given member function (@c Method) from the
4607/// expression @p From.
4608static ImplicitConversionSequence
4609TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
4610                                Expr::Classification FromClassification,
4611                                CXXMethodDecl *Method,
4612                                CXXRecordDecl *ActingContext) {
4613  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4614  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4615  //                 const volatile object.
4616  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4617    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4618  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4619
4620  // Set up the conversion sequence as a "bad" conversion, to allow us
4621  // to exit early.
4622  ImplicitConversionSequence ICS;
4623
4624  // We need to have an object of class type.
4625  QualType FromType = OrigFromType;
4626  if (const PointerType *PT = FromType->getAs<PointerType>()) {
4627    FromType = PT->getPointeeType();
4628
4629    // When we had a pointer, it's implicitly dereferenced, so we
4630    // better have an lvalue.
4631    assert(FromClassification.isLValue());
4632  }
4633
4634  assert(FromType->isRecordType());
4635
4636  // C++0x [over.match.funcs]p4:
4637  //   For non-static member functions, the type of the implicit object
4638  //   parameter is
4639  //
4640  //     - "lvalue reference to cv X" for functions declared without a
4641  //        ref-qualifier or with the & ref-qualifier
4642  //     - "rvalue reference to cv X" for functions declared with the &&
4643  //        ref-qualifier
4644  //
4645  // where X is the class of which the function is a member and cv is the
4646  // cv-qualification on the member function declaration.
4647  //
4648  // However, when finding an implicit conversion sequence for the argument, we
4649  // are not allowed to create temporaries or perform user-defined conversions
4650  // (C++ [over.match.funcs]p5). We perform a simplified version of
4651  // reference binding here, that allows class rvalues to bind to
4652  // non-constant references.
4653
4654  // First check the qualifiers.
4655  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4656  if (ImplicitParamType.getCVRQualifiers()
4657                                    != FromTypeCanon.getLocalCVRQualifiers() &&
4658      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4659    ICS.setBad(BadConversionSequence::bad_qualifiers,
4660               OrigFromType, ImplicitParamType);
4661    return ICS;
4662  }
4663
4664  // Check that we have either the same type or a derived type. It
4665  // affects the conversion rank.
4666  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4667  ImplicitConversionKind SecondKind;
4668  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4669    SecondKind = ICK_Identity;
4670  } else if (S.IsDerivedFrom(FromType, ClassType))
4671    SecondKind = ICK_Derived_To_Base;
4672  else {
4673    ICS.setBad(BadConversionSequence::unrelated_class,
4674               FromType, ImplicitParamType);
4675    return ICS;
4676  }
4677
4678  // Check the ref-qualifier.
4679  switch (Method->getRefQualifier()) {
4680  case RQ_None:
4681    // Do nothing; we don't care about lvalueness or rvalueness.
4682    break;
4683
4684  case RQ_LValue:
4685    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4686      // non-const lvalue reference cannot bind to an rvalue
4687      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4688                 ImplicitParamType);
4689      return ICS;
4690    }
4691    break;
4692
4693  case RQ_RValue:
4694    if (!FromClassification.isRValue()) {
4695      // rvalue reference cannot bind to an lvalue
4696      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4697                 ImplicitParamType);
4698      return ICS;
4699    }
4700    break;
4701  }
4702
4703  // Success. Mark this as a reference binding.
4704  ICS.setStandard();
4705  ICS.Standard.setAsIdentityConversion();
4706  ICS.Standard.Second = SecondKind;
4707  ICS.Standard.setFromType(FromType);
4708  ICS.Standard.setAllToTypes(ImplicitParamType);
4709  ICS.Standard.ReferenceBinding = true;
4710  ICS.Standard.DirectBinding = true;
4711  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4712  ICS.Standard.BindsToFunctionLvalue = false;
4713  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4714  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4715    = (Method->getRefQualifier() == RQ_None);
4716  return ICS;
4717}
4718
4719/// PerformObjectArgumentInitialization - Perform initialization of
4720/// the implicit object parameter for the given Method with the given
4721/// expression.
4722ExprResult
4723Sema::PerformObjectArgumentInitialization(Expr *From,
4724                                          NestedNameSpecifier *Qualifier,
4725                                          NamedDecl *FoundDecl,
4726                                          CXXMethodDecl *Method) {
4727  QualType FromRecordType, DestType;
4728  QualType ImplicitParamRecordType  =
4729    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4730
4731  Expr::Classification FromClassification;
4732  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4733    FromRecordType = PT->getPointeeType();
4734    DestType = Method->getThisType(Context);
4735    FromClassification = Expr::Classification::makeSimpleLValue();
4736  } else {
4737    FromRecordType = From->getType();
4738    DestType = ImplicitParamRecordType;
4739    FromClassification = From->Classify(Context);
4740  }
4741
4742  // Note that we always use the true parent context when performing
4743  // the actual argument initialization.
4744  ImplicitConversionSequence ICS
4745    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4746                                      Method, Method->getParent());
4747  if (ICS.isBad()) {
4748    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4749      Qualifiers FromQs = FromRecordType.getQualifiers();
4750      Qualifiers ToQs = DestType.getQualifiers();
4751      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4752      if (CVR) {
4753        Diag(From->getLocStart(),
4754             diag::err_member_function_call_bad_cvr)
4755          << Method->getDeclName() << FromRecordType << (CVR - 1)
4756          << From->getSourceRange();
4757        Diag(Method->getLocation(), diag::note_previous_decl)
4758          << Method->getDeclName();
4759        return ExprError();
4760      }
4761    }
4762
4763    return Diag(From->getLocStart(),
4764                diag::err_implicit_object_parameter_init)
4765       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4766  }
4767
4768  if (ICS.Standard.Second == ICK_Derived_To_Base) {
4769    ExprResult FromRes =
4770      PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4771    if (FromRes.isInvalid())
4772      return ExprError();
4773    From = FromRes.take();
4774  }
4775
4776  if (!Context.hasSameType(From->getType(), DestType))
4777    From = ImpCastExprToType(From, DestType, CK_NoOp,
4778                             From->getValueKind()).take();
4779  return Owned(From);
4780}
4781
4782/// TryContextuallyConvertToBool - Attempt to contextually convert the
4783/// expression From to bool (C++0x [conv]p3).
4784static ImplicitConversionSequence
4785TryContextuallyConvertToBool(Sema &S, Expr *From) {
4786  // FIXME: This is pretty broken.
4787  return TryImplicitConversion(S, From, S.Context.BoolTy,
4788                               // FIXME: Are these flags correct?
4789                               /*SuppressUserConversions=*/false,
4790                               /*AllowExplicit=*/true,
4791                               /*InOverloadResolution=*/false,
4792                               /*CStyle=*/false,
4793                               /*AllowObjCWritebackConversion=*/false);
4794}
4795
4796/// PerformContextuallyConvertToBool - Perform a contextual conversion
4797/// of the expression From to bool (C++0x [conv]p3).
4798ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4799  if (checkPlaceholderForOverload(*this, From))
4800    return ExprError();
4801
4802  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4803  if (!ICS.isBad())
4804    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4805
4806  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4807    return Diag(From->getLocStart(),
4808                diag::err_typecheck_bool_condition)
4809                  << From->getType() << From->getSourceRange();
4810  return ExprError();
4811}
4812
4813/// Check that the specified conversion is permitted in a converted constant
4814/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4815/// is acceptable.
4816static bool CheckConvertedConstantConversions(Sema &S,
4817                                              StandardConversionSequence &SCS) {
4818  // Since we know that the target type is an integral or unscoped enumeration
4819  // type, most conversion kinds are impossible. All possible First and Third
4820  // conversions are fine.
4821  switch (SCS.Second) {
4822  case ICK_Identity:
4823  case ICK_Integral_Promotion:
4824  case ICK_Integral_Conversion:
4825    return true;
4826
4827  case ICK_Boolean_Conversion:
4828    // Conversion from an integral or unscoped enumeration type to bool is
4829    // classified as ICK_Boolean_Conversion, but it's also an integral
4830    // conversion, so it's permitted in a converted constant expression.
4831    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4832           SCS.getToType(2)->isBooleanType();
4833
4834  case ICK_Floating_Integral:
4835  case ICK_Complex_Real:
4836    return false;
4837
4838  case ICK_Lvalue_To_Rvalue:
4839  case ICK_Array_To_Pointer:
4840  case ICK_Function_To_Pointer:
4841  case ICK_NoReturn_Adjustment:
4842  case ICK_Qualification:
4843  case ICK_Compatible_Conversion:
4844  case ICK_Vector_Conversion:
4845  case ICK_Vector_Splat:
4846  case ICK_Derived_To_Base:
4847  case ICK_Pointer_Conversion:
4848  case ICK_Pointer_Member:
4849  case ICK_Block_Pointer_Conversion:
4850  case ICK_Writeback_Conversion:
4851  case ICK_Floating_Promotion:
4852  case ICK_Complex_Promotion:
4853  case ICK_Complex_Conversion:
4854  case ICK_Floating_Conversion:
4855  case ICK_TransparentUnionConversion:
4856    llvm_unreachable("unexpected second conversion kind");
4857
4858  case ICK_Num_Conversion_Kinds:
4859    break;
4860  }
4861
4862  llvm_unreachable("unknown conversion kind");
4863}
4864
4865/// CheckConvertedConstantExpression - Check that the expression From is a
4866/// converted constant expression of type T, perform the conversion and produce
4867/// the converted expression, per C++11 [expr.const]p3.
4868ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4869                                                  llvm::APSInt &Value,
4870                                                  CCEKind CCE) {
4871  assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4872  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4873
4874  if (checkPlaceholderForOverload(*this, From))
4875    return ExprError();
4876
4877  // C++11 [expr.const]p3 with proposed wording fixes:
4878  //  A converted constant expression of type T is a core constant expression,
4879  //  implicitly converted to a prvalue of type T, where the converted
4880  //  expression is a literal constant expression and the implicit conversion
4881  //  sequence contains only user-defined conversions, lvalue-to-rvalue
4882  //  conversions, integral promotions, and integral conversions other than
4883  //  narrowing conversions.
4884  ImplicitConversionSequence ICS =
4885    TryImplicitConversion(From, T,
4886                          /*SuppressUserConversions=*/false,
4887                          /*AllowExplicit=*/false,
4888                          /*InOverloadResolution=*/false,
4889                          /*CStyle=*/false,
4890                          /*AllowObjcWritebackConversion=*/false);
4891  StandardConversionSequence *SCS = 0;
4892  switch (ICS.getKind()) {
4893  case ImplicitConversionSequence::StandardConversion:
4894    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4895      return Diag(From->getLocStart(),
4896                  diag::err_typecheck_converted_constant_expression_disallowed)
4897               << From->getType() << From->getSourceRange() << T;
4898    SCS = &ICS.Standard;
4899    break;
4900  case ImplicitConversionSequence::UserDefinedConversion:
4901    // We are converting from class type to an integral or enumeration type, so
4902    // the Before sequence must be trivial.
4903    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4904      return Diag(From->getLocStart(),
4905                  diag::err_typecheck_converted_constant_expression_disallowed)
4906               << From->getType() << From->getSourceRange() << T;
4907    SCS = &ICS.UserDefined.After;
4908    break;
4909  case ImplicitConversionSequence::AmbiguousConversion:
4910  case ImplicitConversionSequence::BadConversion:
4911    if (!DiagnoseMultipleUserDefinedConversion(From, T))
4912      return Diag(From->getLocStart(),
4913                  diag::err_typecheck_converted_constant_expression)
4914                    << From->getType() << From->getSourceRange() << T;
4915    return ExprError();
4916
4917  case ImplicitConversionSequence::EllipsisConversion:
4918    llvm_unreachable("ellipsis conversion in converted constant expression");
4919  }
4920
4921  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4922  if (Result.isInvalid())
4923    return Result;
4924
4925  // Check for a narrowing implicit conversion.
4926  APValue PreNarrowingValue;
4927  QualType PreNarrowingType;
4928  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4929                                PreNarrowingType)) {
4930  case NK_Variable_Narrowing:
4931    // Implicit conversion to a narrower type, and the value is not a constant
4932    // expression. We'll diagnose this in a moment.
4933  case NK_Not_Narrowing:
4934    break;
4935
4936  case NK_Constant_Narrowing:
4937    Diag(From->getLocStart(),
4938         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4939                             diag::err_cce_narrowing)
4940      << CCE << /*Constant*/1
4941      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
4942    break;
4943
4944  case NK_Type_Narrowing:
4945    Diag(From->getLocStart(),
4946         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4947                             diag::err_cce_narrowing)
4948      << CCE << /*Constant*/0 << From->getType() << T;
4949    break;
4950  }
4951
4952  // Check the expression is a constant expression.
4953  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4954  Expr::EvalResult Eval;
4955  Eval.Diag = &Notes;
4956
4957  if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4958    // The expression can't be folded, so we can't keep it at this position in
4959    // the AST.
4960    Result = ExprError();
4961  } else {
4962    Value = Eval.Val.getInt();
4963
4964    if (Notes.empty()) {
4965      // It's a constant expression.
4966      return Result;
4967    }
4968  }
4969
4970  // It's not a constant expression. Produce an appropriate diagnostic.
4971  if (Notes.size() == 1 &&
4972      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4973    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4974  else {
4975    Diag(From->getLocStart(), diag::err_expr_not_cce)
4976      << CCE << From->getSourceRange();
4977    for (unsigned I = 0; I < Notes.size(); ++I)
4978      Diag(Notes[I].first, Notes[I].second);
4979  }
4980  return Result;
4981}
4982
4983/// dropPointerConversions - If the given standard conversion sequence
4984/// involves any pointer conversions, remove them.  This may change
4985/// the result type of the conversion sequence.
4986static void dropPointerConversion(StandardConversionSequence &SCS) {
4987  if (SCS.Second == ICK_Pointer_Conversion) {
4988    SCS.Second = ICK_Identity;
4989    SCS.Third = ICK_Identity;
4990    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4991  }
4992}
4993
4994/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4995/// convert the expression From to an Objective-C pointer type.
4996static ImplicitConversionSequence
4997TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4998  // Do an implicit conversion to 'id'.
4999  QualType Ty = S.Context.getObjCIdType();
5000  ImplicitConversionSequence ICS
5001    = TryImplicitConversion(S, From, Ty,
5002                            // FIXME: Are these flags correct?
5003                            /*SuppressUserConversions=*/false,
5004                            /*AllowExplicit=*/true,
5005                            /*InOverloadResolution=*/false,
5006                            /*CStyle=*/false,
5007                            /*AllowObjCWritebackConversion=*/false);
5008
5009  // Strip off any final conversions to 'id'.
5010  switch (ICS.getKind()) {
5011  case ImplicitConversionSequence::BadConversion:
5012  case ImplicitConversionSequence::AmbiguousConversion:
5013  case ImplicitConversionSequence::EllipsisConversion:
5014    break;
5015
5016  case ImplicitConversionSequence::UserDefinedConversion:
5017    dropPointerConversion(ICS.UserDefined.After);
5018    break;
5019
5020  case ImplicitConversionSequence::StandardConversion:
5021    dropPointerConversion(ICS.Standard);
5022    break;
5023  }
5024
5025  return ICS;
5026}
5027
5028/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5029/// conversion of the expression From to an Objective-C pointer type.
5030ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5031  if (checkPlaceholderForOverload(*this, From))
5032    return ExprError();
5033
5034  QualType Ty = Context.getObjCIdType();
5035  ImplicitConversionSequence ICS =
5036    TryContextuallyConvertToObjCPointer(*this, From);
5037  if (!ICS.isBad())
5038    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5039  return ExprError();
5040}
5041
5042/// Determine whether the provided type is an integral type, or an enumeration
5043/// type of a permitted flavor.
5044static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5045  return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5046                         : T->isIntegralOrUnscopedEnumerationType();
5047}
5048
5049/// \brief Attempt to convert the given expression to an integral or
5050/// enumeration type.
5051///
5052/// This routine will attempt to convert an expression of class type to an
5053/// integral or enumeration type, if that class type only has a single
5054/// conversion to an integral or enumeration type.
5055///
5056/// \param Loc The source location of the construct that requires the
5057/// conversion.
5058///
5059/// \param From The expression we're converting from.
5060///
5061/// \param Diagnoser Used to output any diagnostics.
5062///
5063/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5064/// enumerations should be considered.
5065///
5066/// \returns The expression, converted to an integral or enumeration type if
5067/// successful.
5068ExprResult
5069Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
5070                                         ICEConvertDiagnoser &Diagnoser,
5071                                         bool AllowScopedEnumerations) {
5072  // We can't perform any more checking for type-dependent expressions.
5073  if (From->isTypeDependent())
5074    return Owned(From);
5075
5076  // Process placeholders immediately.
5077  if (From->hasPlaceholderType()) {
5078    ExprResult result = CheckPlaceholderExpr(From);
5079    if (result.isInvalid()) return result;
5080    From = result.take();
5081  }
5082
5083  // If the expression already has integral or enumeration type, we're golden.
5084  QualType T = From->getType();
5085  if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
5086    return DefaultLvalueConversion(From);
5087
5088  // FIXME: Check for missing '()' if T is a function type?
5089
5090  // If we don't have a class type in C++, there's no way we can get an
5091  // expression of integral or enumeration type.
5092  const RecordType *RecordTy = T->getAs<RecordType>();
5093  if (!RecordTy || !getLangOpts().CPlusPlus) {
5094    if (!Diagnoser.Suppress)
5095      Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
5096    return Owned(From);
5097  }
5098
5099  // We must have a complete class type.
5100  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5101    ICEConvertDiagnoser &Diagnoser;
5102    Expr *From;
5103
5104    TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5105      : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
5106
5107    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5108      Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5109    }
5110  } IncompleteDiagnoser(Diagnoser, From);
5111
5112  if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5113    return Owned(From);
5114
5115  // Look for a conversion to an integral or enumeration type.
5116  UnresolvedSet<4> ViableConversions;
5117  UnresolvedSet<4> ExplicitConversions;
5118  std::pair<CXXRecordDecl::conversion_iterator,
5119            CXXRecordDecl::conversion_iterator> Conversions
5120    = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5121
5122  bool HadMultipleCandidates
5123    = (std::distance(Conversions.first, Conversions.second) > 1);
5124
5125  for (CXXRecordDecl::conversion_iterator
5126         I = Conversions.first, E = Conversions.second; I != E; ++I) {
5127    if (CXXConversionDecl *Conversion
5128          = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5129      if (isIntegralOrEnumerationType(
5130            Conversion->getConversionType().getNonReferenceType(),
5131            AllowScopedEnumerations)) {
5132        if (Conversion->isExplicit())
5133          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5134        else
5135          ViableConversions.addDecl(I.getDecl(), I.getAccess());
5136      }
5137    }
5138  }
5139
5140  switch (ViableConversions.size()) {
5141  case 0:
5142    if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
5143      DeclAccessPair Found = ExplicitConversions[0];
5144      CXXConversionDecl *Conversion
5145        = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5146
5147      // The user probably meant to invoke the given explicit
5148      // conversion; use it.
5149      QualType ConvTy
5150        = Conversion->getConversionType().getNonReferenceType();
5151      std::string TypeStr;
5152      ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
5153
5154      Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
5155        << FixItHint::CreateInsertion(From->getLocStart(),
5156                                      "static_cast<" + TypeStr + ">(")
5157        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5158                                      ")");
5159      Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
5160
5161      // If we aren't in a SFINAE context, build a call to the
5162      // explicit conversion function.
5163      if (isSFINAEContext())
5164        return ExprError();
5165
5166      CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5167      ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5168                                                 HadMultipleCandidates);
5169      if (Result.isInvalid())
5170        return ExprError();
5171      // Record usage of conversion in an implicit cast.
5172      From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5173                                      CK_UserDefinedConversion,
5174                                      Result.get(), 0,
5175                                      Result.get()->getValueKind());
5176    }
5177
5178    // We'll complain below about a non-integral condition type.
5179    break;
5180
5181  case 1: {
5182    // Apply this conversion.
5183    DeclAccessPair Found = ViableConversions[0];
5184    CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5185
5186    CXXConversionDecl *Conversion
5187      = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5188    QualType ConvTy
5189      = Conversion->getConversionType().getNonReferenceType();
5190    if (!Diagnoser.SuppressConversion) {
5191      if (isSFINAEContext())
5192        return ExprError();
5193
5194      Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5195        << From->getSourceRange();
5196    }
5197
5198    ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5199                                               HadMultipleCandidates);
5200    if (Result.isInvalid())
5201      return ExprError();
5202    // Record usage of conversion in an implicit cast.
5203    From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5204                                    CK_UserDefinedConversion,
5205                                    Result.get(), 0,
5206                                    Result.get()->getValueKind());
5207    break;
5208  }
5209
5210  default:
5211    if (Diagnoser.Suppress)
5212      return ExprError();
5213
5214    Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
5215    for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5216      CXXConversionDecl *Conv
5217        = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5218      QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5219      Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
5220    }
5221    return Owned(From);
5222  }
5223
5224  if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5225      !Diagnoser.Suppress) {
5226    Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5227      << From->getSourceRange();
5228  }
5229
5230  return DefaultLvalueConversion(From);
5231}
5232
5233/// AddOverloadCandidate - Adds the given function to the set of
5234/// candidate functions, using the given function call arguments.  If
5235/// @p SuppressUserConversions, then don't allow user-defined
5236/// conversions via constructors or conversion operators.
5237///
5238/// \param PartialOverloading true if we are performing "partial" overloading
5239/// based on an incomplete set of function arguments. This feature is used by
5240/// code completion.
5241void
5242Sema::AddOverloadCandidate(FunctionDecl *Function,
5243                           DeclAccessPair FoundDecl,
5244                           llvm::ArrayRef<Expr *> Args,
5245                           OverloadCandidateSet& CandidateSet,
5246                           bool SuppressUserConversions,
5247                           bool PartialOverloading,
5248                           bool AllowExplicit) {
5249  const FunctionProtoType* Proto
5250    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5251  assert(Proto && "Functions without a prototype cannot be overloaded");
5252  assert(!Function->getDescribedFunctionTemplate() &&
5253         "Use AddTemplateOverloadCandidate for function templates");
5254
5255  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5256    if (!isa<CXXConstructorDecl>(Method)) {
5257      // If we get here, it's because we're calling a member function
5258      // that is named without a member access expression (e.g.,
5259      // "this->f") that was either written explicitly or created
5260      // implicitly. This can happen with a qualified call to a member
5261      // function, e.g., X::f(). We use an empty type for the implied
5262      // object argument (C++ [over.call.func]p3), and the acting context
5263      // is irrelevant.
5264      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5265                         QualType(), Expr::Classification::makeSimpleLValue(),
5266                         Args, CandidateSet, SuppressUserConversions);
5267      return;
5268    }
5269    // We treat a constructor like a non-member function, since its object
5270    // argument doesn't participate in overload resolution.
5271  }
5272
5273  if (!CandidateSet.isNewCandidate(Function))
5274    return;
5275
5276  // Overload resolution is always an unevaluated context.
5277  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5278
5279  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5280    // C++ [class.copy]p3:
5281    //   A member function template is never instantiated to perform the copy
5282    //   of a class object to an object of its class type.
5283    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5284    if (Args.size() == 1 &&
5285        Constructor->isSpecializationCopyingObject() &&
5286        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5287         IsDerivedFrom(Args[0]->getType(), ClassType)))
5288      return;
5289  }
5290
5291  // Add this candidate
5292  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5293  Candidate.FoundDecl = FoundDecl;
5294  Candidate.Function = Function;
5295  Candidate.Viable = true;
5296  Candidate.IsSurrogate = false;
5297  Candidate.IgnoreObjectArgument = false;
5298  Candidate.ExplicitCallArguments = Args.size();
5299
5300  unsigned NumArgsInProto = Proto->getNumArgs();
5301
5302  // (C++ 13.3.2p2): A candidate function having fewer than m
5303  // parameters is viable only if it has an ellipsis in its parameter
5304  // list (8.3.5).
5305  if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5306      !Proto->isVariadic()) {
5307    Candidate.Viable = false;
5308    Candidate.FailureKind = ovl_fail_too_many_arguments;
5309    return;
5310  }
5311
5312  // (C++ 13.3.2p2): A candidate function having more than m parameters
5313  // is viable only if the (m+1)st parameter has a default argument
5314  // (8.3.6). For the purposes of overload resolution, the
5315  // parameter list is truncated on the right, so that there are
5316  // exactly m parameters.
5317  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5318  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5319    // Not enough arguments.
5320    Candidate.Viable = false;
5321    Candidate.FailureKind = ovl_fail_too_few_arguments;
5322    return;
5323  }
5324
5325  // (CUDA B.1): Check for invalid calls between targets.
5326  if (getLangOpts().CUDA)
5327    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5328      if (CheckCUDATarget(Caller, Function)) {
5329        Candidate.Viable = false;
5330        Candidate.FailureKind = ovl_fail_bad_target;
5331        return;
5332      }
5333
5334  // Determine the implicit conversion sequences for each of the
5335  // arguments.
5336  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5337    if (ArgIdx < NumArgsInProto) {
5338      // (C++ 13.3.2p3): for F to be a viable function, there shall
5339      // exist for each argument an implicit conversion sequence
5340      // (13.3.3.1) that converts that argument to the corresponding
5341      // parameter of F.
5342      QualType ParamType = Proto->getArgType(ArgIdx);
5343      Candidate.Conversions[ArgIdx]
5344        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5345                                SuppressUserConversions,
5346                                /*InOverloadResolution=*/true,
5347                                /*AllowObjCWritebackConversion=*/
5348                                  getLangOpts().ObjCAutoRefCount,
5349                                AllowExplicit);
5350      if (Candidate.Conversions[ArgIdx].isBad()) {
5351        Candidate.Viable = false;
5352        Candidate.FailureKind = ovl_fail_bad_conversion;
5353        break;
5354      }
5355    } else {
5356      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5357      // argument for which there is no corresponding parameter is
5358      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5359      Candidate.Conversions[ArgIdx].setEllipsis();
5360    }
5361  }
5362}
5363
5364/// \brief Add all of the function declarations in the given function set to
5365/// the overload canddiate set.
5366void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5367                                 llvm::ArrayRef<Expr *> Args,
5368                                 OverloadCandidateSet& CandidateSet,
5369                                 bool SuppressUserConversions,
5370                               TemplateArgumentListInfo *ExplicitTemplateArgs) {
5371  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5372    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5373    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5374      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5375        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5376                           cast<CXXMethodDecl>(FD)->getParent(),
5377                           Args[0]->getType(), Args[0]->Classify(Context),
5378                           Args.slice(1), CandidateSet,
5379                           SuppressUserConversions);
5380      else
5381        AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5382                             SuppressUserConversions);
5383    } else {
5384      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5385      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5386          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5387        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5388                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5389                                   ExplicitTemplateArgs,
5390                                   Args[0]->getType(),
5391                                   Args[0]->Classify(Context), Args.slice(1),
5392                                   CandidateSet, SuppressUserConversions);
5393      else
5394        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5395                                     ExplicitTemplateArgs, Args,
5396                                     CandidateSet, SuppressUserConversions);
5397    }
5398  }
5399}
5400
5401/// AddMethodCandidate - Adds a named decl (which is some kind of
5402/// method) as a method candidate to the given overload set.
5403void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5404                              QualType ObjectType,
5405                              Expr::Classification ObjectClassification,
5406                              Expr **Args, unsigned NumArgs,
5407                              OverloadCandidateSet& CandidateSet,
5408                              bool SuppressUserConversions) {
5409  NamedDecl *Decl = FoundDecl.getDecl();
5410  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5411
5412  if (isa<UsingShadowDecl>(Decl))
5413    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5414
5415  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5416    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5417           "Expected a member function template");
5418    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5419                               /*ExplicitArgs*/ 0,
5420                               ObjectType, ObjectClassification,
5421                               llvm::makeArrayRef(Args, NumArgs), CandidateSet,
5422                               SuppressUserConversions);
5423  } else {
5424    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5425                       ObjectType, ObjectClassification,
5426                       llvm::makeArrayRef(Args, NumArgs),
5427                       CandidateSet, SuppressUserConversions);
5428  }
5429}
5430
5431/// AddMethodCandidate - Adds the given C++ member function to the set
5432/// of candidate functions, using the given function call arguments
5433/// and the object argument (@c Object). For example, in a call
5434/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5435/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5436/// allow user-defined conversions via constructors or conversion
5437/// operators.
5438void
5439Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5440                         CXXRecordDecl *ActingContext, QualType ObjectType,
5441                         Expr::Classification ObjectClassification,
5442                         llvm::ArrayRef<Expr *> Args,
5443                         OverloadCandidateSet& CandidateSet,
5444                         bool SuppressUserConversions) {
5445  const FunctionProtoType* Proto
5446    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5447  assert(Proto && "Methods without a prototype cannot be overloaded");
5448  assert(!isa<CXXConstructorDecl>(Method) &&
5449         "Use AddOverloadCandidate for constructors");
5450
5451  if (!CandidateSet.isNewCandidate(Method))
5452    return;
5453
5454  // Overload resolution is always an unevaluated context.
5455  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5456
5457  // Add this candidate
5458  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5459  Candidate.FoundDecl = FoundDecl;
5460  Candidate.Function = Method;
5461  Candidate.IsSurrogate = false;
5462  Candidate.IgnoreObjectArgument = false;
5463  Candidate.ExplicitCallArguments = Args.size();
5464
5465  unsigned NumArgsInProto = Proto->getNumArgs();
5466
5467  // (C++ 13.3.2p2): A candidate function having fewer than m
5468  // parameters is viable only if it has an ellipsis in its parameter
5469  // list (8.3.5).
5470  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5471    Candidate.Viable = false;
5472    Candidate.FailureKind = ovl_fail_too_many_arguments;
5473    return;
5474  }
5475
5476  // (C++ 13.3.2p2): A candidate function having more than m parameters
5477  // is viable only if the (m+1)st parameter has a default argument
5478  // (8.3.6). For the purposes of overload resolution, the
5479  // parameter list is truncated on the right, so that there are
5480  // exactly m parameters.
5481  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5482  if (Args.size() < MinRequiredArgs) {
5483    // Not enough arguments.
5484    Candidate.Viable = false;
5485    Candidate.FailureKind = ovl_fail_too_few_arguments;
5486    return;
5487  }
5488
5489  Candidate.Viable = true;
5490
5491  if (Method->isStatic() || ObjectType.isNull())
5492    // The implicit object argument is ignored.
5493    Candidate.IgnoreObjectArgument = true;
5494  else {
5495    // Determine the implicit conversion sequence for the object
5496    // parameter.
5497    Candidate.Conversions[0]
5498      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5499                                        Method, ActingContext);
5500    if (Candidate.Conversions[0].isBad()) {
5501      Candidate.Viable = false;
5502      Candidate.FailureKind = ovl_fail_bad_conversion;
5503      return;
5504    }
5505  }
5506
5507  // Determine the implicit conversion sequences for each of the
5508  // arguments.
5509  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5510    if (ArgIdx < NumArgsInProto) {
5511      // (C++ 13.3.2p3): for F to be a viable function, there shall
5512      // exist for each argument an implicit conversion sequence
5513      // (13.3.3.1) that converts that argument to the corresponding
5514      // parameter of F.
5515      QualType ParamType = Proto->getArgType(ArgIdx);
5516      Candidate.Conversions[ArgIdx + 1]
5517        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5518                                SuppressUserConversions,
5519                                /*InOverloadResolution=*/true,
5520                                /*AllowObjCWritebackConversion=*/
5521                                  getLangOpts().ObjCAutoRefCount);
5522      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5523        Candidate.Viable = false;
5524        Candidate.FailureKind = ovl_fail_bad_conversion;
5525        break;
5526      }
5527    } else {
5528      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5529      // argument for which there is no corresponding parameter is
5530      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5531      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5532    }
5533  }
5534}
5535
5536/// \brief Add a C++ member function template as a candidate to the candidate
5537/// set, using template argument deduction to produce an appropriate member
5538/// function template specialization.
5539void
5540Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5541                                 DeclAccessPair FoundDecl,
5542                                 CXXRecordDecl *ActingContext,
5543                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5544                                 QualType ObjectType,
5545                                 Expr::Classification ObjectClassification,
5546                                 llvm::ArrayRef<Expr *> Args,
5547                                 OverloadCandidateSet& CandidateSet,
5548                                 bool SuppressUserConversions) {
5549  if (!CandidateSet.isNewCandidate(MethodTmpl))
5550    return;
5551
5552  // C++ [over.match.funcs]p7:
5553  //   In each case where a candidate is a function template, candidate
5554  //   function template specializations are generated using template argument
5555  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5556  //   candidate functions in the usual way.113) A given name can refer to one
5557  //   or more function templates and also to a set of overloaded non-template
5558  //   functions. In such a case, the candidate functions generated from each
5559  //   function template are combined with the set of non-template candidate
5560  //   functions.
5561  TemplateDeductionInfo Info(CandidateSet.getLocation());
5562  FunctionDecl *Specialization = 0;
5563  if (TemplateDeductionResult Result
5564      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5565                                Specialization, Info)) {
5566    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5567    Candidate.FoundDecl = FoundDecl;
5568    Candidate.Function = MethodTmpl->getTemplatedDecl();
5569    Candidate.Viable = false;
5570    Candidate.FailureKind = ovl_fail_bad_deduction;
5571    Candidate.IsSurrogate = false;
5572    Candidate.IgnoreObjectArgument = false;
5573    Candidate.ExplicitCallArguments = Args.size();
5574    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5575                                                          Info);
5576    return;
5577  }
5578
5579  // Add the function template specialization produced by template argument
5580  // deduction as a candidate.
5581  assert(Specialization && "Missing member function template specialization?");
5582  assert(isa<CXXMethodDecl>(Specialization) &&
5583         "Specialization is not a member function?");
5584  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5585                     ActingContext, ObjectType, ObjectClassification, Args,
5586                     CandidateSet, SuppressUserConversions);
5587}
5588
5589/// \brief Add a C++ function template specialization as a candidate
5590/// in the candidate set, using template argument deduction to produce
5591/// an appropriate function template specialization.
5592void
5593Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5594                                   DeclAccessPair FoundDecl,
5595                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5596                                   llvm::ArrayRef<Expr *> Args,
5597                                   OverloadCandidateSet& CandidateSet,
5598                                   bool SuppressUserConversions) {
5599  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5600    return;
5601
5602  // C++ [over.match.funcs]p7:
5603  //   In each case where a candidate is a function template, candidate
5604  //   function template specializations are generated using template argument
5605  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5606  //   candidate functions in the usual way.113) A given name can refer to one
5607  //   or more function templates and also to a set of overloaded non-template
5608  //   functions. In such a case, the candidate functions generated from each
5609  //   function template are combined with the set of non-template candidate
5610  //   functions.
5611  TemplateDeductionInfo Info(CandidateSet.getLocation());
5612  FunctionDecl *Specialization = 0;
5613  if (TemplateDeductionResult Result
5614        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5615                                  Specialization, Info)) {
5616    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5617    Candidate.FoundDecl = FoundDecl;
5618    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5619    Candidate.Viable = false;
5620    Candidate.FailureKind = ovl_fail_bad_deduction;
5621    Candidate.IsSurrogate = false;
5622    Candidate.IgnoreObjectArgument = false;
5623    Candidate.ExplicitCallArguments = Args.size();
5624    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5625                                                          Info);
5626    return;
5627  }
5628
5629  // Add the function template specialization produced by template argument
5630  // deduction as a candidate.
5631  assert(Specialization && "Missing function template specialization?");
5632  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5633                       SuppressUserConversions);
5634}
5635
5636/// AddConversionCandidate - Add a C++ conversion function as a
5637/// candidate in the candidate set (C++ [over.match.conv],
5638/// C++ [over.match.copy]). From is the expression we're converting from,
5639/// and ToType is the type that we're eventually trying to convert to
5640/// (which may or may not be the same type as the type that the
5641/// conversion function produces).
5642void
5643Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5644                             DeclAccessPair FoundDecl,
5645                             CXXRecordDecl *ActingContext,
5646                             Expr *From, QualType ToType,
5647                             OverloadCandidateSet& CandidateSet) {
5648  assert(!Conversion->getDescribedFunctionTemplate() &&
5649         "Conversion function templates use AddTemplateConversionCandidate");
5650  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5651  if (!CandidateSet.isNewCandidate(Conversion))
5652    return;
5653
5654  // Overload resolution is always an unevaluated context.
5655  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5656
5657  // Add this candidate
5658  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5659  Candidate.FoundDecl = FoundDecl;
5660  Candidate.Function = Conversion;
5661  Candidate.IsSurrogate = false;
5662  Candidate.IgnoreObjectArgument = false;
5663  Candidate.FinalConversion.setAsIdentityConversion();
5664  Candidate.FinalConversion.setFromType(ConvType);
5665  Candidate.FinalConversion.setAllToTypes(ToType);
5666  Candidate.Viable = true;
5667  Candidate.ExplicitCallArguments = 1;
5668
5669  // C++ [over.match.funcs]p4:
5670  //   For conversion functions, the function is considered to be a member of
5671  //   the class of the implicit implied object argument for the purpose of
5672  //   defining the type of the implicit object parameter.
5673  //
5674  // Determine the implicit conversion sequence for the implicit
5675  // object parameter.
5676  QualType ImplicitParamType = From->getType();
5677  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5678    ImplicitParamType = FromPtrType->getPointeeType();
5679  CXXRecordDecl *ConversionContext
5680    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5681
5682  Candidate.Conversions[0]
5683    = TryObjectArgumentInitialization(*this, From->getType(),
5684                                      From->Classify(Context),
5685                                      Conversion, ConversionContext);
5686
5687  if (Candidate.Conversions[0].isBad()) {
5688    Candidate.Viable = false;
5689    Candidate.FailureKind = ovl_fail_bad_conversion;
5690    return;
5691  }
5692
5693  // We won't go through a user-define type conversion function to convert a
5694  // derived to base as such conversions are given Conversion Rank. They only
5695  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5696  QualType FromCanon
5697    = Context.getCanonicalType(From->getType().getUnqualifiedType());
5698  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5699  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5700    Candidate.Viable = false;
5701    Candidate.FailureKind = ovl_fail_trivial_conversion;
5702    return;
5703  }
5704
5705  // To determine what the conversion from the result of calling the
5706  // conversion function to the type we're eventually trying to
5707  // convert to (ToType), we need to synthesize a call to the
5708  // conversion function and attempt copy initialization from it. This
5709  // makes sure that we get the right semantics with respect to
5710  // lvalues/rvalues and the type. Fortunately, we can allocate this
5711  // call on the stack and we don't need its arguments to be
5712  // well-formed.
5713  DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5714                            VK_LValue, From->getLocStart());
5715  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5716                                Context.getPointerType(Conversion->getType()),
5717                                CK_FunctionToPointerDecay,
5718                                &ConversionRef, VK_RValue);
5719
5720  QualType ConversionType = Conversion->getConversionType();
5721  if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5722    Candidate.Viable = false;
5723    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5724    return;
5725  }
5726
5727  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5728
5729  // Note that it is safe to allocate CallExpr on the stack here because
5730  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5731  // allocator).
5732  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5733  CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
5734                From->getLocStart());
5735  ImplicitConversionSequence ICS =
5736    TryCopyInitialization(*this, &Call, ToType,
5737                          /*SuppressUserConversions=*/true,
5738                          /*InOverloadResolution=*/false,
5739                          /*AllowObjCWritebackConversion=*/false);
5740
5741  switch (ICS.getKind()) {
5742  case ImplicitConversionSequence::StandardConversion:
5743    Candidate.FinalConversion = ICS.Standard;
5744
5745    // C++ [over.ics.user]p3:
5746    //   If the user-defined conversion is specified by a specialization of a
5747    //   conversion function template, the second standard conversion sequence
5748    //   shall have exact match rank.
5749    if (Conversion->getPrimaryTemplate() &&
5750        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5751      Candidate.Viable = false;
5752      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5753    }
5754
5755    // C++0x [dcl.init.ref]p5:
5756    //    In the second case, if the reference is an rvalue reference and
5757    //    the second standard conversion sequence of the user-defined
5758    //    conversion sequence includes an lvalue-to-rvalue conversion, the
5759    //    program is ill-formed.
5760    if (ToType->isRValueReferenceType() &&
5761        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5762      Candidate.Viable = false;
5763      Candidate.FailureKind = ovl_fail_bad_final_conversion;
5764    }
5765    break;
5766
5767  case ImplicitConversionSequence::BadConversion:
5768    Candidate.Viable = false;
5769    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5770    break;
5771
5772  default:
5773    llvm_unreachable(
5774           "Can only end up with a standard conversion sequence or failure");
5775  }
5776}
5777
5778/// \brief Adds a conversion function template specialization
5779/// candidate to the overload set, using template argument deduction
5780/// to deduce the template arguments of the conversion function
5781/// template from the type that we are converting to (C++
5782/// [temp.deduct.conv]).
5783void
5784Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5785                                     DeclAccessPair FoundDecl,
5786                                     CXXRecordDecl *ActingDC,
5787                                     Expr *From, QualType ToType,
5788                                     OverloadCandidateSet &CandidateSet) {
5789  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5790         "Only conversion function templates permitted here");
5791
5792  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5793    return;
5794
5795  TemplateDeductionInfo Info(CandidateSet.getLocation());
5796  CXXConversionDecl *Specialization = 0;
5797  if (TemplateDeductionResult Result
5798        = DeduceTemplateArguments(FunctionTemplate, ToType,
5799                                  Specialization, Info)) {
5800    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5801    Candidate.FoundDecl = FoundDecl;
5802    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5803    Candidate.Viable = false;
5804    Candidate.FailureKind = ovl_fail_bad_deduction;
5805    Candidate.IsSurrogate = false;
5806    Candidate.IgnoreObjectArgument = false;
5807    Candidate.ExplicitCallArguments = 1;
5808    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5809                                                          Info);
5810    return;
5811  }
5812
5813  // Add the conversion function template specialization produced by
5814  // template argument deduction as a candidate.
5815  assert(Specialization && "Missing function template specialization?");
5816  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5817                         CandidateSet);
5818}
5819
5820/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5821/// converts the given @c Object to a function pointer via the
5822/// conversion function @c Conversion, and then attempts to call it
5823/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5824/// the type of function that we'll eventually be calling.
5825void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5826                                 DeclAccessPair FoundDecl,
5827                                 CXXRecordDecl *ActingContext,
5828                                 const FunctionProtoType *Proto,
5829                                 Expr *Object,
5830                                 llvm::ArrayRef<Expr *> Args,
5831                                 OverloadCandidateSet& CandidateSet) {
5832  if (!CandidateSet.isNewCandidate(Conversion))
5833    return;
5834
5835  // Overload resolution is always an unevaluated context.
5836  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5837
5838  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5839  Candidate.FoundDecl = FoundDecl;
5840  Candidate.Function = 0;
5841  Candidate.Surrogate = Conversion;
5842  Candidate.Viable = true;
5843  Candidate.IsSurrogate = true;
5844  Candidate.IgnoreObjectArgument = false;
5845  Candidate.ExplicitCallArguments = Args.size();
5846
5847  // Determine the implicit conversion sequence for the implicit
5848  // object parameter.
5849  ImplicitConversionSequence ObjectInit
5850    = TryObjectArgumentInitialization(*this, Object->getType(),
5851                                      Object->Classify(Context),
5852                                      Conversion, ActingContext);
5853  if (ObjectInit.isBad()) {
5854    Candidate.Viable = false;
5855    Candidate.FailureKind = ovl_fail_bad_conversion;
5856    Candidate.Conversions[0] = ObjectInit;
5857    return;
5858  }
5859
5860  // The first conversion is actually a user-defined conversion whose
5861  // first conversion is ObjectInit's standard conversion (which is
5862  // effectively a reference binding). Record it as such.
5863  Candidate.Conversions[0].setUserDefined();
5864  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
5865  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
5866  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
5867  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
5868  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
5869  Candidate.Conversions[0].UserDefined.After
5870    = Candidate.Conversions[0].UserDefined.Before;
5871  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5872
5873  // Find the
5874  unsigned NumArgsInProto = Proto->getNumArgs();
5875
5876  // (C++ 13.3.2p2): A candidate function having fewer than m
5877  // parameters is viable only if it has an ellipsis in its parameter
5878  // list (8.3.5).
5879  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5880    Candidate.Viable = false;
5881    Candidate.FailureKind = ovl_fail_too_many_arguments;
5882    return;
5883  }
5884
5885  // Function types don't have any default arguments, so just check if
5886  // we have enough arguments.
5887  if (Args.size() < NumArgsInProto) {
5888    // Not enough arguments.
5889    Candidate.Viable = false;
5890    Candidate.FailureKind = ovl_fail_too_few_arguments;
5891    return;
5892  }
5893
5894  // Determine the implicit conversion sequences for each of the
5895  // arguments.
5896  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5897    if (ArgIdx < NumArgsInProto) {
5898      // (C++ 13.3.2p3): for F to be a viable function, there shall
5899      // exist for each argument an implicit conversion sequence
5900      // (13.3.3.1) that converts that argument to the corresponding
5901      // parameter of F.
5902      QualType ParamType = Proto->getArgType(ArgIdx);
5903      Candidate.Conversions[ArgIdx + 1]
5904        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5905                                /*SuppressUserConversions=*/false,
5906                                /*InOverloadResolution=*/false,
5907                                /*AllowObjCWritebackConversion=*/
5908                                  getLangOpts().ObjCAutoRefCount);
5909      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5910        Candidate.Viable = false;
5911        Candidate.FailureKind = ovl_fail_bad_conversion;
5912        break;
5913      }
5914    } else {
5915      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5916      // argument for which there is no corresponding parameter is
5917      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5918      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5919    }
5920  }
5921}
5922
5923/// \brief Add overload candidates for overloaded operators that are
5924/// member functions.
5925///
5926/// Add the overloaded operator candidates that are member functions
5927/// for the operator Op that was used in an operator expression such
5928/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5929/// CandidateSet will store the added overload candidates. (C++
5930/// [over.match.oper]).
5931void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5932                                       SourceLocation OpLoc,
5933                                       Expr **Args, unsigned NumArgs,
5934                                       OverloadCandidateSet& CandidateSet,
5935                                       SourceRange OpRange) {
5936  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5937
5938  // C++ [over.match.oper]p3:
5939  //   For a unary operator @ with an operand of a type whose
5940  //   cv-unqualified version is T1, and for a binary operator @ with
5941  //   a left operand of a type whose cv-unqualified version is T1 and
5942  //   a right operand of a type whose cv-unqualified version is T2,
5943  //   three sets of candidate functions, designated member
5944  //   candidates, non-member candidates and built-in candidates, are
5945  //   constructed as follows:
5946  QualType T1 = Args[0]->getType();
5947
5948  //     -- If T1 is a class type, the set of member candidates is the
5949  //        result of the qualified lookup of T1::operator@
5950  //        (13.3.1.1.1); otherwise, the set of member candidates is
5951  //        empty.
5952  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
5953    // Complete the type if it can be completed. Otherwise, we're done.
5954    if (RequireCompleteType(OpLoc, T1, 0))
5955      return;
5956
5957    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5958    LookupQualifiedName(Operators, T1Rec->getDecl());
5959    Operators.suppressDiagnostics();
5960
5961    for (LookupResult::iterator Oper = Operators.begin(),
5962                             OperEnd = Operators.end();
5963         Oper != OperEnd;
5964         ++Oper)
5965      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
5966                         Args[0]->Classify(Context), Args + 1, NumArgs - 1,
5967                         CandidateSet,
5968                         /* SuppressUserConversions = */ false);
5969  }
5970}
5971
5972/// AddBuiltinCandidate - Add a candidate for a built-in
5973/// operator. ResultTy and ParamTys are the result and parameter types
5974/// of the built-in candidate, respectively. Args and NumArgs are the
5975/// arguments being passed to the candidate. IsAssignmentOperator
5976/// should be true when this built-in candidate is an assignment
5977/// operator. NumContextualBoolArguments is the number of arguments
5978/// (at the beginning of the argument list) that will be contextually
5979/// converted to bool.
5980void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
5981                               Expr **Args, unsigned NumArgs,
5982                               OverloadCandidateSet& CandidateSet,
5983                               bool IsAssignmentOperator,
5984                               unsigned NumContextualBoolArguments) {
5985  // Overload resolution is always an unevaluated context.
5986  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5987
5988  // Add this candidate
5989  OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
5990  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
5991  Candidate.Function = 0;
5992  Candidate.IsSurrogate = false;
5993  Candidate.IgnoreObjectArgument = false;
5994  Candidate.BuiltinTypes.ResultTy = ResultTy;
5995  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5996    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5997
5998  // Determine the implicit conversion sequences for each of the
5999  // arguments.
6000  Candidate.Viable = true;
6001  Candidate.ExplicitCallArguments = NumArgs;
6002  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6003    // C++ [over.match.oper]p4:
6004    //   For the built-in assignment operators, conversions of the
6005    //   left operand are restricted as follows:
6006    //     -- no temporaries are introduced to hold the left operand, and
6007    //     -- no user-defined conversions are applied to the left
6008    //        operand to achieve a type match with the left-most
6009    //        parameter of a built-in candidate.
6010    //
6011    // We block these conversions by turning off user-defined
6012    // conversions, since that is the only way that initialization of
6013    // a reference to a non-class type can occur from something that
6014    // is not of the same type.
6015    if (ArgIdx < NumContextualBoolArguments) {
6016      assert(ParamTys[ArgIdx] == Context.BoolTy &&
6017             "Contextual conversion to bool requires bool type");
6018      Candidate.Conversions[ArgIdx]
6019        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6020    } else {
6021      Candidate.Conversions[ArgIdx]
6022        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6023                                ArgIdx == 0 && IsAssignmentOperator,
6024                                /*InOverloadResolution=*/false,
6025                                /*AllowObjCWritebackConversion=*/
6026                                  getLangOpts().ObjCAutoRefCount);
6027    }
6028    if (Candidate.Conversions[ArgIdx].isBad()) {
6029      Candidate.Viable = false;
6030      Candidate.FailureKind = ovl_fail_bad_conversion;
6031      break;
6032    }
6033  }
6034}
6035
6036/// BuiltinCandidateTypeSet - A set of types that will be used for the
6037/// candidate operator functions for built-in operators (C++
6038/// [over.built]). The types are separated into pointer types and
6039/// enumeration types.
6040class BuiltinCandidateTypeSet  {
6041  /// TypeSet - A set of types.
6042  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6043
6044  /// PointerTypes - The set of pointer types that will be used in the
6045  /// built-in candidates.
6046  TypeSet PointerTypes;
6047
6048  /// MemberPointerTypes - The set of member pointer types that will be
6049  /// used in the built-in candidates.
6050  TypeSet MemberPointerTypes;
6051
6052  /// EnumerationTypes - The set of enumeration types that will be
6053  /// used in the built-in candidates.
6054  TypeSet EnumerationTypes;
6055
6056  /// \brief The set of vector types that will be used in the built-in
6057  /// candidates.
6058  TypeSet VectorTypes;
6059
6060  /// \brief A flag indicating non-record types are viable candidates
6061  bool HasNonRecordTypes;
6062
6063  /// \brief A flag indicating whether either arithmetic or enumeration types
6064  /// were present in the candidate set.
6065  bool HasArithmeticOrEnumeralTypes;
6066
6067  /// \brief A flag indicating whether the nullptr type was present in the
6068  /// candidate set.
6069  bool HasNullPtrType;
6070
6071  /// Sema - The semantic analysis instance where we are building the
6072  /// candidate type set.
6073  Sema &SemaRef;
6074
6075  /// Context - The AST context in which we will build the type sets.
6076  ASTContext &Context;
6077
6078  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6079                                               const Qualifiers &VisibleQuals);
6080  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6081
6082public:
6083  /// iterator - Iterates through the types that are part of the set.
6084  typedef TypeSet::iterator iterator;
6085
6086  BuiltinCandidateTypeSet(Sema &SemaRef)
6087    : HasNonRecordTypes(false),
6088      HasArithmeticOrEnumeralTypes(false),
6089      HasNullPtrType(false),
6090      SemaRef(SemaRef),
6091      Context(SemaRef.Context) { }
6092
6093  void AddTypesConvertedFrom(QualType Ty,
6094                             SourceLocation Loc,
6095                             bool AllowUserConversions,
6096                             bool AllowExplicitConversions,
6097                             const Qualifiers &VisibleTypeConversionsQuals);
6098
6099  /// pointer_begin - First pointer type found;
6100  iterator pointer_begin() { return PointerTypes.begin(); }
6101
6102  /// pointer_end - Past the last pointer type found;
6103  iterator pointer_end() { return PointerTypes.end(); }
6104
6105  /// member_pointer_begin - First member pointer type found;
6106  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6107
6108  /// member_pointer_end - Past the last member pointer type found;
6109  iterator member_pointer_end() { return MemberPointerTypes.end(); }
6110
6111  /// enumeration_begin - First enumeration type found;
6112  iterator enumeration_begin() { return EnumerationTypes.begin(); }
6113
6114  /// enumeration_end - Past the last enumeration type found;
6115  iterator enumeration_end() { return EnumerationTypes.end(); }
6116
6117  iterator vector_begin() { return VectorTypes.begin(); }
6118  iterator vector_end() { return VectorTypes.end(); }
6119
6120  bool hasNonRecordTypes() { return HasNonRecordTypes; }
6121  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6122  bool hasNullPtrType() const { return HasNullPtrType; }
6123};
6124
6125/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6126/// the set of pointer types along with any more-qualified variants of
6127/// that type. For example, if @p Ty is "int const *", this routine
6128/// will add "int const *", "int const volatile *", "int const
6129/// restrict *", and "int const volatile restrict *" to the set of
6130/// pointer types. Returns true if the add of @p Ty itself succeeded,
6131/// false otherwise.
6132///
6133/// FIXME: what to do about extended qualifiers?
6134bool
6135BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6136                                             const Qualifiers &VisibleQuals) {
6137
6138  // Insert this type.
6139  if (!PointerTypes.insert(Ty))
6140    return false;
6141
6142  QualType PointeeTy;
6143  const PointerType *PointerTy = Ty->getAs<PointerType>();
6144  bool buildObjCPtr = false;
6145  if (!PointerTy) {
6146    const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6147    PointeeTy = PTy->getPointeeType();
6148    buildObjCPtr = true;
6149  } else {
6150    PointeeTy = PointerTy->getPointeeType();
6151  }
6152
6153  // Don't add qualified variants of arrays. For one, they're not allowed
6154  // (the qualifier would sink to the element type), and for another, the
6155  // only overload situation where it matters is subscript or pointer +- int,
6156  // and those shouldn't have qualifier variants anyway.
6157  if (PointeeTy->isArrayType())
6158    return true;
6159
6160  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6161  bool hasVolatile = VisibleQuals.hasVolatile();
6162  bool hasRestrict = VisibleQuals.hasRestrict();
6163
6164  // Iterate through all strict supersets of BaseCVR.
6165  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6166    if ((CVR | BaseCVR) != CVR) continue;
6167    // Skip over volatile if no volatile found anywhere in the types.
6168    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6169
6170    // Skip over restrict if no restrict found anywhere in the types, or if
6171    // the type cannot be restrict-qualified.
6172    if ((CVR & Qualifiers::Restrict) &&
6173        (!hasRestrict ||
6174         (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6175      continue;
6176
6177    // Build qualified pointee type.
6178    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6179
6180    // Build qualified pointer type.
6181    QualType QPointerTy;
6182    if (!buildObjCPtr)
6183      QPointerTy = Context.getPointerType(QPointeeTy);
6184    else
6185      QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6186
6187    // Insert qualified pointer type.
6188    PointerTypes.insert(QPointerTy);
6189  }
6190
6191  return true;
6192}
6193
6194/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6195/// to the set of pointer types along with any more-qualified variants of
6196/// that type. For example, if @p Ty is "int const *", this routine
6197/// will add "int const *", "int const volatile *", "int const
6198/// restrict *", and "int const volatile restrict *" to the set of
6199/// pointer types. Returns true if the add of @p Ty itself succeeded,
6200/// false otherwise.
6201///
6202/// FIXME: what to do about extended qualifiers?
6203bool
6204BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6205    QualType Ty) {
6206  // Insert this type.
6207  if (!MemberPointerTypes.insert(Ty))
6208    return false;
6209
6210  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6211  assert(PointerTy && "type was not a member pointer type!");
6212
6213  QualType PointeeTy = PointerTy->getPointeeType();
6214  // Don't add qualified variants of arrays. For one, they're not allowed
6215  // (the qualifier would sink to the element type), and for another, the
6216  // only overload situation where it matters is subscript or pointer +- int,
6217  // and those shouldn't have qualifier variants anyway.
6218  if (PointeeTy->isArrayType())
6219    return true;
6220  const Type *ClassTy = PointerTy->getClass();
6221
6222  // Iterate through all strict supersets of the pointee type's CVR
6223  // qualifiers.
6224  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6225  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6226    if ((CVR | BaseCVR) != CVR) continue;
6227
6228    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6229    MemberPointerTypes.insert(
6230      Context.getMemberPointerType(QPointeeTy, ClassTy));
6231  }
6232
6233  return true;
6234}
6235
6236/// AddTypesConvertedFrom - Add each of the types to which the type @p
6237/// Ty can be implicit converted to the given set of @p Types. We're
6238/// primarily interested in pointer types and enumeration types. We also
6239/// take member pointer types, for the conditional operator.
6240/// AllowUserConversions is true if we should look at the conversion
6241/// functions of a class type, and AllowExplicitConversions if we
6242/// should also include the explicit conversion functions of a class
6243/// type.
6244void
6245BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6246                                               SourceLocation Loc,
6247                                               bool AllowUserConversions,
6248                                               bool AllowExplicitConversions,
6249                                               const Qualifiers &VisibleQuals) {
6250  // Only deal with canonical types.
6251  Ty = Context.getCanonicalType(Ty);
6252
6253  // Look through reference types; they aren't part of the type of an
6254  // expression for the purposes of conversions.
6255  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6256    Ty = RefTy->getPointeeType();
6257
6258  // If we're dealing with an array type, decay to the pointer.
6259  if (Ty->isArrayType())
6260    Ty = SemaRef.Context.getArrayDecayedType(Ty);
6261
6262  // Otherwise, we don't care about qualifiers on the type.
6263  Ty = Ty.getLocalUnqualifiedType();
6264
6265  // Flag if we ever add a non-record type.
6266  const RecordType *TyRec = Ty->getAs<RecordType>();
6267  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6268
6269  // Flag if we encounter an arithmetic type.
6270  HasArithmeticOrEnumeralTypes =
6271    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6272
6273  if (Ty->isObjCIdType() || Ty->isObjCClassType())
6274    PointerTypes.insert(Ty);
6275  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6276    // Insert our type, and its more-qualified variants, into the set
6277    // of types.
6278    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6279      return;
6280  } else if (Ty->isMemberPointerType()) {
6281    // Member pointers are far easier, since the pointee can't be converted.
6282    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6283      return;
6284  } else if (Ty->isEnumeralType()) {
6285    HasArithmeticOrEnumeralTypes = true;
6286    EnumerationTypes.insert(Ty);
6287  } else if (Ty->isVectorType()) {
6288    // We treat vector types as arithmetic types in many contexts as an
6289    // extension.
6290    HasArithmeticOrEnumeralTypes = true;
6291    VectorTypes.insert(Ty);
6292  } else if (Ty->isNullPtrType()) {
6293    HasNullPtrType = true;
6294  } else if (AllowUserConversions && TyRec) {
6295    // No conversion functions in incomplete types.
6296    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6297      return;
6298
6299    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6300    std::pair<CXXRecordDecl::conversion_iterator,
6301              CXXRecordDecl::conversion_iterator>
6302      Conversions = ClassDecl->getVisibleConversionFunctions();
6303    for (CXXRecordDecl::conversion_iterator
6304           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6305      NamedDecl *D = I.getDecl();
6306      if (isa<UsingShadowDecl>(D))
6307        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6308
6309      // Skip conversion function templates; they don't tell us anything
6310      // about which builtin types we can convert to.
6311      if (isa<FunctionTemplateDecl>(D))
6312        continue;
6313
6314      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6315      if (AllowExplicitConversions || !Conv->isExplicit()) {
6316        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6317                              VisibleQuals);
6318      }
6319    }
6320  }
6321}
6322
6323/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6324/// the volatile- and non-volatile-qualified assignment operators for the
6325/// given type to the candidate set.
6326static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6327                                                   QualType T,
6328                                                   Expr **Args,
6329                                                   unsigned NumArgs,
6330                                    OverloadCandidateSet &CandidateSet) {
6331  QualType ParamTypes[2];
6332
6333  // T& operator=(T&, T)
6334  ParamTypes[0] = S.Context.getLValueReferenceType(T);
6335  ParamTypes[1] = T;
6336  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6337                        /*IsAssignmentOperator=*/true);
6338
6339  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6340    // volatile T& operator=(volatile T&, T)
6341    ParamTypes[0]
6342      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6343    ParamTypes[1] = T;
6344    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6345                          /*IsAssignmentOperator=*/true);
6346  }
6347}
6348
6349/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6350/// if any, found in visible type conversion functions found in ArgExpr's type.
6351static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6352    Qualifiers VRQuals;
6353    const RecordType *TyRec;
6354    if (const MemberPointerType *RHSMPType =
6355        ArgExpr->getType()->getAs<MemberPointerType>())
6356      TyRec = RHSMPType->getClass()->getAs<RecordType>();
6357    else
6358      TyRec = ArgExpr->getType()->getAs<RecordType>();
6359    if (!TyRec) {
6360      // Just to be safe, assume the worst case.
6361      VRQuals.addVolatile();
6362      VRQuals.addRestrict();
6363      return VRQuals;
6364    }
6365
6366    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6367    if (!ClassDecl->hasDefinition())
6368      return VRQuals;
6369
6370    std::pair<CXXRecordDecl::conversion_iterator,
6371              CXXRecordDecl::conversion_iterator>
6372      Conversions = ClassDecl->getVisibleConversionFunctions();
6373
6374    for (CXXRecordDecl::conversion_iterator
6375           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6376      NamedDecl *D = I.getDecl();
6377      if (isa<UsingShadowDecl>(D))
6378        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6379      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6380        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6381        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6382          CanTy = ResTypeRef->getPointeeType();
6383        // Need to go down the pointer/mempointer chain and add qualifiers
6384        // as see them.
6385        bool done = false;
6386        while (!done) {
6387          if (CanTy.isRestrictQualified())
6388            VRQuals.addRestrict();
6389          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6390            CanTy = ResTypePtr->getPointeeType();
6391          else if (const MemberPointerType *ResTypeMPtr =
6392                CanTy->getAs<MemberPointerType>())
6393            CanTy = ResTypeMPtr->getPointeeType();
6394          else
6395            done = true;
6396          if (CanTy.isVolatileQualified())
6397            VRQuals.addVolatile();
6398          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6399            return VRQuals;
6400        }
6401      }
6402    }
6403    return VRQuals;
6404}
6405
6406namespace {
6407
6408/// \brief Helper class to manage the addition of builtin operator overload
6409/// candidates. It provides shared state and utility methods used throughout
6410/// the process, as well as a helper method to add each group of builtin
6411/// operator overloads from the standard to a candidate set.
6412class BuiltinOperatorOverloadBuilder {
6413  // Common instance state available to all overload candidate addition methods.
6414  Sema &S;
6415  Expr **Args;
6416  unsigned NumArgs;
6417  Qualifiers VisibleTypeConversionsQuals;
6418  bool HasArithmeticOrEnumeralCandidateType;
6419  SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6420  OverloadCandidateSet &CandidateSet;
6421
6422  // Define some constants used to index and iterate over the arithemetic types
6423  // provided via the getArithmeticType() method below.
6424  // The "promoted arithmetic types" are the arithmetic
6425  // types are that preserved by promotion (C++ [over.built]p2).
6426  static const unsigned FirstIntegralType = 3;
6427  static const unsigned LastIntegralType = 20;
6428  static const unsigned FirstPromotedIntegralType = 3,
6429                        LastPromotedIntegralType = 11;
6430  static const unsigned FirstPromotedArithmeticType = 0,
6431                        LastPromotedArithmeticType = 11;
6432  static const unsigned NumArithmeticTypes = 20;
6433
6434  /// \brief Get the canonical type for a given arithmetic type index.
6435  CanQualType getArithmeticType(unsigned index) {
6436    assert(index < NumArithmeticTypes);
6437    static CanQualType ASTContext::* const
6438      ArithmeticTypes[NumArithmeticTypes] = {
6439      // Start of promoted types.
6440      &ASTContext::FloatTy,
6441      &ASTContext::DoubleTy,
6442      &ASTContext::LongDoubleTy,
6443
6444      // Start of integral types.
6445      &ASTContext::IntTy,
6446      &ASTContext::LongTy,
6447      &ASTContext::LongLongTy,
6448      &ASTContext::Int128Ty,
6449      &ASTContext::UnsignedIntTy,
6450      &ASTContext::UnsignedLongTy,
6451      &ASTContext::UnsignedLongLongTy,
6452      &ASTContext::UnsignedInt128Ty,
6453      // End of promoted types.
6454
6455      &ASTContext::BoolTy,
6456      &ASTContext::CharTy,
6457      &ASTContext::WCharTy,
6458      &ASTContext::Char16Ty,
6459      &ASTContext::Char32Ty,
6460      &ASTContext::SignedCharTy,
6461      &ASTContext::ShortTy,
6462      &ASTContext::UnsignedCharTy,
6463      &ASTContext::UnsignedShortTy,
6464      // End of integral types.
6465      // FIXME: What about complex? What about half?
6466    };
6467    return S.Context.*ArithmeticTypes[index];
6468  }
6469
6470  /// \brief Gets the canonical type resulting from the usual arithemetic
6471  /// converions for the given arithmetic types.
6472  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6473    // Accelerator table for performing the usual arithmetic conversions.
6474    // The rules are basically:
6475    //   - if either is floating-point, use the wider floating-point
6476    //   - if same signedness, use the higher rank
6477    //   - if same size, use unsigned of the higher rank
6478    //   - use the larger type
6479    // These rules, together with the axiom that higher ranks are
6480    // never smaller, are sufficient to precompute all of these results
6481    // *except* when dealing with signed types of higher rank.
6482    // (we could precompute SLL x UI for all known platforms, but it's
6483    // better not to make any assumptions).
6484    // We assume that int128 has a higher rank than long long on all platforms.
6485    enum PromotedType {
6486            Dep=-1,
6487            Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6488    };
6489    static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6490                                        [LastPromotedArithmeticType] = {
6491/* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6492/* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6493/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6494/*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6495/*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6496/* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6497/*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6498/*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6499/*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6500/* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6501/*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6502    };
6503
6504    assert(L < LastPromotedArithmeticType);
6505    assert(R < LastPromotedArithmeticType);
6506    int Idx = ConversionsTable[L][R];
6507
6508    // Fast path: the table gives us a concrete answer.
6509    if (Idx != Dep) return getArithmeticType(Idx);
6510
6511    // Slow path: we need to compare widths.
6512    // An invariant is that the signed type has higher rank.
6513    CanQualType LT = getArithmeticType(L),
6514                RT = getArithmeticType(R);
6515    unsigned LW = S.Context.getIntWidth(LT),
6516             RW = S.Context.getIntWidth(RT);
6517
6518    // If they're different widths, use the signed type.
6519    if (LW > RW) return LT;
6520    else if (LW < RW) return RT;
6521
6522    // Otherwise, use the unsigned type of the signed type's rank.
6523    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6524    assert(L == SLL || R == SLL);
6525    return S.Context.UnsignedLongLongTy;
6526  }
6527
6528  /// \brief Helper method to factor out the common pattern of adding overloads
6529  /// for '++' and '--' builtin operators.
6530  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6531                                           bool HasVolatile,
6532                                           bool HasRestrict) {
6533    QualType ParamTypes[2] = {
6534      S.Context.getLValueReferenceType(CandidateTy),
6535      S.Context.IntTy
6536    };
6537
6538    // Non-volatile version.
6539    if (NumArgs == 1)
6540      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6541    else
6542      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6543
6544    // Use a heuristic to reduce number of builtin candidates in the set:
6545    // add volatile version only if there are conversions to a volatile type.
6546    if (HasVolatile) {
6547      ParamTypes[0] =
6548        S.Context.getLValueReferenceType(
6549          S.Context.getVolatileType(CandidateTy));
6550      if (NumArgs == 1)
6551        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6552      else
6553        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6554    }
6555
6556    // Add restrict version only if there are conversions to a restrict type
6557    // and our candidate type is a non-restrict-qualified pointer.
6558    if (HasRestrict && CandidateTy->isAnyPointerType() &&
6559        !CandidateTy.isRestrictQualified()) {
6560      ParamTypes[0]
6561        = S.Context.getLValueReferenceType(
6562            S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6563      if (NumArgs == 1)
6564        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6565      else
6566        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6567
6568      if (HasVolatile) {
6569        ParamTypes[0]
6570          = S.Context.getLValueReferenceType(
6571              S.Context.getCVRQualifiedType(CandidateTy,
6572                                            (Qualifiers::Volatile |
6573                                             Qualifiers::Restrict)));
6574        if (NumArgs == 1)
6575          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6576                                CandidateSet);
6577        else
6578          S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6579      }
6580    }
6581
6582  }
6583
6584public:
6585  BuiltinOperatorOverloadBuilder(
6586    Sema &S, Expr **Args, unsigned NumArgs,
6587    Qualifiers VisibleTypeConversionsQuals,
6588    bool HasArithmeticOrEnumeralCandidateType,
6589    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6590    OverloadCandidateSet &CandidateSet)
6591    : S(S), Args(Args), NumArgs(NumArgs),
6592      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6593      HasArithmeticOrEnumeralCandidateType(
6594        HasArithmeticOrEnumeralCandidateType),
6595      CandidateTypes(CandidateTypes),
6596      CandidateSet(CandidateSet) {
6597    // Validate some of our static helper constants in debug builds.
6598    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6599           "Invalid first promoted integral type");
6600    assert(getArithmeticType(LastPromotedIntegralType - 1)
6601             == S.Context.UnsignedInt128Ty &&
6602           "Invalid last promoted integral type");
6603    assert(getArithmeticType(FirstPromotedArithmeticType)
6604             == S.Context.FloatTy &&
6605           "Invalid first promoted arithmetic type");
6606    assert(getArithmeticType(LastPromotedArithmeticType - 1)
6607             == S.Context.UnsignedInt128Ty &&
6608           "Invalid last promoted arithmetic type");
6609  }
6610
6611  // C++ [over.built]p3:
6612  //
6613  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6614  //   is either volatile or empty, there exist candidate operator
6615  //   functions of the form
6616  //
6617  //       VQ T&      operator++(VQ T&);
6618  //       T          operator++(VQ T&, int);
6619  //
6620  // C++ [over.built]p4:
6621  //
6622  //   For every pair (T, VQ), where T is an arithmetic type other
6623  //   than bool, and VQ is either volatile or empty, there exist
6624  //   candidate operator functions of the form
6625  //
6626  //       VQ T&      operator--(VQ T&);
6627  //       T          operator--(VQ T&, int);
6628  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6629    if (!HasArithmeticOrEnumeralCandidateType)
6630      return;
6631
6632    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6633         Arith < NumArithmeticTypes; ++Arith) {
6634      addPlusPlusMinusMinusStyleOverloads(
6635        getArithmeticType(Arith),
6636        VisibleTypeConversionsQuals.hasVolatile(),
6637        VisibleTypeConversionsQuals.hasRestrict());
6638    }
6639  }
6640
6641  // C++ [over.built]p5:
6642  //
6643  //   For every pair (T, VQ), where T is a cv-qualified or
6644  //   cv-unqualified object type, and VQ is either volatile or
6645  //   empty, there exist candidate operator functions of the form
6646  //
6647  //       T*VQ&      operator++(T*VQ&);
6648  //       T*VQ&      operator--(T*VQ&);
6649  //       T*         operator++(T*VQ&, int);
6650  //       T*         operator--(T*VQ&, int);
6651  void addPlusPlusMinusMinusPointerOverloads() {
6652    for (BuiltinCandidateTypeSet::iterator
6653              Ptr = CandidateTypes[0].pointer_begin(),
6654           PtrEnd = CandidateTypes[0].pointer_end();
6655         Ptr != PtrEnd; ++Ptr) {
6656      // Skip pointer types that aren't pointers to object types.
6657      if (!(*Ptr)->getPointeeType()->isObjectType())
6658        continue;
6659
6660      addPlusPlusMinusMinusStyleOverloads(*Ptr,
6661        (!(*Ptr).isVolatileQualified() &&
6662         VisibleTypeConversionsQuals.hasVolatile()),
6663        (!(*Ptr).isRestrictQualified() &&
6664         VisibleTypeConversionsQuals.hasRestrict()));
6665    }
6666  }
6667
6668  // C++ [over.built]p6:
6669  //   For every cv-qualified or cv-unqualified object type T, there
6670  //   exist candidate operator functions of the form
6671  //
6672  //       T&         operator*(T*);
6673  //
6674  // C++ [over.built]p7:
6675  //   For every function type T that does not have cv-qualifiers or a
6676  //   ref-qualifier, there exist candidate operator functions of the form
6677  //       T&         operator*(T*);
6678  void addUnaryStarPointerOverloads() {
6679    for (BuiltinCandidateTypeSet::iterator
6680              Ptr = CandidateTypes[0].pointer_begin(),
6681           PtrEnd = CandidateTypes[0].pointer_end();
6682         Ptr != PtrEnd; ++Ptr) {
6683      QualType ParamTy = *Ptr;
6684      QualType PointeeTy = ParamTy->getPointeeType();
6685      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6686        continue;
6687
6688      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6689        if (Proto->getTypeQuals() || Proto->getRefQualifier())
6690          continue;
6691
6692      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6693                            &ParamTy, Args, 1, CandidateSet);
6694    }
6695  }
6696
6697  // C++ [over.built]p9:
6698  //  For every promoted arithmetic type T, there exist candidate
6699  //  operator functions of the form
6700  //
6701  //       T         operator+(T);
6702  //       T         operator-(T);
6703  void addUnaryPlusOrMinusArithmeticOverloads() {
6704    if (!HasArithmeticOrEnumeralCandidateType)
6705      return;
6706
6707    for (unsigned Arith = FirstPromotedArithmeticType;
6708         Arith < LastPromotedArithmeticType; ++Arith) {
6709      QualType ArithTy = getArithmeticType(Arith);
6710      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6711    }
6712
6713    // Extension: We also add these operators for vector types.
6714    for (BuiltinCandidateTypeSet::iterator
6715              Vec = CandidateTypes[0].vector_begin(),
6716           VecEnd = CandidateTypes[0].vector_end();
6717         Vec != VecEnd; ++Vec) {
6718      QualType VecTy = *Vec;
6719      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6720    }
6721  }
6722
6723  // C++ [over.built]p8:
6724  //   For every type T, there exist candidate operator functions of
6725  //   the form
6726  //
6727  //       T*         operator+(T*);
6728  void addUnaryPlusPointerOverloads() {
6729    for (BuiltinCandidateTypeSet::iterator
6730              Ptr = CandidateTypes[0].pointer_begin(),
6731           PtrEnd = CandidateTypes[0].pointer_end();
6732         Ptr != PtrEnd; ++Ptr) {
6733      QualType ParamTy = *Ptr;
6734      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6735    }
6736  }
6737
6738  // C++ [over.built]p10:
6739  //   For every promoted integral type T, there exist candidate
6740  //   operator functions of the form
6741  //
6742  //        T         operator~(T);
6743  void addUnaryTildePromotedIntegralOverloads() {
6744    if (!HasArithmeticOrEnumeralCandidateType)
6745      return;
6746
6747    for (unsigned Int = FirstPromotedIntegralType;
6748         Int < LastPromotedIntegralType; ++Int) {
6749      QualType IntTy = getArithmeticType(Int);
6750      S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6751    }
6752
6753    // Extension: We also add this operator for vector types.
6754    for (BuiltinCandidateTypeSet::iterator
6755              Vec = CandidateTypes[0].vector_begin(),
6756           VecEnd = CandidateTypes[0].vector_end();
6757         Vec != VecEnd; ++Vec) {
6758      QualType VecTy = *Vec;
6759      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6760    }
6761  }
6762
6763  // C++ [over.match.oper]p16:
6764  //   For every pointer to member type T, there exist candidate operator
6765  //   functions of the form
6766  //
6767  //        bool operator==(T,T);
6768  //        bool operator!=(T,T);
6769  void addEqualEqualOrNotEqualMemberPointerOverloads() {
6770    /// Set of (canonical) types that we've already handled.
6771    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6772
6773    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6774      for (BuiltinCandidateTypeSet::iterator
6775                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6776             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6777           MemPtr != MemPtrEnd;
6778           ++MemPtr) {
6779        // Don't add the same builtin candidate twice.
6780        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6781          continue;
6782
6783        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6784        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6785                              CandidateSet);
6786      }
6787    }
6788  }
6789
6790  // C++ [over.built]p15:
6791  //
6792  //   For every T, where T is an enumeration type, a pointer type, or
6793  //   std::nullptr_t, there exist candidate operator functions of the form
6794  //
6795  //        bool       operator<(T, T);
6796  //        bool       operator>(T, T);
6797  //        bool       operator<=(T, T);
6798  //        bool       operator>=(T, T);
6799  //        bool       operator==(T, T);
6800  //        bool       operator!=(T, T);
6801  void addRelationalPointerOrEnumeralOverloads() {
6802    // C++ [over.match.oper]p3:
6803    //   [...]the built-in candidates include all of the candidate operator
6804    //   functions defined in 13.6 that, compared to the given operator, [...]
6805    //   do not have the same parameter-type-list as any non-template non-member
6806    //   candidate.
6807    //
6808    // Note that in practice, this only affects enumeration types because there
6809    // aren't any built-in candidates of record type, and a user-defined operator
6810    // must have an operand of record or enumeration type. Also, the only other
6811    // overloaded operator with enumeration arguments, operator=,
6812    // cannot be overloaded for enumeration types, so this is the only place
6813    // where we must suppress candidates like this.
6814    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6815      UserDefinedBinaryOperators;
6816
6817    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6818      if (CandidateTypes[ArgIdx].enumeration_begin() !=
6819          CandidateTypes[ArgIdx].enumeration_end()) {
6820        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6821                                         CEnd = CandidateSet.end();
6822             C != CEnd; ++C) {
6823          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6824            continue;
6825
6826          if (C->Function->isFunctionTemplateSpecialization())
6827            continue;
6828
6829          QualType FirstParamType =
6830            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6831          QualType SecondParamType =
6832            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6833
6834          // Skip if either parameter isn't of enumeral type.
6835          if (!FirstParamType->isEnumeralType() ||
6836              !SecondParamType->isEnumeralType())
6837            continue;
6838
6839          // Add this operator to the set of known user-defined operators.
6840          UserDefinedBinaryOperators.insert(
6841            std::make_pair(S.Context.getCanonicalType(FirstParamType),
6842                           S.Context.getCanonicalType(SecondParamType)));
6843        }
6844      }
6845    }
6846
6847    /// Set of (canonical) types that we've already handled.
6848    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6849
6850    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6851      for (BuiltinCandidateTypeSet::iterator
6852                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6853             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6854           Ptr != PtrEnd; ++Ptr) {
6855        // Don't add the same builtin candidate twice.
6856        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6857          continue;
6858
6859        QualType ParamTypes[2] = { *Ptr, *Ptr };
6860        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6861                              CandidateSet);
6862      }
6863      for (BuiltinCandidateTypeSet::iterator
6864                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6865             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6866           Enum != EnumEnd; ++Enum) {
6867        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6868
6869        // Don't add the same builtin candidate twice, or if a user defined
6870        // candidate exists.
6871        if (!AddedTypes.insert(CanonType) ||
6872            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6873                                                            CanonType)))
6874          continue;
6875
6876        QualType ParamTypes[2] = { *Enum, *Enum };
6877        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6878                              CandidateSet);
6879      }
6880
6881      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6882        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6883        if (AddedTypes.insert(NullPtrTy) &&
6884            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6885                                                             NullPtrTy))) {
6886          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6887          S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6888                                CandidateSet);
6889        }
6890      }
6891    }
6892  }
6893
6894  // C++ [over.built]p13:
6895  //
6896  //   For every cv-qualified or cv-unqualified object type T
6897  //   there exist candidate operator functions of the form
6898  //
6899  //      T*         operator+(T*, ptrdiff_t);
6900  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
6901  //      T*         operator-(T*, ptrdiff_t);
6902  //      T*         operator+(ptrdiff_t, T*);
6903  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
6904  //
6905  // C++ [over.built]p14:
6906  //
6907  //   For every T, where T is a pointer to object type, there
6908  //   exist candidate operator functions of the form
6909  //
6910  //      ptrdiff_t  operator-(T, T);
6911  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6912    /// Set of (canonical) types that we've already handled.
6913    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6914
6915    for (int Arg = 0; Arg < 2; ++Arg) {
6916      QualType AsymetricParamTypes[2] = {
6917        S.Context.getPointerDiffType(),
6918        S.Context.getPointerDiffType(),
6919      };
6920      for (BuiltinCandidateTypeSet::iterator
6921                Ptr = CandidateTypes[Arg].pointer_begin(),
6922             PtrEnd = CandidateTypes[Arg].pointer_end();
6923           Ptr != PtrEnd; ++Ptr) {
6924        QualType PointeeTy = (*Ptr)->getPointeeType();
6925        if (!PointeeTy->isObjectType())
6926          continue;
6927
6928        AsymetricParamTypes[Arg] = *Ptr;
6929        if (Arg == 0 || Op == OO_Plus) {
6930          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6931          // T* operator+(ptrdiff_t, T*);
6932          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6933                                CandidateSet);
6934        }
6935        if (Op == OO_Minus) {
6936          // ptrdiff_t operator-(T, T);
6937          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6938            continue;
6939
6940          QualType ParamTypes[2] = { *Ptr, *Ptr };
6941          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6942                                Args, 2, CandidateSet);
6943        }
6944      }
6945    }
6946  }
6947
6948  // C++ [over.built]p12:
6949  //
6950  //   For every pair of promoted arithmetic types L and R, there
6951  //   exist candidate operator functions of the form
6952  //
6953  //        LR         operator*(L, R);
6954  //        LR         operator/(L, R);
6955  //        LR         operator+(L, R);
6956  //        LR         operator-(L, R);
6957  //        bool       operator<(L, R);
6958  //        bool       operator>(L, R);
6959  //        bool       operator<=(L, R);
6960  //        bool       operator>=(L, R);
6961  //        bool       operator==(L, R);
6962  //        bool       operator!=(L, R);
6963  //
6964  //   where LR is the result of the usual arithmetic conversions
6965  //   between types L and R.
6966  //
6967  // C++ [over.built]p24:
6968  //
6969  //   For every pair of promoted arithmetic types L and R, there exist
6970  //   candidate operator functions of the form
6971  //
6972  //        LR       operator?(bool, L, R);
6973  //
6974  //   where LR is the result of the usual arithmetic conversions
6975  //   between types L and R.
6976  // Our candidates ignore the first parameter.
6977  void addGenericBinaryArithmeticOverloads(bool isComparison) {
6978    if (!HasArithmeticOrEnumeralCandidateType)
6979      return;
6980
6981    for (unsigned Left = FirstPromotedArithmeticType;
6982         Left < LastPromotedArithmeticType; ++Left) {
6983      for (unsigned Right = FirstPromotedArithmeticType;
6984           Right < LastPromotedArithmeticType; ++Right) {
6985        QualType LandR[2] = { getArithmeticType(Left),
6986                              getArithmeticType(Right) };
6987        QualType Result =
6988          isComparison ? S.Context.BoolTy
6989                       : getUsualArithmeticConversions(Left, Right);
6990        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6991      }
6992    }
6993
6994    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6995    // conditional operator for vector types.
6996    for (BuiltinCandidateTypeSet::iterator
6997              Vec1 = CandidateTypes[0].vector_begin(),
6998           Vec1End = CandidateTypes[0].vector_end();
6999         Vec1 != Vec1End; ++Vec1) {
7000      for (BuiltinCandidateTypeSet::iterator
7001                Vec2 = CandidateTypes[1].vector_begin(),
7002             Vec2End = CandidateTypes[1].vector_end();
7003           Vec2 != Vec2End; ++Vec2) {
7004        QualType LandR[2] = { *Vec1, *Vec2 };
7005        QualType Result = S.Context.BoolTy;
7006        if (!isComparison) {
7007          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7008            Result = *Vec1;
7009          else
7010            Result = *Vec2;
7011        }
7012
7013        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7014      }
7015    }
7016  }
7017
7018  // C++ [over.built]p17:
7019  //
7020  //   For every pair of promoted integral types L and R, there
7021  //   exist candidate operator functions of the form
7022  //
7023  //      LR         operator%(L, R);
7024  //      LR         operator&(L, R);
7025  //      LR         operator^(L, R);
7026  //      LR         operator|(L, R);
7027  //      L          operator<<(L, R);
7028  //      L          operator>>(L, R);
7029  //
7030  //   where LR is the result of the usual arithmetic conversions
7031  //   between types L and R.
7032  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7033    if (!HasArithmeticOrEnumeralCandidateType)
7034      return;
7035
7036    for (unsigned Left = FirstPromotedIntegralType;
7037         Left < LastPromotedIntegralType; ++Left) {
7038      for (unsigned Right = FirstPromotedIntegralType;
7039           Right < LastPromotedIntegralType; ++Right) {
7040        QualType LandR[2] = { getArithmeticType(Left),
7041                              getArithmeticType(Right) };
7042        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7043            ? LandR[0]
7044            : getUsualArithmeticConversions(Left, Right);
7045        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7046      }
7047    }
7048  }
7049
7050  // C++ [over.built]p20:
7051  //
7052  //   For every pair (T, VQ), where T is an enumeration or
7053  //   pointer to member type and VQ is either volatile or
7054  //   empty, there exist candidate operator functions of the form
7055  //
7056  //        VQ T&      operator=(VQ T&, T);
7057  void addAssignmentMemberPointerOrEnumeralOverloads() {
7058    /// Set of (canonical) types that we've already handled.
7059    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7060
7061    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7062      for (BuiltinCandidateTypeSet::iterator
7063                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7064             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7065           Enum != EnumEnd; ++Enum) {
7066        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7067          continue;
7068
7069        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7070                                               CandidateSet);
7071      }
7072
7073      for (BuiltinCandidateTypeSet::iterator
7074                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7075             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7076           MemPtr != MemPtrEnd; ++MemPtr) {
7077        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7078          continue;
7079
7080        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7081                                               CandidateSet);
7082      }
7083    }
7084  }
7085
7086  // C++ [over.built]p19:
7087  //
7088  //   For every pair (T, VQ), where T is any type and VQ is either
7089  //   volatile or empty, there exist candidate operator functions
7090  //   of the form
7091  //
7092  //        T*VQ&      operator=(T*VQ&, T*);
7093  //
7094  // C++ [over.built]p21:
7095  //
7096  //   For every pair (T, VQ), where T is a cv-qualified or
7097  //   cv-unqualified object type and VQ is either volatile or
7098  //   empty, there exist candidate operator functions of the form
7099  //
7100  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7101  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7102  void addAssignmentPointerOverloads(bool isEqualOp) {
7103    /// Set of (canonical) types that we've already handled.
7104    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7105
7106    for (BuiltinCandidateTypeSet::iterator
7107              Ptr = CandidateTypes[0].pointer_begin(),
7108           PtrEnd = CandidateTypes[0].pointer_end();
7109         Ptr != PtrEnd; ++Ptr) {
7110      // If this is operator=, keep track of the builtin candidates we added.
7111      if (isEqualOp)
7112        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7113      else if (!(*Ptr)->getPointeeType()->isObjectType())
7114        continue;
7115
7116      // non-volatile version
7117      QualType ParamTypes[2] = {
7118        S.Context.getLValueReferenceType(*Ptr),
7119        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7120      };
7121      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7122                            /*IsAssigmentOperator=*/ isEqualOp);
7123
7124      bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7125                          VisibleTypeConversionsQuals.hasVolatile();
7126      if (NeedVolatile) {
7127        // volatile version
7128        ParamTypes[0] =
7129          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7130        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7131                              /*IsAssigmentOperator=*/isEqualOp);
7132      }
7133
7134      if (!(*Ptr).isRestrictQualified() &&
7135          VisibleTypeConversionsQuals.hasRestrict()) {
7136        // restrict version
7137        ParamTypes[0]
7138          = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7139        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7140                              /*IsAssigmentOperator=*/isEqualOp);
7141
7142        if (NeedVolatile) {
7143          // volatile restrict version
7144          ParamTypes[0]
7145            = S.Context.getLValueReferenceType(
7146                S.Context.getCVRQualifiedType(*Ptr,
7147                                              (Qualifiers::Volatile |
7148                                               Qualifiers::Restrict)));
7149          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7150                                CandidateSet,
7151                                /*IsAssigmentOperator=*/isEqualOp);
7152        }
7153      }
7154    }
7155
7156    if (isEqualOp) {
7157      for (BuiltinCandidateTypeSet::iterator
7158                Ptr = CandidateTypes[1].pointer_begin(),
7159             PtrEnd = CandidateTypes[1].pointer_end();
7160           Ptr != PtrEnd; ++Ptr) {
7161        // Make sure we don't add the same candidate twice.
7162        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7163          continue;
7164
7165        QualType ParamTypes[2] = {
7166          S.Context.getLValueReferenceType(*Ptr),
7167          *Ptr,
7168        };
7169
7170        // non-volatile version
7171        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7172                              /*IsAssigmentOperator=*/true);
7173
7174        bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7175                           VisibleTypeConversionsQuals.hasVolatile();
7176        if (NeedVolatile) {
7177          // volatile version
7178          ParamTypes[0] =
7179            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7180          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7181                                CandidateSet, /*IsAssigmentOperator=*/true);
7182        }
7183
7184        if (!(*Ptr).isRestrictQualified() &&
7185            VisibleTypeConversionsQuals.hasRestrict()) {
7186          // restrict version
7187          ParamTypes[0]
7188            = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7189          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7190                                CandidateSet, /*IsAssigmentOperator=*/true);
7191
7192          if (NeedVolatile) {
7193            // volatile restrict version
7194            ParamTypes[0]
7195              = S.Context.getLValueReferenceType(
7196                  S.Context.getCVRQualifiedType(*Ptr,
7197                                                (Qualifiers::Volatile |
7198                                                 Qualifiers::Restrict)));
7199            S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7200                                  CandidateSet, /*IsAssigmentOperator=*/true);
7201
7202          }
7203        }
7204      }
7205    }
7206  }
7207
7208  // C++ [over.built]p18:
7209  //
7210  //   For every triple (L, VQ, R), where L is an arithmetic type,
7211  //   VQ is either volatile or empty, and R is a promoted
7212  //   arithmetic type, there exist candidate operator functions of
7213  //   the form
7214  //
7215  //        VQ L&      operator=(VQ L&, R);
7216  //        VQ L&      operator*=(VQ L&, R);
7217  //        VQ L&      operator/=(VQ L&, R);
7218  //        VQ L&      operator+=(VQ L&, R);
7219  //        VQ L&      operator-=(VQ L&, R);
7220  void addAssignmentArithmeticOverloads(bool isEqualOp) {
7221    if (!HasArithmeticOrEnumeralCandidateType)
7222      return;
7223
7224    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7225      for (unsigned Right = FirstPromotedArithmeticType;
7226           Right < LastPromotedArithmeticType; ++Right) {
7227        QualType ParamTypes[2];
7228        ParamTypes[1] = getArithmeticType(Right);
7229
7230        // Add this built-in operator as a candidate (VQ is empty).
7231        ParamTypes[0] =
7232          S.Context.getLValueReferenceType(getArithmeticType(Left));
7233        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7234                              /*IsAssigmentOperator=*/isEqualOp);
7235
7236        // Add this built-in operator as a candidate (VQ is 'volatile').
7237        if (VisibleTypeConversionsQuals.hasVolatile()) {
7238          ParamTypes[0] =
7239            S.Context.getVolatileType(getArithmeticType(Left));
7240          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7241          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7242                                CandidateSet,
7243                                /*IsAssigmentOperator=*/isEqualOp);
7244        }
7245      }
7246    }
7247
7248    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7249    for (BuiltinCandidateTypeSet::iterator
7250              Vec1 = CandidateTypes[0].vector_begin(),
7251           Vec1End = CandidateTypes[0].vector_end();
7252         Vec1 != Vec1End; ++Vec1) {
7253      for (BuiltinCandidateTypeSet::iterator
7254                Vec2 = CandidateTypes[1].vector_begin(),
7255             Vec2End = CandidateTypes[1].vector_end();
7256           Vec2 != Vec2End; ++Vec2) {
7257        QualType ParamTypes[2];
7258        ParamTypes[1] = *Vec2;
7259        // Add this built-in operator as a candidate (VQ is empty).
7260        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7261        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7262                              /*IsAssigmentOperator=*/isEqualOp);
7263
7264        // Add this built-in operator as a candidate (VQ is 'volatile').
7265        if (VisibleTypeConversionsQuals.hasVolatile()) {
7266          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7267          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7268          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7269                                CandidateSet,
7270                                /*IsAssigmentOperator=*/isEqualOp);
7271        }
7272      }
7273    }
7274  }
7275
7276  // C++ [over.built]p22:
7277  //
7278  //   For every triple (L, VQ, R), where L is an integral type, VQ
7279  //   is either volatile or empty, and R is a promoted integral
7280  //   type, there exist candidate operator functions of the form
7281  //
7282  //        VQ L&       operator%=(VQ L&, R);
7283  //        VQ L&       operator<<=(VQ L&, R);
7284  //        VQ L&       operator>>=(VQ L&, R);
7285  //        VQ L&       operator&=(VQ L&, R);
7286  //        VQ L&       operator^=(VQ L&, R);
7287  //        VQ L&       operator|=(VQ L&, R);
7288  void addAssignmentIntegralOverloads() {
7289    if (!HasArithmeticOrEnumeralCandidateType)
7290      return;
7291
7292    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7293      for (unsigned Right = FirstPromotedIntegralType;
7294           Right < LastPromotedIntegralType; ++Right) {
7295        QualType ParamTypes[2];
7296        ParamTypes[1] = getArithmeticType(Right);
7297
7298        // Add this built-in operator as a candidate (VQ is empty).
7299        ParamTypes[0] =
7300          S.Context.getLValueReferenceType(getArithmeticType(Left));
7301        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7302        if (VisibleTypeConversionsQuals.hasVolatile()) {
7303          // Add this built-in operator as a candidate (VQ is 'volatile').
7304          ParamTypes[0] = getArithmeticType(Left);
7305          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7306          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7307          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7308                                CandidateSet);
7309        }
7310      }
7311    }
7312  }
7313
7314  // C++ [over.operator]p23:
7315  //
7316  //   There also exist candidate operator functions of the form
7317  //
7318  //        bool        operator!(bool);
7319  //        bool        operator&&(bool, bool);
7320  //        bool        operator||(bool, bool);
7321  void addExclaimOverload() {
7322    QualType ParamTy = S.Context.BoolTy;
7323    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7324                          /*IsAssignmentOperator=*/false,
7325                          /*NumContextualBoolArguments=*/1);
7326  }
7327  void addAmpAmpOrPipePipeOverload() {
7328    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7329    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7330                          /*IsAssignmentOperator=*/false,
7331                          /*NumContextualBoolArguments=*/2);
7332  }
7333
7334  // C++ [over.built]p13:
7335  //
7336  //   For every cv-qualified or cv-unqualified object type T there
7337  //   exist candidate operator functions of the form
7338  //
7339  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7340  //        T&         operator[](T*, ptrdiff_t);
7341  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7342  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7343  //        T&         operator[](ptrdiff_t, T*);
7344  void addSubscriptOverloads() {
7345    for (BuiltinCandidateTypeSet::iterator
7346              Ptr = CandidateTypes[0].pointer_begin(),
7347           PtrEnd = CandidateTypes[0].pointer_end();
7348         Ptr != PtrEnd; ++Ptr) {
7349      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7350      QualType PointeeType = (*Ptr)->getPointeeType();
7351      if (!PointeeType->isObjectType())
7352        continue;
7353
7354      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7355
7356      // T& operator[](T*, ptrdiff_t)
7357      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7358    }
7359
7360    for (BuiltinCandidateTypeSet::iterator
7361              Ptr = CandidateTypes[1].pointer_begin(),
7362           PtrEnd = CandidateTypes[1].pointer_end();
7363         Ptr != PtrEnd; ++Ptr) {
7364      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7365      QualType PointeeType = (*Ptr)->getPointeeType();
7366      if (!PointeeType->isObjectType())
7367        continue;
7368
7369      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7370
7371      // T& operator[](ptrdiff_t, T*)
7372      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7373    }
7374  }
7375
7376  // C++ [over.built]p11:
7377  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7378  //    C1 is the same type as C2 or is a derived class of C2, T is an object
7379  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7380  //    there exist candidate operator functions of the form
7381  //
7382  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7383  //
7384  //    where CV12 is the union of CV1 and CV2.
7385  void addArrowStarOverloads() {
7386    for (BuiltinCandidateTypeSet::iterator
7387             Ptr = CandidateTypes[0].pointer_begin(),
7388           PtrEnd = CandidateTypes[0].pointer_end();
7389         Ptr != PtrEnd; ++Ptr) {
7390      QualType C1Ty = (*Ptr);
7391      QualType C1;
7392      QualifierCollector Q1;
7393      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7394      if (!isa<RecordType>(C1))
7395        continue;
7396      // heuristic to reduce number of builtin candidates in the set.
7397      // Add volatile/restrict version only if there are conversions to a
7398      // volatile/restrict type.
7399      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7400        continue;
7401      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7402        continue;
7403      for (BuiltinCandidateTypeSet::iterator
7404                MemPtr = CandidateTypes[1].member_pointer_begin(),
7405             MemPtrEnd = CandidateTypes[1].member_pointer_end();
7406           MemPtr != MemPtrEnd; ++MemPtr) {
7407        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7408        QualType C2 = QualType(mptr->getClass(), 0);
7409        C2 = C2.getUnqualifiedType();
7410        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7411          break;
7412        QualType ParamTypes[2] = { *Ptr, *MemPtr };
7413        // build CV12 T&
7414        QualType T = mptr->getPointeeType();
7415        if (!VisibleTypeConversionsQuals.hasVolatile() &&
7416            T.isVolatileQualified())
7417          continue;
7418        if (!VisibleTypeConversionsQuals.hasRestrict() &&
7419            T.isRestrictQualified())
7420          continue;
7421        T = Q1.apply(S.Context, T);
7422        QualType ResultTy = S.Context.getLValueReferenceType(T);
7423        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7424      }
7425    }
7426  }
7427
7428  // Note that we don't consider the first argument, since it has been
7429  // contextually converted to bool long ago. The candidates below are
7430  // therefore added as binary.
7431  //
7432  // C++ [over.built]p25:
7433  //   For every type T, where T is a pointer, pointer-to-member, or scoped
7434  //   enumeration type, there exist candidate operator functions of the form
7435  //
7436  //        T        operator?(bool, T, T);
7437  //
7438  void addConditionalOperatorOverloads() {
7439    /// Set of (canonical) types that we've already handled.
7440    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7441
7442    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7443      for (BuiltinCandidateTypeSet::iterator
7444                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7445             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7446           Ptr != PtrEnd; ++Ptr) {
7447        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7448          continue;
7449
7450        QualType ParamTypes[2] = { *Ptr, *Ptr };
7451        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7452      }
7453
7454      for (BuiltinCandidateTypeSet::iterator
7455                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7456             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7457           MemPtr != MemPtrEnd; ++MemPtr) {
7458        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7459          continue;
7460
7461        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7462        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7463      }
7464
7465      if (S.getLangOpts().CPlusPlus11) {
7466        for (BuiltinCandidateTypeSet::iterator
7467                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7468               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7469             Enum != EnumEnd; ++Enum) {
7470          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7471            continue;
7472
7473          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7474            continue;
7475
7476          QualType ParamTypes[2] = { *Enum, *Enum };
7477          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7478        }
7479      }
7480    }
7481  }
7482};
7483
7484} // end anonymous namespace
7485
7486/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7487/// operator overloads to the candidate set (C++ [over.built]), based
7488/// on the operator @p Op and the arguments given. For example, if the
7489/// operator is a binary '+', this routine might add "int
7490/// operator+(int, int)" to cover integer addition.
7491void
7492Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7493                                   SourceLocation OpLoc,
7494                                   Expr **Args, unsigned NumArgs,
7495                                   OverloadCandidateSet& CandidateSet) {
7496  // Find all of the types that the arguments can convert to, but only
7497  // if the operator we're looking at has built-in operator candidates
7498  // that make use of these types. Also record whether we encounter non-record
7499  // candidate types or either arithmetic or enumeral candidate types.
7500  Qualifiers VisibleTypeConversionsQuals;
7501  VisibleTypeConversionsQuals.addConst();
7502  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7503    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7504
7505  bool HasNonRecordCandidateType = false;
7506  bool HasArithmeticOrEnumeralCandidateType = false;
7507  SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7508  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7509    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7510    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7511                                                 OpLoc,
7512                                                 true,
7513                                                 (Op == OO_Exclaim ||
7514                                                  Op == OO_AmpAmp ||
7515                                                  Op == OO_PipePipe),
7516                                                 VisibleTypeConversionsQuals);
7517    HasNonRecordCandidateType = HasNonRecordCandidateType ||
7518        CandidateTypes[ArgIdx].hasNonRecordTypes();
7519    HasArithmeticOrEnumeralCandidateType =
7520        HasArithmeticOrEnumeralCandidateType ||
7521        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7522  }
7523
7524  // Exit early when no non-record types have been added to the candidate set
7525  // for any of the arguments to the operator.
7526  //
7527  // We can't exit early for !, ||, or &&, since there we have always have
7528  // 'bool' overloads.
7529  if (!HasNonRecordCandidateType &&
7530      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7531    return;
7532
7533  // Setup an object to manage the common state for building overloads.
7534  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7535                                           VisibleTypeConversionsQuals,
7536                                           HasArithmeticOrEnumeralCandidateType,
7537                                           CandidateTypes, CandidateSet);
7538
7539  // Dispatch over the operation to add in only those overloads which apply.
7540  switch (Op) {
7541  case OO_None:
7542  case NUM_OVERLOADED_OPERATORS:
7543    llvm_unreachable("Expected an overloaded operator");
7544
7545  case OO_New:
7546  case OO_Delete:
7547  case OO_Array_New:
7548  case OO_Array_Delete:
7549  case OO_Call:
7550    llvm_unreachable(
7551                    "Special operators don't use AddBuiltinOperatorCandidates");
7552
7553  case OO_Comma:
7554  case OO_Arrow:
7555    // C++ [over.match.oper]p3:
7556    //   -- For the operator ',', the unary operator '&', or the
7557    //      operator '->', the built-in candidates set is empty.
7558    break;
7559
7560  case OO_Plus: // '+' is either unary or binary
7561    if (NumArgs == 1)
7562      OpBuilder.addUnaryPlusPointerOverloads();
7563    // Fall through.
7564
7565  case OO_Minus: // '-' is either unary or binary
7566    if (NumArgs == 1) {
7567      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7568    } else {
7569      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7570      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7571    }
7572    break;
7573
7574  case OO_Star: // '*' is either unary or binary
7575    if (NumArgs == 1)
7576      OpBuilder.addUnaryStarPointerOverloads();
7577    else
7578      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7579    break;
7580
7581  case OO_Slash:
7582    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7583    break;
7584
7585  case OO_PlusPlus:
7586  case OO_MinusMinus:
7587    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7588    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7589    break;
7590
7591  case OO_EqualEqual:
7592  case OO_ExclaimEqual:
7593    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7594    // Fall through.
7595
7596  case OO_Less:
7597  case OO_Greater:
7598  case OO_LessEqual:
7599  case OO_GreaterEqual:
7600    OpBuilder.addRelationalPointerOrEnumeralOverloads();
7601    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7602    break;
7603
7604  case OO_Percent:
7605  case OO_Caret:
7606  case OO_Pipe:
7607  case OO_LessLess:
7608  case OO_GreaterGreater:
7609    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7610    break;
7611
7612  case OO_Amp: // '&' is either unary or binary
7613    if (NumArgs == 1)
7614      // C++ [over.match.oper]p3:
7615      //   -- For the operator ',', the unary operator '&', or the
7616      //      operator '->', the built-in candidates set is empty.
7617      break;
7618
7619    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7620    break;
7621
7622  case OO_Tilde:
7623    OpBuilder.addUnaryTildePromotedIntegralOverloads();
7624    break;
7625
7626  case OO_Equal:
7627    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7628    // Fall through.
7629
7630  case OO_PlusEqual:
7631  case OO_MinusEqual:
7632    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7633    // Fall through.
7634
7635  case OO_StarEqual:
7636  case OO_SlashEqual:
7637    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7638    break;
7639
7640  case OO_PercentEqual:
7641  case OO_LessLessEqual:
7642  case OO_GreaterGreaterEqual:
7643  case OO_AmpEqual:
7644  case OO_CaretEqual:
7645  case OO_PipeEqual:
7646    OpBuilder.addAssignmentIntegralOverloads();
7647    break;
7648
7649  case OO_Exclaim:
7650    OpBuilder.addExclaimOverload();
7651    break;
7652
7653  case OO_AmpAmp:
7654  case OO_PipePipe:
7655    OpBuilder.addAmpAmpOrPipePipeOverload();
7656    break;
7657
7658  case OO_Subscript:
7659    OpBuilder.addSubscriptOverloads();
7660    break;
7661
7662  case OO_ArrowStar:
7663    OpBuilder.addArrowStarOverloads();
7664    break;
7665
7666  case OO_Conditional:
7667    OpBuilder.addConditionalOperatorOverloads();
7668    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7669    break;
7670  }
7671}
7672
7673/// \brief Add function candidates found via argument-dependent lookup
7674/// to the set of overloading candidates.
7675///
7676/// This routine performs argument-dependent name lookup based on the
7677/// given function name (which may also be an operator name) and adds
7678/// all of the overload candidates found by ADL to the overload
7679/// candidate set (C++ [basic.lookup.argdep]).
7680void
7681Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7682                                           bool Operator, SourceLocation Loc,
7683                                           llvm::ArrayRef<Expr *> Args,
7684                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7685                                           OverloadCandidateSet& CandidateSet,
7686                                           bool PartialOverloading) {
7687  ADLResult Fns;
7688
7689  // FIXME: This approach for uniquing ADL results (and removing
7690  // redundant candidates from the set) relies on pointer-equality,
7691  // which means we need to key off the canonical decl.  However,
7692  // always going back to the canonical decl might not get us the
7693  // right set of default arguments.  What default arguments are
7694  // we supposed to consider on ADL candidates, anyway?
7695
7696  // FIXME: Pass in the explicit template arguments?
7697  ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
7698
7699  // Erase all of the candidates we already knew about.
7700  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7701                                   CandEnd = CandidateSet.end();
7702       Cand != CandEnd; ++Cand)
7703    if (Cand->Function) {
7704      Fns.erase(Cand->Function);
7705      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7706        Fns.erase(FunTmpl);
7707    }
7708
7709  // For each of the ADL candidates we found, add it to the overload
7710  // set.
7711  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7712    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7713    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7714      if (ExplicitTemplateArgs)
7715        continue;
7716
7717      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7718                           PartialOverloading);
7719    } else
7720      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7721                                   FoundDecl, ExplicitTemplateArgs,
7722                                   Args, CandidateSet);
7723  }
7724}
7725
7726/// isBetterOverloadCandidate - Determines whether the first overload
7727/// candidate is a better candidate than the second (C++ 13.3.3p1).
7728bool
7729isBetterOverloadCandidate(Sema &S,
7730                          const OverloadCandidate &Cand1,
7731                          const OverloadCandidate &Cand2,
7732                          SourceLocation Loc,
7733                          bool UserDefinedConversion) {
7734  // Define viable functions to be better candidates than non-viable
7735  // functions.
7736  if (!Cand2.Viable)
7737    return Cand1.Viable;
7738  else if (!Cand1.Viable)
7739    return false;
7740
7741  // C++ [over.match.best]p1:
7742  //
7743  //   -- if F is a static member function, ICS1(F) is defined such
7744  //      that ICS1(F) is neither better nor worse than ICS1(G) for
7745  //      any function G, and, symmetrically, ICS1(G) is neither
7746  //      better nor worse than ICS1(F).
7747  unsigned StartArg = 0;
7748  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7749    StartArg = 1;
7750
7751  // C++ [over.match.best]p1:
7752  //   A viable function F1 is defined to be a better function than another
7753  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7754  //   conversion sequence than ICSi(F2), and then...
7755  unsigned NumArgs = Cand1.NumConversions;
7756  assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7757  bool HasBetterConversion = false;
7758  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7759    switch (CompareImplicitConversionSequences(S,
7760                                               Cand1.Conversions[ArgIdx],
7761                                               Cand2.Conversions[ArgIdx])) {
7762    case ImplicitConversionSequence::Better:
7763      // Cand1 has a better conversion sequence.
7764      HasBetterConversion = true;
7765      break;
7766
7767    case ImplicitConversionSequence::Worse:
7768      // Cand1 can't be better than Cand2.
7769      return false;
7770
7771    case ImplicitConversionSequence::Indistinguishable:
7772      // Do nothing.
7773      break;
7774    }
7775  }
7776
7777  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7778  //       ICSj(F2), or, if not that,
7779  if (HasBetterConversion)
7780    return true;
7781
7782  //     - F1 is a non-template function and F2 is a function template
7783  //       specialization, or, if not that,
7784  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7785      Cand2.Function && Cand2.Function->getPrimaryTemplate())
7786    return true;
7787
7788  //   -- F1 and F2 are function template specializations, and the function
7789  //      template for F1 is more specialized than the template for F2
7790  //      according to the partial ordering rules described in 14.5.5.2, or,
7791  //      if not that,
7792  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7793      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7794    if (FunctionTemplateDecl *BetterTemplate
7795          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7796                                         Cand2.Function->getPrimaryTemplate(),
7797                                         Loc,
7798                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7799                                                             : TPOC_Call,
7800                                         Cand1.ExplicitCallArguments))
7801      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7802  }
7803
7804  //   -- the context is an initialization by user-defined conversion
7805  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7806  //      from the return type of F1 to the destination type (i.e.,
7807  //      the type of the entity being initialized) is a better
7808  //      conversion sequence than the standard conversion sequence
7809  //      from the return type of F2 to the destination type.
7810  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7811      isa<CXXConversionDecl>(Cand1.Function) &&
7812      isa<CXXConversionDecl>(Cand2.Function)) {
7813    // First check whether we prefer one of the conversion functions over the
7814    // other. This only distinguishes the results in non-standard, extension
7815    // cases such as the conversion from a lambda closure type to a function
7816    // pointer or block.
7817    ImplicitConversionSequence::CompareKind FuncResult
7818      = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7819    if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7820      return FuncResult;
7821
7822    switch (CompareStandardConversionSequences(S,
7823                                               Cand1.FinalConversion,
7824                                               Cand2.FinalConversion)) {
7825    case ImplicitConversionSequence::Better:
7826      // Cand1 has a better conversion sequence.
7827      return true;
7828
7829    case ImplicitConversionSequence::Worse:
7830      // Cand1 can't be better than Cand2.
7831      return false;
7832
7833    case ImplicitConversionSequence::Indistinguishable:
7834      // Do nothing
7835      break;
7836    }
7837  }
7838
7839  return false;
7840}
7841
7842/// \brief Computes the best viable function (C++ 13.3.3)
7843/// within an overload candidate set.
7844///
7845/// \param Loc The location of the function name (or operator symbol) for
7846/// which overload resolution occurs.
7847///
7848/// \param Best If overload resolution was successful or found a deleted
7849/// function, \p Best points to the candidate function found.
7850///
7851/// \returns The result of overload resolution.
7852OverloadingResult
7853OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
7854                                         iterator &Best,
7855                                         bool UserDefinedConversion) {
7856  // Find the best viable function.
7857  Best = end();
7858  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7859    if (Cand->Viable)
7860      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
7861                                                     UserDefinedConversion))
7862        Best = Cand;
7863  }
7864
7865  // If we didn't find any viable functions, abort.
7866  if (Best == end())
7867    return OR_No_Viable_Function;
7868
7869  // Make sure that this function is better than every other viable
7870  // function. If not, we have an ambiguity.
7871  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7872    if (Cand->Viable &&
7873        Cand != Best &&
7874        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
7875                                   UserDefinedConversion)) {
7876      Best = end();
7877      return OR_Ambiguous;
7878    }
7879  }
7880
7881  // Best is the best viable function.
7882  if (Best->Function &&
7883      (Best->Function->isDeleted() ||
7884       S.isFunctionConsideredUnavailable(Best->Function)))
7885    return OR_Deleted;
7886
7887  return OR_Success;
7888}
7889
7890namespace {
7891
7892enum OverloadCandidateKind {
7893  oc_function,
7894  oc_method,
7895  oc_constructor,
7896  oc_function_template,
7897  oc_method_template,
7898  oc_constructor_template,
7899  oc_implicit_default_constructor,
7900  oc_implicit_copy_constructor,
7901  oc_implicit_move_constructor,
7902  oc_implicit_copy_assignment,
7903  oc_implicit_move_assignment,
7904  oc_implicit_inherited_constructor
7905};
7906
7907OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7908                                                FunctionDecl *Fn,
7909                                                std::string &Description) {
7910  bool isTemplate = false;
7911
7912  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7913    isTemplate = true;
7914    Description = S.getTemplateArgumentBindingsText(
7915      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7916  }
7917
7918  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
7919    if (!Ctor->isImplicit())
7920      return isTemplate ? oc_constructor_template : oc_constructor;
7921
7922    if (Ctor->getInheritedConstructor())
7923      return oc_implicit_inherited_constructor;
7924
7925    if (Ctor->isDefaultConstructor())
7926      return oc_implicit_default_constructor;
7927
7928    if (Ctor->isMoveConstructor())
7929      return oc_implicit_move_constructor;
7930
7931    assert(Ctor->isCopyConstructor() &&
7932           "unexpected sort of implicit constructor");
7933    return oc_implicit_copy_constructor;
7934  }
7935
7936  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7937    // This actually gets spelled 'candidate function' for now, but
7938    // it doesn't hurt to split it out.
7939    if (!Meth->isImplicit())
7940      return isTemplate ? oc_method_template : oc_method;
7941
7942    if (Meth->isMoveAssignmentOperator())
7943      return oc_implicit_move_assignment;
7944
7945    if (Meth->isCopyAssignmentOperator())
7946      return oc_implicit_copy_assignment;
7947
7948    assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7949    return oc_method;
7950  }
7951
7952  return isTemplate ? oc_function_template : oc_function;
7953}
7954
7955void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7956  const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7957  if (!Ctor) return;
7958
7959  Ctor = Ctor->getInheritedConstructor();
7960  if (!Ctor) return;
7961
7962  S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7963}
7964
7965} // end anonymous namespace
7966
7967// Notes the location of an overload candidate.
7968void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
7969  std::string FnDesc;
7970  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
7971  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7972                             << (unsigned) K << FnDesc;
7973  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7974  Diag(Fn->getLocation(), PD);
7975  MaybeEmitInheritedConstructorNote(*this, Fn);
7976}
7977
7978//Notes the location of all overload candidates designated through
7979// OverloadedExpr
7980void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
7981  assert(OverloadedExpr->getType() == Context.OverloadTy);
7982
7983  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7984  OverloadExpr *OvlExpr = Ovl.Expression;
7985
7986  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7987                            IEnd = OvlExpr->decls_end();
7988       I != IEnd; ++I) {
7989    if (FunctionTemplateDecl *FunTmpl =
7990                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
7991      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
7992    } else if (FunctionDecl *Fun
7993                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
7994      NoteOverloadCandidate(Fun, DestType);
7995    }
7996  }
7997}
7998
7999/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8000/// "lead" diagnostic; it will be given two arguments, the source and
8001/// target types of the conversion.
8002void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8003                                 Sema &S,
8004                                 SourceLocation CaretLoc,
8005                                 const PartialDiagnostic &PDiag) const {
8006  S.Diag(CaretLoc, PDiag)
8007    << Ambiguous.getFromType() << Ambiguous.getToType();
8008  // FIXME: The note limiting machinery is borrowed from
8009  // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8010  // refactoring here.
8011  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8012  unsigned CandsShown = 0;
8013  AmbiguousConversionSequence::const_iterator I, E;
8014  for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8015    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8016      break;
8017    ++CandsShown;
8018    S.NoteOverloadCandidate(*I);
8019  }
8020  if (I != E)
8021    S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8022}
8023
8024namespace {
8025
8026void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8027  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8028  assert(Conv.isBad());
8029  assert(Cand->Function && "for now, candidate must be a function");
8030  FunctionDecl *Fn = Cand->Function;
8031
8032  // There's a conversion slot for the object argument if this is a
8033  // non-constructor method.  Note that 'I' corresponds the
8034  // conversion-slot index.
8035  bool isObjectArgument = false;
8036  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8037    if (I == 0)
8038      isObjectArgument = true;
8039    else
8040      I--;
8041  }
8042
8043  std::string FnDesc;
8044  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8045
8046  Expr *FromExpr = Conv.Bad.FromExpr;
8047  QualType FromTy = Conv.Bad.getFromType();
8048  QualType ToTy = Conv.Bad.getToType();
8049
8050  if (FromTy == S.Context.OverloadTy) {
8051    assert(FromExpr && "overload set argument came from implicit argument?");
8052    Expr *E = FromExpr->IgnoreParens();
8053    if (isa<UnaryOperator>(E))
8054      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8055    DeclarationName Name = cast<OverloadExpr>(E)->getName();
8056
8057    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8058      << (unsigned) FnKind << FnDesc
8059      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8060      << ToTy << Name << I+1;
8061    MaybeEmitInheritedConstructorNote(S, Fn);
8062    return;
8063  }
8064
8065  // Do some hand-waving analysis to see if the non-viability is due
8066  // to a qualifier mismatch.
8067  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8068  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8069  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8070    CToTy = RT->getPointeeType();
8071  else {
8072    // TODO: detect and diagnose the full richness of const mismatches.
8073    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8074      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8075        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8076  }
8077
8078  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8079      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8080    Qualifiers FromQs = CFromTy.getQualifiers();
8081    Qualifiers ToQs = CToTy.getQualifiers();
8082
8083    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8084      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8085        << (unsigned) FnKind << FnDesc
8086        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8087        << FromTy
8088        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8089        << (unsigned) isObjectArgument << I+1;
8090      MaybeEmitInheritedConstructorNote(S, Fn);
8091      return;
8092    }
8093
8094    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8095      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8096        << (unsigned) FnKind << FnDesc
8097        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8098        << FromTy
8099        << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8100        << (unsigned) isObjectArgument << I+1;
8101      MaybeEmitInheritedConstructorNote(S, Fn);
8102      return;
8103    }
8104
8105    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8106      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8107      << (unsigned) FnKind << FnDesc
8108      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8109      << FromTy
8110      << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8111      << (unsigned) isObjectArgument << I+1;
8112      MaybeEmitInheritedConstructorNote(S, Fn);
8113      return;
8114    }
8115
8116    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8117    assert(CVR && "unexpected qualifiers mismatch");
8118
8119    if (isObjectArgument) {
8120      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8121        << (unsigned) FnKind << FnDesc
8122        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8123        << FromTy << (CVR - 1);
8124    } else {
8125      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8126        << (unsigned) FnKind << FnDesc
8127        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8128        << FromTy << (CVR - 1) << I+1;
8129    }
8130    MaybeEmitInheritedConstructorNote(S, Fn);
8131    return;
8132  }
8133
8134  // Special diagnostic for failure to convert an initializer list, since
8135  // telling the user that it has type void is not useful.
8136  if (FromExpr && isa<InitListExpr>(FromExpr)) {
8137    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8138      << (unsigned) FnKind << FnDesc
8139      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8140      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8141    MaybeEmitInheritedConstructorNote(S, Fn);
8142    return;
8143  }
8144
8145  // Diagnose references or pointers to incomplete types differently,
8146  // since it's far from impossible that the incompleteness triggered
8147  // the failure.
8148  QualType TempFromTy = FromTy.getNonReferenceType();
8149  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8150    TempFromTy = PTy->getPointeeType();
8151  if (TempFromTy->isIncompleteType()) {
8152    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8153      << (unsigned) FnKind << FnDesc
8154      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8155      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8156    MaybeEmitInheritedConstructorNote(S, Fn);
8157    return;
8158  }
8159
8160  // Diagnose base -> derived pointer conversions.
8161  unsigned BaseToDerivedConversion = 0;
8162  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8163    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8164      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8165                                               FromPtrTy->getPointeeType()) &&
8166          !FromPtrTy->getPointeeType()->isIncompleteType() &&
8167          !ToPtrTy->getPointeeType()->isIncompleteType() &&
8168          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8169                          FromPtrTy->getPointeeType()))
8170        BaseToDerivedConversion = 1;
8171    }
8172  } else if (const ObjCObjectPointerType *FromPtrTy
8173                                    = FromTy->getAs<ObjCObjectPointerType>()) {
8174    if (const ObjCObjectPointerType *ToPtrTy
8175                                        = ToTy->getAs<ObjCObjectPointerType>())
8176      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8177        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8178          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8179                                                FromPtrTy->getPointeeType()) &&
8180              FromIface->isSuperClassOf(ToIface))
8181            BaseToDerivedConversion = 2;
8182  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8183    if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8184        !FromTy->isIncompleteType() &&
8185        !ToRefTy->getPointeeType()->isIncompleteType() &&
8186        S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8187      BaseToDerivedConversion = 3;
8188    } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8189               ToTy.getNonReferenceType().getCanonicalType() ==
8190               FromTy.getNonReferenceType().getCanonicalType()) {
8191      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8192        << (unsigned) FnKind << FnDesc
8193        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8194        << (unsigned) isObjectArgument << I + 1;
8195      MaybeEmitInheritedConstructorNote(S, Fn);
8196      return;
8197    }
8198  }
8199
8200  if (BaseToDerivedConversion) {
8201    S.Diag(Fn->getLocation(),
8202           diag::note_ovl_candidate_bad_base_to_derived_conv)
8203      << (unsigned) FnKind << FnDesc
8204      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8205      << (BaseToDerivedConversion - 1)
8206      << FromTy << ToTy << I+1;
8207    MaybeEmitInheritedConstructorNote(S, Fn);
8208    return;
8209  }
8210
8211  if (isa<ObjCObjectPointerType>(CFromTy) &&
8212      isa<PointerType>(CToTy)) {
8213      Qualifiers FromQs = CFromTy.getQualifiers();
8214      Qualifiers ToQs = CToTy.getQualifiers();
8215      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8216        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8217        << (unsigned) FnKind << FnDesc
8218        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8219        << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8220        MaybeEmitInheritedConstructorNote(S, Fn);
8221        return;
8222      }
8223  }
8224
8225  // Emit the generic diagnostic and, optionally, add the hints to it.
8226  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8227  FDiag << (unsigned) FnKind << FnDesc
8228    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8229    << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8230    << (unsigned) (Cand->Fix.Kind);
8231
8232  // If we can fix the conversion, suggest the FixIts.
8233  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8234       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8235    FDiag << *HI;
8236  S.Diag(Fn->getLocation(), FDiag);
8237
8238  MaybeEmitInheritedConstructorNote(S, Fn);
8239}
8240
8241void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8242                           unsigned NumFormalArgs) {
8243  // TODO: treat calls to a missing default constructor as a special case
8244
8245  FunctionDecl *Fn = Cand->Function;
8246  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8247
8248  unsigned MinParams = Fn->getMinRequiredArguments();
8249
8250  // With invalid overloaded operators, it's possible that we think we
8251  // have an arity mismatch when it fact it looks like we have the
8252  // right number of arguments, because only overloaded operators have
8253  // the weird behavior of overloading member and non-member functions.
8254  // Just don't report anything.
8255  if (Fn->isInvalidDecl() &&
8256      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8257    return;
8258
8259  // at least / at most / exactly
8260  unsigned mode, modeCount;
8261  if (NumFormalArgs < MinParams) {
8262    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8263           (Cand->FailureKind == ovl_fail_bad_deduction &&
8264            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8265    if (MinParams != FnTy->getNumArgs() ||
8266        FnTy->isVariadic() || FnTy->isTemplateVariadic())
8267      mode = 0; // "at least"
8268    else
8269      mode = 2; // "exactly"
8270    modeCount = MinParams;
8271  } else {
8272    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8273           (Cand->FailureKind == ovl_fail_bad_deduction &&
8274            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8275    if (MinParams != FnTy->getNumArgs())
8276      mode = 1; // "at most"
8277    else
8278      mode = 2; // "exactly"
8279    modeCount = FnTy->getNumArgs();
8280  }
8281
8282  std::string Description;
8283  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8284
8285  if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8286    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8287      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8288      << Fn->getParamDecl(0) << NumFormalArgs;
8289  else
8290    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8291      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8292      << modeCount << NumFormalArgs;
8293  MaybeEmitInheritedConstructorNote(S, Fn);
8294}
8295
8296/// Diagnose a failed template-argument deduction.
8297void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8298                          unsigned NumArgs) {
8299  FunctionDecl *Fn = Cand->Function; // pattern
8300
8301  TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
8302  NamedDecl *ParamD;
8303  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8304  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8305  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8306  switch (Cand->DeductionFailure.Result) {
8307  case Sema::TDK_Success:
8308    llvm_unreachable("TDK_success while diagnosing bad deduction");
8309
8310  case Sema::TDK_Incomplete: {
8311    assert(ParamD && "no parameter found for incomplete deduction result");
8312    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8313      << ParamD->getDeclName();
8314    MaybeEmitInheritedConstructorNote(S, Fn);
8315    return;
8316  }
8317
8318  case Sema::TDK_Underqualified: {
8319    assert(ParamD && "no parameter found for bad qualifiers deduction result");
8320    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8321
8322    QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8323
8324    // Param will have been canonicalized, but it should just be a
8325    // qualified version of ParamD, so move the qualifiers to that.
8326    QualifierCollector Qs;
8327    Qs.strip(Param);
8328    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8329    assert(S.Context.hasSameType(Param, NonCanonParam));
8330
8331    // Arg has also been canonicalized, but there's nothing we can do
8332    // about that.  It also doesn't matter as much, because it won't
8333    // have any template parameters in it (because deduction isn't
8334    // done on dependent types).
8335    QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8336
8337    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8338      << ParamD->getDeclName() << Arg << NonCanonParam;
8339    MaybeEmitInheritedConstructorNote(S, Fn);
8340    return;
8341  }
8342
8343  case Sema::TDK_Inconsistent: {
8344    assert(ParamD && "no parameter found for inconsistent deduction result");
8345    int which = 0;
8346    if (isa<TemplateTypeParmDecl>(ParamD))
8347      which = 0;
8348    else if (isa<NonTypeTemplateParmDecl>(ParamD))
8349      which = 1;
8350    else {
8351      which = 2;
8352    }
8353
8354    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8355      << which << ParamD->getDeclName()
8356      << *Cand->DeductionFailure.getFirstArg()
8357      << *Cand->DeductionFailure.getSecondArg();
8358    MaybeEmitInheritedConstructorNote(S, Fn);
8359    return;
8360  }
8361
8362  case Sema::TDK_InvalidExplicitArguments:
8363    assert(ParamD && "no parameter found for invalid explicit arguments");
8364    if (ParamD->getDeclName())
8365      S.Diag(Fn->getLocation(),
8366             diag::note_ovl_candidate_explicit_arg_mismatch_named)
8367        << ParamD->getDeclName();
8368    else {
8369      int index = 0;
8370      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8371        index = TTP->getIndex();
8372      else if (NonTypeTemplateParmDecl *NTTP
8373                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8374        index = NTTP->getIndex();
8375      else
8376        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8377      S.Diag(Fn->getLocation(),
8378             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8379        << (index + 1);
8380    }
8381    MaybeEmitInheritedConstructorNote(S, Fn);
8382    return;
8383
8384  case Sema::TDK_TooManyArguments:
8385  case Sema::TDK_TooFewArguments:
8386    DiagnoseArityMismatch(S, Cand, NumArgs);
8387    return;
8388
8389  case Sema::TDK_InstantiationDepth:
8390    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8391    MaybeEmitInheritedConstructorNote(S, Fn);
8392    return;
8393
8394  case Sema::TDK_SubstitutionFailure: {
8395    // Format the template argument list into the argument string.
8396    llvm::SmallString<128> TemplateArgString;
8397    if (TemplateArgumentList *Args =
8398          Cand->DeductionFailure.getTemplateArgumentList()) {
8399      TemplateArgString = " ";
8400      TemplateArgString += S.getTemplateArgumentBindingsText(
8401          Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8402    }
8403
8404    // If this candidate was disabled by enable_if, say so.
8405    PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8406    if (PDiag && PDiag->second.getDiagID() ==
8407          diag::err_typename_nested_not_found_enable_if) {
8408      // FIXME: Use the source range of the condition, and the fully-qualified
8409      //        name of the enable_if template. These are both present in PDiag.
8410      S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8411        << "'enable_if'" << TemplateArgString;
8412      return;
8413    }
8414
8415    // Format the SFINAE diagnostic into the argument string.
8416    // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8417    //        formatted message in another diagnostic.
8418    llvm::SmallString<128> SFINAEArgString;
8419    SourceRange R;
8420    if (PDiag) {
8421      SFINAEArgString = ": ";
8422      R = SourceRange(PDiag->first, PDiag->first);
8423      PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8424    }
8425
8426    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8427      << TemplateArgString << SFINAEArgString << R;
8428    MaybeEmitInheritedConstructorNote(S, Fn);
8429    return;
8430  }
8431
8432  // TODO: diagnose these individually, then kill off
8433  // note_ovl_candidate_bad_deduction, which is uselessly vague.
8434  case Sema::TDK_NonDeducedMismatch:
8435  case Sema::TDK_FailedOverloadResolution:
8436    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8437    MaybeEmitInheritedConstructorNote(S, Fn);
8438    return;
8439  }
8440}
8441
8442/// CUDA: diagnose an invalid call across targets.
8443void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8444  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8445  FunctionDecl *Callee = Cand->Function;
8446
8447  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8448                           CalleeTarget = S.IdentifyCUDATarget(Callee);
8449
8450  std::string FnDesc;
8451  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8452
8453  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8454      << (unsigned) FnKind << CalleeTarget << CallerTarget;
8455}
8456
8457/// Generates a 'note' diagnostic for an overload candidate.  We've
8458/// already generated a primary error at the call site.
8459///
8460/// It really does need to be a single diagnostic with its caret
8461/// pointed at the candidate declaration.  Yes, this creates some
8462/// major challenges of technical writing.  Yes, this makes pointing
8463/// out problems with specific arguments quite awkward.  It's still
8464/// better than generating twenty screens of text for every failed
8465/// overload.
8466///
8467/// It would be great to be able to express per-candidate problems
8468/// more richly for those diagnostic clients that cared, but we'd
8469/// still have to be just as careful with the default diagnostics.
8470void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8471                           unsigned NumArgs) {
8472  FunctionDecl *Fn = Cand->Function;
8473
8474  // Note deleted candidates, but only if they're viable.
8475  if (Cand->Viable && (Fn->isDeleted() ||
8476      S.isFunctionConsideredUnavailable(Fn))) {
8477    std::string FnDesc;
8478    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8479
8480    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8481      << FnKind << FnDesc
8482      << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8483    MaybeEmitInheritedConstructorNote(S, Fn);
8484    return;
8485  }
8486
8487  // We don't really have anything else to say about viable candidates.
8488  if (Cand->Viable) {
8489    S.NoteOverloadCandidate(Fn);
8490    return;
8491  }
8492
8493  switch (Cand->FailureKind) {
8494  case ovl_fail_too_many_arguments:
8495  case ovl_fail_too_few_arguments:
8496    return DiagnoseArityMismatch(S, Cand, NumArgs);
8497
8498  case ovl_fail_bad_deduction:
8499    return DiagnoseBadDeduction(S, Cand, NumArgs);
8500
8501  case ovl_fail_trivial_conversion:
8502  case ovl_fail_bad_final_conversion:
8503  case ovl_fail_final_conversion_not_exact:
8504    return S.NoteOverloadCandidate(Fn);
8505
8506  case ovl_fail_bad_conversion: {
8507    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8508    for (unsigned N = Cand->NumConversions; I != N; ++I)
8509      if (Cand->Conversions[I].isBad())
8510        return DiagnoseBadConversion(S, Cand, I);
8511
8512    // FIXME: this currently happens when we're called from SemaInit
8513    // when user-conversion overload fails.  Figure out how to handle
8514    // those conditions and diagnose them well.
8515    return S.NoteOverloadCandidate(Fn);
8516  }
8517
8518  case ovl_fail_bad_target:
8519    return DiagnoseBadTarget(S, Cand);
8520  }
8521}
8522
8523void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8524  // Desugar the type of the surrogate down to a function type,
8525  // retaining as many typedefs as possible while still showing
8526  // the function type (and, therefore, its parameter types).
8527  QualType FnType = Cand->Surrogate->getConversionType();
8528  bool isLValueReference = false;
8529  bool isRValueReference = false;
8530  bool isPointer = false;
8531  if (const LValueReferenceType *FnTypeRef =
8532        FnType->getAs<LValueReferenceType>()) {
8533    FnType = FnTypeRef->getPointeeType();
8534    isLValueReference = true;
8535  } else if (const RValueReferenceType *FnTypeRef =
8536               FnType->getAs<RValueReferenceType>()) {
8537    FnType = FnTypeRef->getPointeeType();
8538    isRValueReference = true;
8539  }
8540  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8541    FnType = FnTypePtr->getPointeeType();
8542    isPointer = true;
8543  }
8544  // Desugar down to a function type.
8545  FnType = QualType(FnType->getAs<FunctionType>(), 0);
8546  // Reconstruct the pointer/reference as appropriate.
8547  if (isPointer) FnType = S.Context.getPointerType(FnType);
8548  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8549  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8550
8551  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8552    << FnType;
8553  MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8554}
8555
8556void NoteBuiltinOperatorCandidate(Sema &S,
8557                                  StringRef Opc,
8558                                  SourceLocation OpLoc,
8559                                  OverloadCandidate *Cand) {
8560  assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8561  std::string TypeStr("operator");
8562  TypeStr += Opc;
8563  TypeStr += "(";
8564  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8565  if (Cand->NumConversions == 1) {
8566    TypeStr += ")";
8567    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8568  } else {
8569    TypeStr += ", ";
8570    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8571    TypeStr += ")";
8572    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8573  }
8574}
8575
8576void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8577                                  OverloadCandidate *Cand) {
8578  unsigned NoOperands = Cand->NumConversions;
8579  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8580    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8581    if (ICS.isBad()) break; // all meaningless after first invalid
8582    if (!ICS.isAmbiguous()) continue;
8583
8584    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8585                              S.PDiag(diag::note_ambiguous_type_conversion));
8586  }
8587}
8588
8589SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8590  if (Cand->Function)
8591    return Cand->Function->getLocation();
8592  if (Cand->IsSurrogate)
8593    return Cand->Surrogate->getLocation();
8594  return SourceLocation();
8595}
8596
8597static unsigned
8598RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8599  switch ((Sema::TemplateDeductionResult)DFI.Result) {
8600  case Sema::TDK_Success:
8601    llvm_unreachable("TDK_success while diagnosing bad deduction");
8602
8603  case Sema::TDK_Invalid:
8604  case Sema::TDK_Incomplete:
8605    return 1;
8606
8607  case Sema::TDK_Underqualified:
8608  case Sema::TDK_Inconsistent:
8609    return 2;
8610
8611  case Sema::TDK_SubstitutionFailure:
8612  case Sema::TDK_NonDeducedMismatch:
8613    return 3;
8614
8615  case Sema::TDK_InstantiationDepth:
8616  case Sema::TDK_FailedOverloadResolution:
8617    return 4;
8618
8619  case Sema::TDK_InvalidExplicitArguments:
8620    return 5;
8621
8622  case Sema::TDK_TooManyArguments:
8623  case Sema::TDK_TooFewArguments:
8624    return 6;
8625  }
8626  llvm_unreachable("Unhandled deduction result");
8627}
8628
8629struct CompareOverloadCandidatesForDisplay {
8630  Sema &S;
8631  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8632
8633  bool operator()(const OverloadCandidate *L,
8634                  const OverloadCandidate *R) {
8635    // Fast-path this check.
8636    if (L == R) return false;
8637
8638    // Order first by viability.
8639    if (L->Viable) {
8640      if (!R->Viable) return true;
8641
8642      // TODO: introduce a tri-valued comparison for overload
8643      // candidates.  Would be more worthwhile if we had a sort
8644      // that could exploit it.
8645      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8646      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8647    } else if (R->Viable)
8648      return false;
8649
8650    assert(L->Viable == R->Viable);
8651
8652    // Criteria by which we can sort non-viable candidates:
8653    if (!L->Viable) {
8654      // 1. Arity mismatches come after other candidates.
8655      if (L->FailureKind == ovl_fail_too_many_arguments ||
8656          L->FailureKind == ovl_fail_too_few_arguments)
8657        return false;
8658      if (R->FailureKind == ovl_fail_too_many_arguments ||
8659          R->FailureKind == ovl_fail_too_few_arguments)
8660        return true;
8661
8662      // 2. Bad conversions come first and are ordered by the number
8663      // of bad conversions and quality of good conversions.
8664      if (L->FailureKind == ovl_fail_bad_conversion) {
8665        if (R->FailureKind != ovl_fail_bad_conversion)
8666          return true;
8667
8668        // The conversion that can be fixed with a smaller number of changes,
8669        // comes first.
8670        unsigned numLFixes = L->Fix.NumConversionsFixed;
8671        unsigned numRFixes = R->Fix.NumConversionsFixed;
8672        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8673        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8674        if (numLFixes != numRFixes) {
8675          if (numLFixes < numRFixes)
8676            return true;
8677          else
8678            return false;
8679        }
8680
8681        // If there's any ordering between the defined conversions...
8682        // FIXME: this might not be transitive.
8683        assert(L->NumConversions == R->NumConversions);
8684
8685        int leftBetter = 0;
8686        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8687        for (unsigned E = L->NumConversions; I != E; ++I) {
8688          switch (CompareImplicitConversionSequences(S,
8689                                                     L->Conversions[I],
8690                                                     R->Conversions[I])) {
8691          case ImplicitConversionSequence::Better:
8692            leftBetter++;
8693            break;
8694
8695          case ImplicitConversionSequence::Worse:
8696            leftBetter--;
8697            break;
8698
8699          case ImplicitConversionSequence::Indistinguishable:
8700            break;
8701          }
8702        }
8703        if (leftBetter > 0) return true;
8704        if (leftBetter < 0) return false;
8705
8706      } else if (R->FailureKind == ovl_fail_bad_conversion)
8707        return false;
8708
8709      if (L->FailureKind == ovl_fail_bad_deduction) {
8710        if (R->FailureKind != ovl_fail_bad_deduction)
8711          return true;
8712
8713        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8714          return RankDeductionFailure(L->DeductionFailure)
8715               < RankDeductionFailure(R->DeductionFailure);
8716      } else if (R->FailureKind == ovl_fail_bad_deduction)
8717        return false;
8718
8719      // TODO: others?
8720    }
8721
8722    // Sort everything else by location.
8723    SourceLocation LLoc = GetLocationForCandidate(L);
8724    SourceLocation RLoc = GetLocationForCandidate(R);
8725
8726    // Put candidates without locations (e.g. builtins) at the end.
8727    if (LLoc.isInvalid()) return false;
8728    if (RLoc.isInvalid()) return true;
8729
8730    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8731  }
8732};
8733
8734/// CompleteNonViableCandidate - Normally, overload resolution only
8735/// computes up to the first. Produces the FixIt set if possible.
8736void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8737                                llvm::ArrayRef<Expr *> Args) {
8738  assert(!Cand->Viable);
8739
8740  // Don't do anything on failures other than bad conversion.
8741  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8742
8743  // We only want the FixIts if all the arguments can be corrected.
8744  bool Unfixable = false;
8745  // Use a implicit copy initialization to check conversion fixes.
8746  Cand->Fix.setConversionChecker(TryCopyInitialization);
8747
8748  // Skip forward to the first bad conversion.
8749  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
8750  unsigned ConvCount = Cand->NumConversions;
8751  while (true) {
8752    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8753    ConvIdx++;
8754    if (Cand->Conversions[ConvIdx - 1].isBad()) {
8755      Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
8756      break;
8757    }
8758  }
8759
8760  if (ConvIdx == ConvCount)
8761    return;
8762
8763  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8764         "remaining conversion is initialized?");
8765
8766  // FIXME: this should probably be preserved from the overload
8767  // operation somehow.
8768  bool SuppressUserConversions = false;
8769
8770  const FunctionProtoType* Proto;
8771  unsigned ArgIdx = ConvIdx;
8772
8773  if (Cand->IsSurrogate) {
8774    QualType ConvType
8775      = Cand->Surrogate->getConversionType().getNonReferenceType();
8776    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8777      ConvType = ConvPtrType->getPointeeType();
8778    Proto = ConvType->getAs<FunctionProtoType>();
8779    ArgIdx--;
8780  } else if (Cand->Function) {
8781    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8782    if (isa<CXXMethodDecl>(Cand->Function) &&
8783        !isa<CXXConstructorDecl>(Cand->Function))
8784      ArgIdx--;
8785  } else {
8786    // Builtin binary operator with a bad first conversion.
8787    assert(ConvCount <= 3);
8788    for (; ConvIdx != ConvCount; ++ConvIdx)
8789      Cand->Conversions[ConvIdx]
8790        = TryCopyInitialization(S, Args[ConvIdx],
8791                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
8792                                SuppressUserConversions,
8793                                /*InOverloadResolution*/ true,
8794                                /*AllowObjCWritebackConversion=*/
8795                                  S.getLangOpts().ObjCAutoRefCount);
8796    return;
8797  }
8798
8799  // Fill in the rest of the conversions.
8800  unsigned NumArgsInProto = Proto->getNumArgs();
8801  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
8802    if (ArgIdx < NumArgsInProto) {
8803      Cand->Conversions[ConvIdx]
8804        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
8805                                SuppressUserConversions,
8806                                /*InOverloadResolution=*/true,
8807                                /*AllowObjCWritebackConversion=*/
8808                                  S.getLangOpts().ObjCAutoRefCount);
8809      // Store the FixIt in the candidate if it exists.
8810      if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
8811        Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
8812    }
8813    else
8814      Cand->Conversions[ConvIdx].setEllipsis();
8815  }
8816}
8817
8818} // end anonymous namespace
8819
8820/// PrintOverloadCandidates - When overload resolution fails, prints
8821/// diagnostic messages containing the candidates in the candidate
8822/// set.
8823void OverloadCandidateSet::NoteCandidates(Sema &S,
8824                                          OverloadCandidateDisplayKind OCD,
8825                                          llvm::ArrayRef<Expr *> Args,
8826                                          StringRef Opc,
8827                                          SourceLocation OpLoc) {
8828  // Sort the candidates by viability and position.  Sorting directly would
8829  // be prohibitive, so we make a set of pointers and sort those.
8830  SmallVector<OverloadCandidate*, 32> Cands;
8831  if (OCD == OCD_AllCandidates) Cands.reserve(size());
8832  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
8833    if (Cand->Viable)
8834      Cands.push_back(Cand);
8835    else if (OCD == OCD_AllCandidates) {
8836      CompleteNonViableCandidate(S, Cand, Args);
8837      if (Cand->Function || Cand->IsSurrogate)
8838        Cands.push_back(Cand);
8839      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
8840      // want to list every possible builtin candidate.
8841    }
8842  }
8843
8844  std::sort(Cands.begin(), Cands.end(),
8845            CompareOverloadCandidatesForDisplay(S));
8846
8847  bool ReportedAmbiguousConversions = false;
8848
8849  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
8850  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8851  unsigned CandsShown = 0;
8852  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8853    OverloadCandidate *Cand = *I;
8854
8855    // Set an arbitrary limit on the number of candidate functions we'll spam
8856    // the user with.  FIXME: This limit should depend on details of the
8857    // candidate list.
8858    if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
8859      break;
8860    }
8861    ++CandsShown;
8862
8863    if (Cand->Function)
8864      NoteFunctionCandidate(S, Cand, Args.size());
8865    else if (Cand->IsSurrogate)
8866      NoteSurrogateCandidate(S, Cand);
8867    else {
8868      assert(Cand->Viable &&
8869             "Non-viable built-in candidates are not added to Cands.");
8870      // Generally we only see ambiguities including viable builtin
8871      // operators if overload resolution got screwed up by an
8872      // ambiguous user-defined conversion.
8873      //
8874      // FIXME: It's quite possible for different conversions to see
8875      // different ambiguities, though.
8876      if (!ReportedAmbiguousConversions) {
8877        NoteAmbiguousUserConversions(S, OpLoc, Cand);
8878        ReportedAmbiguousConversions = true;
8879      }
8880
8881      // If this is a viable builtin, print it.
8882      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
8883    }
8884  }
8885
8886  if (I != E)
8887    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
8888}
8889
8890// [PossiblyAFunctionType]  -->   [Return]
8891// NonFunctionType --> NonFunctionType
8892// R (A) --> R(A)
8893// R (*)(A) --> R (A)
8894// R (&)(A) --> R (A)
8895// R (S::*)(A) --> R (A)
8896QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8897  QualType Ret = PossiblyAFunctionType;
8898  if (const PointerType *ToTypePtr =
8899    PossiblyAFunctionType->getAs<PointerType>())
8900    Ret = ToTypePtr->getPointeeType();
8901  else if (const ReferenceType *ToTypeRef =
8902    PossiblyAFunctionType->getAs<ReferenceType>())
8903    Ret = ToTypeRef->getPointeeType();
8904  else if (const MemberPointerType *MemTypePtr =
8905    PossiblyAFunctionType->getAs<MemberPointerType>())
8906    Ret = MemTypePtr->getPointeeType();
8907  Ret =
8908    Context.getCanonicalType(Ret).getUnqualifiedType();
8909  return Ret;
8910}
8911
8912// A helper class to help with address of function resolution
8913// - allows us to avoid passing around all those ugly parameters
8914class AddressOfFunctionResolver
8915{
8916  Sema& S;
8917  Expr* SourceExpr;
8918  const QualType& TargetType;
8919  QualType TargetFunctionType; // Extracted function type from target type
8920
8921  bool Complain;
8922  //DeclAccessPair& ResultFunctionAccessPair;
8923  ASTContext& Context;
8924
8925  bool TargetTypeIsNonStaticMemberFunction;
8926  bool FoundNonTemplateFunction;
8927
8928  OverloadExpr::FindResult OvlExprInfo;
8929  OverloadExpr *OvlExpr;
8930  TemplateArgumentListInfo OvlExplicitTemplateArgs;
8931  SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
8932
8933public:
8934  AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8935                            const QualType& TargetType, bool Complain)
8936    : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8937      Complain(Complain), Context(S.getASTContext()),
8938      TargetTypeIsNonStaticMemberFunction(
8939                                    !!TargetType->getAs<MemberPointerType>()),
8940      FoundNonTemplateFunction(false),
8941      OvlExprInfo(OverloadExpr::find(SourceExpr)),
8942      OvlExpr(OvlExprInfo.Expression)
8943  {
8944    ExtractUnqualifiedFunctionTypeFromTargetType();
8945
8946    if (!TargetFunctionType->isFunctionType()) {
8947      if (OvlExpr->hasExplicitTemplateArgs()) {
8948        DeclAccessPair dap;
8949        if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
8950                                            OvlExpr, false, &dap) ) {
8951
8952          if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8953            if (!Method->isStatic()) {
8954              // If the target type is a non-function type and the function
8955              // found is a non-static member function, pretend as if that was
8956              // the target, it's the only possible type to end up with.
8957              TargetTypeIsNonStaticMemberFunction = true;
8958
8959              // And skip adding the function if its not in the proper form.
8960              // We'll diagnose this due to an empty set of functions.
8961              if (!OvlExprInfo.HasFormOfMemberPointer)
8962                return;
8963            }
8964          }
8965
8966          Matches.push_back(std::make_pair(dap,Fn));
8967        }
8968      }
8969      return;
8970    }
8971
8972    if (OvlExpr->hasExplicitTemplateArgs())
8973      OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
8974
8975    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8976      // C++ [over.over]p4:
8977      //   If more than one function is selected, [...]
8978      if (Matches.size() > 1) {
8979        if (FoundNonTemplateFunction)
8980          EliminateAllTemplateMatches();
8981        else
8982          EliminateAllExceptMostSpecializedTemplate();
8983      }
8984    }
8985  }
8986
8987private:
8988  bool isTargetTypeAFunction() const {
8989    return TargetFunctionType->isFunctionType();
8990  }
8991
8992  // [ToType]     [Return]
8993
8994  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8995  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8996  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8997  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8998    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8999  }
9000
9001  // return true if any matching specializations were found
9002  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9003                                   const DeclAccessPair& CurAccessFunPair) {
9004    if (CXXMethodDecl *Method
9005              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9006      // Skip non-static function templates when converting to pointer, and
9007      // static when converting to member pointer.
9008      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9009        return false;
9010    }
9011    else if (TargetTypeIsNonStaticMemberFunction)
9012      return false;
9013
9014    // C++ [over.over]p2:
9015    //   If the name is a function template, template argument deduction is
9016    //   done (14.8.2.2), and if the argument deduction succeeds, the
9017    //   resulting template argument list is used to generate a single
9018    //   function template specialization, which is added to the set of
9019    //   overloaded functions considered.
9020    FunctionDecl *Specialization = 0;
9021    TemplateDeductionInfo Info(OvlExpr->getNameLoc());
9022    if (Sema::TemplateDeductionResult Result
9023          = S.DeduceTemplateArguments(FunctionTemplate,
9024                                      &OvlExplicitTemplateArgs,
9025                                      TargetFunctionType, Specialization,
9026                                      Info)) {
9027      // FIXME: make a note of the failed deduction for diagnostics.
9028      (void)Result;
9029      return false;
9030    }
9031
9032    // Template argument deduction ensures that we have an exact match.
9033    // This function template specicalization works.
9034    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9035    assert(TargetFunctionType
9036                      == Context.getCanonicalType(Specialization->getType()));
9037    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9038    return true;
9039  }
9040
9041  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9042                                      const DeclAccessPair& CurAccessFunPair) {
9043    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9044      // Skip non-static functions when converting to pointer, and static
9045      // when converting to member pointer.
9046      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9047        return false;
9048    }
9049    else if (TargetTypeIsNonStaticMemberFunction)
9050      return false;
9051
9052    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9053      if (S.getLangOpts().CUDA)
9054        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9055          if (S.CheckCUDATarget(Caller, FunDecl))
9056            return false;
9057
9058      QualType ResultTy;
9059      if (Context.hasSameUnqualifiedType(TargetFunctionType,
9060                                         FunDecl->getType()) ||
9061          S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9062                                 ResultTy)) {
9063        Matches.push_back(std::make_pair(CurAccessFunPair,
9064          cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9065        FoundNonTemplateFunction = true;
9066        return true;
9067      }
9068    }
9069
9070    return false;
9071  }
9072
9073  bool FindAllFunctionsThatMatchTargetTypeExactly() {
9074    bool Ret = false;
9075
9076    // If the overload expression doesn't have the form of a pointer to
9077    // member, don't try to convert it to a pointer-to-member type.
9078    if (IsInvalidFormOfPointerToMemberFunction())
9079      return false;
9080
9081    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9082                               E = OvlExpr->decls_end();
9083         I != E; ++I) {
9084      // Look through any using declarations to find the underlying function.
9085      NamedDecl *Fn = (*I)->getUnderlyingDecl();
9086
9087      // C++ [over.over]p3:
9088      //   Non-member functions and static member functions match
9089      //   targets of type "pointer-to-function" or "reference-to-function."
9090      //   Nonstatic member functions match targets of
9091      //   type "pointer-to-member-function."
9092      // Note that according to DR 247, the containing class does not matter.
9093      if (FunctionTemplateDecl *FunctionTemplate
9094                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
9095        if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9096          Ret = true;
9097      }
9098      // If we have explicit template arguments supplied, skip non-templates.
9099      else if (!OvlExpr->hasExplicitTemplateArgs() &&
9100               AddMatchingNonTemplateFunction(Fn, I.getPair()))
9101        Ret = true;
9102    }
9103    assert(Ret || Matches.empty());
9104    return Ret;
9105  }
9106
9107  void EliminateAllExceptMostSpecializedTemplate() {
9108    //   [...] and any given function template specialization F1 is
9109    //   eliminated if the set contains a second function template
9110    //   specialization whose function template is more specialized
9111    //   than the function template of F1 according to the partial
9112    //   ordering rules of 14.5.5.2.
9113
9114    // The algorithm specified above is quadratic. We instead use a
9115    // two-pass algorithm (similar to the one used to identify the
9116    // best viable function in an overload set) that identifies the
9117    // best function template (if it exists).
9118
9119    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9120    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9121      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9122
9123    UnresolvedSetIterator Result =
9124      S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9125                           TPOC_Other, 0, SourceExpr->getLocStart(),
9126                           S.PDiag(),
9127                           S.PDiag(diag::err_addr_ovl_ambiguous)
9128                             << Matches[0].second->getDeclName(),
9129                           S.PDiag(diag::note_ovl_candidate)
9130                             << (unsigned) oc_function_template,
9131                           Complain, TargetFunctionType);
9132
9133    if (Result != MatchesCopy.end()) {
9134      // Make it the first and only element
9135      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9136      Matches[0].second = cast<FunctionDecl>(*Result);
9137      Matches.resize(1);
9138    }
9139  }
9140
9141  void EliminateAllTemplateMatches() {
9142    //   [...] any function template specializations in the set are
9143    //   eliminated if the set also contains a non-template function, [...]
9144    for (unsigned I = 0, N = Matches.size(); I != N; ) {
9145      if (Matches[I].second->getPrimaryTemplate() == 0)
9146        ++I;
9147      else {
9148        Matches[I] = Matches[--N];
9149        Matches.set_size(N);
9150      }
9151    }
9152  }
9153
9154public:
9155  void ComplainNoMatchesFound() const {
9156    assert(Matches.empty());
9157    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9158        << OvlExpr->getName() << TargetFunctionType
9159        << OvlExpr->getSourceRange();
9160    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9161  }
9162
9163  bool IsInvalidFormOfPointerToMemberFunction() const {
9164    return TargetTypeIsNonStaticMemberFunction &&
9165      !OvlExprInfo.HasFormOfMemberPointer;
9166  }
9167
9168  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9169      // TODO: Should we condition this on whether any functions might
9170      // have matched, or is it more appropriate to do that in callers?
9171      // TODO: a fixit wouldn't hurt.
9172      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9173        << TargetType << OvlExpr->getSourceRange();
9174  }
9175
9176  void ComplainOfInvalidConversion() const {
9177    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9178      << OvlExpr->getName() << TargetType;
9179  }
9180
9181  void ComplainMultipleMatchesFound() const {
9182    assert(Matches.size() > 1);
9183    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9184      << OvlExpr->getName()
9185      << OvlExpr->getSourceRange();
9186    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9187  }
9188
9189  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9190
9191  int getNumMatches() const { return Matches.size(); }
9192
9193  FunctionDecl* getMatchingFunctionDecl() const {
9194    if (Matches.size() != 1) return 0;
9195    return Matches[0].second;
9196  }
9197
9198  const DeclAccessPair* getMatchingFunctionAccessPair() const {
9199    if (Matches.size() != 1) return 0;
9200    return &Matches[0].first;
9201  }
9202};
9203
9204/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9205/// an overloaded function (C++ [over.over]), where @p From is an
9206/// expression with overloaded function type and @p ToType is the type
9207/// we're trying to resolve to. For example:
9208///
9209/// @code
9210/// int f(double);
9211/// int f(int);
9212///
9213/// int (*pfd)(double) = f; // selects f(double)
9214/// @endcode
9215///
9216/// This routine returns the resulting FunctionDecl if it could be
9217/// resolved, and NULL otherwise. When @p Complain is true, this
9218/// routine will emit diagnostics if there is an error.
9219FunctionDecl *
9220Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9221                                         QualType TargetType,
9222                                         bool Complain,
9223                                         DeclAccessPair &FoundResult,
9224                                         bool *pHadMultipleCandidates) {
9225  assert(AddressOfExpr->getType() == Context.OverloadTy);
9226
9227  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9228                                     Complain);
9229  int NumMatches = Resolver.getNumMatches();
9230  FunctionDecl* Fn = 0;
9231  if (NumMatches == 0 && Complain) {
9232    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9233      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9234    else
9235      Resolver.ComplainNoMatchesFound();
9236  }
9237  else if (NumMatches > 1 && Complain)
9238    Resolver.ComplainMultipleMatchesFound();
9239  else if (NumMatches == 1) {
9240    Fn = Resolver.getMatchingFunctionDecl();
9241    assert(Fn);
9242    FoundResult = *Resolver.getMatchingFunctionAccessPair();
9243    if (Complain)
9244      CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9245  }
9246
9247  if (pHadMultipleCandidates)
9248    *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9249  return Fn;
9250}
9251
9252/// \brief Given an expression that refers to an overloaded function, try to
9253/// resolve that overloaded function expression down to a single function.
9254///
9255/// This routine can only resolve template-ids that refer to a single function
9256/// template, where that template-id refers to a single template whose template
9257/// arguments are either provided by the template-id or have defaults,
9258/// as described in C++0x [temp.arg.explicit]p3.
9259FunctionDecl *
9260Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9261                                                  bool Complain,
9262                                                  DeclAccessPair *FoundResult) {
9263  // C++ [over.over]p1:
9264  //   [...] [Note: any redundant set of parentheses surrounding the
9265  //   overloaded function name is ignored (5.1). ]
9266  // C++ [over.over]p1:
9267  //   [...] The overloaded function name can be preceded by the &
9268  //   operator.
9269
9270  // If we didn't actually find any template-ids, we're done.
9271  if (!ovl->hasExplicitTemplateArgs())
9272    return 0;
9273
9274  TemplateArgumentListInfo ExplicitTemplateArgs;
9275  ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9276
9277  // Look through all of the overloaded functions, searching for one
9278  // whose type matches exactly.
9279  FunctionDecl *Matched = 0;
9280  for (UnresolvedSetIterator I = ovl->decls_begin(),
9281         E = ovl->decls_end(); I != E; ++I) {
9282    // C++0x [temp.arg.explicit]p3:
9283    //   [...] In contexts where deduction is done and fails, or in contexts
9284    //   where deduction is not done, if a template argument list is
9285    //   specified and it, along with any default template arguments,
9286    //   identifies a single function template specialization, then the
9287    //   template-id is an lvalue for the function template specialization.
9288    FunctionTemplateDecl *FunctionTemplate
9289      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9290
9291    // C++ [over.over]p2:
9292    //   If the name is a function template, template argument deduction is
9293    //   done (14.8.2.2), and if the argument deduction succeeds, the
9294    //   resulting template argument list is used to generate a single
9295    //   function template specialization, which is added to the set of
9296    //   overloaded functions considered.
9297    FunctionDecl *Specialization = 0;
9298    TemplateDeductionInfo Info(ovl->getNameLoc());
9299    if (TemplateDeductionResult Result
9300          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9301                                    Specialization, Info)) {
9302      // FIXME: make a note of the failed deduction for diagnostics.
9303      (void)Result;
9304      continue;
9305    }
9306
9307    assert(Specialization && "no specialization and no error?");
9308
9309    // Multiple matches; we can't resolve to a single declaration.
9310    if (Matched) {
9311      if (Complain) {
9312        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9313          << ovl->getName();
9314        NoteAllOverloadCandidates(ovl);
9315      }
9316      return 0;
9317    }
9318
9319    Matched = Specialization;
9320    if (FoundResult) *FoundResult = I.getPair();
9321  }
9322
9323  return Matched;
9324}
9325
9326
9327
9328
9329// Resolve and fix an overloaded expression that can be resolved
9330// because it identifies a single function template specialization.
9331//
9332// Last three arguments should only be supplied if Complain = true
9333//
9334// Return true if it was logically possible to so resolve the
9335// expression, regardless of whether or not it succeeded.  Always
9336// returns true if 'complain' is set.
9337bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9338                      ExprResult &SrcExpr, bool doFunctionPointerConverion,
9339                   bool complain, const SourceRange& OpRangeForComplaining,
9340                                           QualType DestTypeForComplaining,
9341                                            unsigned DiagIDForComplaining) {
9342  assert(SrcExpr.get()->getType() == Context.OverloadTy);
9343
9344  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9345
9346  DeclAccessPair found;
9347  ExprResult SingleFunctionExpression;
9348  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9349                           ovl.Expression, /*complain*/ false, &found)) {
9350    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9351      SrcExpr = ExprError();
9352      return true;
9353    }
9354
9355    // It is only correct to resolve to an instance method if we're
9356    // resolving a form that's permitted to be a pointer to member.
9357    // Otherwise we'll end up making a bound member expression, which
9358    // is illegal in all the contexts we resolve like this.
9359    if (!ovl.HasFormOfMemberPointer &&
9360        isa<CXXMethodDecl>(fn) &&
9361        cast<CXXMethodDecl>(fn)->isInstance()) {
9362      if (!complain) return false;
9363
9364      Diag(ovl.Expression->getExprLoc(),
9365           diag::err_bound_member_function)
9366        << 0 << ovl.Expression->getSourceRange();
9367
9368      // TODO: I believe we only end up here if there's a mix of
9369      // static and non-static candidates (otherwise the expression
9370      // would have 'bound member' type, not 'overload' type).
9371      // Ideally we would note which candidate was chosen and why
9372      // the static candidates were rejected.
9373      SrcExpr = ExprError();
9374      return true;
9375    }
9376
9377    // Fix the expression to refer to 'fn'.
9378    SingleFunctionExpression =
9379      Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9380
9381    // If desired, do function-to-pointer decay.
9382    if (doFunctionPointerConverion) {
9383      SingleFunctionExpression =
9384        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9385      if (SingleFunctionExpression.isInvalid()) {
9386        SrcExpr = ExprError();
9387        return true;
9388      }
9389    }
9390  }
9391
9392  if (!SingleFunctionExpression.isUsable()) {
9393    if (complain) {
9394      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9395        << ovl.Expression->getName()
9396        << DestTypeForComplaining
9397        << OpRangeForComplaining
9398        << ovl.Expression->getQualifierLoc().getSourceRange();
9399      NoteAllOverloadCandidates(SrcExpr.get());
9400
9401      SrcExpr = ExprError();
9402      return true;
9403    }
9404
9405    return false;
9406  }
9407
9408  SrcExpr = SingleFunctionExpression;
9409  return true;
9410}
9411
9412/// \brief Add a single candidate to the overload set.
9413static void AddOverloadedCallCandidate(Sema &S,
9414                                       DeclAccessPair FoundDecl,
9415                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
9416                                       llvm::ArrayRef<Expr *> Args,
9417                                       OverloadCandidateSet &CandidateSet,
9418                                       bool PartialOverloading,
9419                                       bool KnownValid) {
9420  NamedDecl *Callee = FoundDecl.getDecl();
9421  if (isa<UsingShadowDecl>(Callee))
9422    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9423
9424  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9425    if (ExplicitTemplateArgs) {
9426      assert(!KnownValid && "Explicit template arguments?");
9427      return;
9428    }
9429    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9430                           PartialOverloading);
9431    return;
9432  }
9433
9434  if (FunctionTemplateDecl *FuncTemplate
9435      = dyn_cast<FunctionTemplateDecl>(Callee)) {
9436    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9437                                   ExplicitTemplateArgs, Args, CandidateSet);
9438    return;
9439  }
9440
9441  assert(!KnownValid && "unhandled case in overloaded call candidate");
9442}
9443
9444/// \brief Add the overload candidates named by callee and/or found by argument
9445/// dependent lookup to the given overload set.
9446void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9447                                       llvm::ArrayRef<Expr *> Args,
9448                                       OverloadCandidateSet &CandidateSet,
9449                                       bool PartialOverloading) {
9450
9451#ifndef NDEBUG
9452  // Verify that ArgumentDependentLookup is consistent with the rules
9453  // in C++0x [basic.lookup.argdep]p3:
9454  //
9455  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9456  //   and let Y be the lookup set produced by argument dependent
9457  //   lookup (defined as follows). If X contains
9458  //
9459  //     -- a declaration of a class member, or
9460  //
9461  //     -- a block-scope function declaration that is not a
9462  //        using-declaration, or
9463  //
9464  //     -- a declaration that is neither a function or a function
9465  //        template
9466  //
9467  //   then Y is empty.
9468
9469  if (ULE->requiresADL()) {
9470    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9471           E = ULE->decls_end(); I != E; ++I) {
9472      assert(!(*I)->getDeclContext()->isRecord());
9473      assert(isa<UsingShadowDecl>(*I) ||
9474             !(*I)->getDeclContext()->isFunctionOrMethod());
9475      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9476    }
9477  }
9478#endif
9479
9480  // It would be nice to avoid this copy.
9481  TemplateArgumentListInfo TABuffer;
9482  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9483  if (ULE->hasExplicitTemplateArgs()) {
9484    ULE->copyTemplateArgumentsInto(TABuffer);
9485    ExplicitTemplateArgs = &TABuffer;
9486  }
9487
9488  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9489         E = ULE->decls_end(); I != E; ++I)
9490    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9491                               CandidateSet, PartialOverloading,
9492                               /*KnownValid*/ true);
9493
9494  if (ULE->requiresADL())
9495    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9496                                         ULE->getExprLoc(),
9497                                         Args, ExplicitTemplateArgs,
9498                                         CandidateSet, PartialOverloading);
9499}
9500
9501/// Attempt to recover from an ill-formed use of a non-dependent name in a
9502/// template, where the non-dependent name was declared after the template
9503/// was defined. This is common in code written for a compilers which do not
9504/// correctly implement two-stage name lookup.
9505///
9506/// Returns true if a viable candidate was found and a diagnostic was issued.
9507static bool
9508DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9509                       const CXXScopeSpec &SS, LookupResult &R,
9510                       TemplateArgumentListInfo *ExplicitTemplateArgs,
9511                       llvm::ArrayRef<Expr *> Args) {
9512  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9513    return false;
9514
9515  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9516    if (DC->isTransparentContext())
9517      continue;
9518
9519    SemaRef.LookupQualifiedName(R, DC);
9520
9521    if (!R.empty()) {
9522      R.suppressDiagnostics();
9523
9524      if (isa<CXXRecordDecl>(DC)) {
9525        // Don't diagnose names we find in classes; we get much better
9526        // diagnostics for these from DiagnoseEmptyLookup.
9527        R.clear();
9528        return false;
9529      }
9530
9531      OverloadCandidateSet Candidates(FnLoc);
9532      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9533        AddOverloadedCallCandidate(SemaRef, I.getPair(),
9534                                   ExplicitTemplateArgs, Args,
9535                                   Candidates, false, /*KnownValid*/ false);
9536
9537      OverloadCandidateSet::iterator Best;
9538      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9539        // No viable functions. Don't bother the user with notes for functions
9540        // which don't work and shouldn't be found anyway.
9541        R.clear();
9542        return false;
9543      }
9544
9545      // Find the namespaces where ADL would have looked, and suggest
9546      // declaring the function there instead.
9547      Sema::AssociatedNamespaceSet AssociatedNamespaces;
9548      Sema::AssociatedClassSet AssociatedClasses;
9549      SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
9550                                                 AssociatedNamespaces,
9551                                                 AssociatedClasses);
9552      Sema::AssociatedNamespaceSet SuggestedNamespaces;
9553      DeclContext *Std = SemaRef.getStdNamespace();
9554      for (Sema::AssociatedNamespaceSet::iterator
9555             it = AssociatedNamespaces.begin(),
9556             end = AssociatedNamespaces.end(); it != end; ++it) {
9557        // Never suggest declaring a function within namespace 'std'.
9558        if (Std && Std->Encloses(*it))
9559          continue;
9560
9561        // Never suggest declaring a function within a namespace with a reserved
9562        // name, like __gnu_cxx.
9563        NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9564        if (NS &&
9565            NS->getQualifiedNameAsString().find("__") != std::string::npos)
9566          continue;
9567
9568        SuggestedNamespaces.insert(*it);
9569      }
9570
9571      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9572        << R.getLookupName();
9573      if (SuggestedNamespaces.empty()) {
9574        SemaRef.Diag(Best->Function->getLocation(),
9575                     diag::note_not_found_by_two_phase_lookup)
9576          << R.getLookupName() << 0;
9577      } else if (SuggestedNamespaces.size() == 1) {
9578        SemaRef.Diag(Best->Function->getLocation(),
9579                     diag::note_not_found_by_two_phase_lookup)
9580          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9581      } else {
9582        // FIXME: It would be useful to list the associated namespaces here,
9583        // but the diagnostics infrastructure doesn't provide a way to produce
9584        // a localized representation of a list of items.
9585        SemaRef.Diag(Best->Function->getLocation(),
9586                     diag::note_not_found_by_two_phase_lookup)
9587          << R.getLookupName() << 2;
9588      }
9589
9590      // Try to recover by calling this function.
9591      return true;
9592    }
9593
9594    R.clear();
9595  }
9596
9597  return false;
9598}
9599
9600/// Attempt to recover from ill-formed use of a non-dependent operator in a
9601/// template, where the non-dependent operator was declared after the template
9602/// was defined.
9603///
9604/// Returns true if a viable candidate was found and a diagnostic was issued.
9605static bool
9606DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9607                               SourceLocation OpLoc,
9608                               llvm::ArrayRef<Expr *> Args) {
9609  DeclarationName OpName =
9610    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9611  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9612  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9613                                /*ExplicitTemplateArgs=*/0, Args);
9614}
9615
9616namespace {
9617// Callback to limit the allowed keywords and to only accept typo corrections
9618// that are keywords or whose decls refer to functions (or template functions)
9619// that accept the given number of arguments.
9620class RecoveryCallCCC : public CorrectionCandidateCallback {
9621 public:
9622  RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9623      : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9624    WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
9625    WantRemainingKeywords = false;
9626  }
9627
9628  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9629    if (!candidate.getCorrectionDecl())
9630      return candidate.isKeyword();
9631
9632    for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9633           DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9634      FunctionDecl *FD = 0;
9635      NamedDecl *ND = (*DI)->getUnderlyingDecl();
9636      if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9637        FD = FTD->getTemplatedDecl();
9638      if (!HasExplicitTemplateArgs && !FD) {
9639        if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9640          // If the Decl is neither a function nor a template function,
9641          // determine if it is a pointer or reference to a function. If so,
9642          // check against the number of arguments expected for the pointee.
9643          QualType ValType = cast<ValueDecl>(ND)->getType();
9644          if (ValType->isAnyPointerType() || ValType->isReferenceType())
9645            ValType = ValType->getPointeeType();
9646          if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9647            if (FPT->getNumArgs() == NumArgs)
9648              return true;
9649        }
9650      }
9651      if (FD && FD->getNumParams() >= NumArgs &&
9652          FD->getMinRequiredArguments() <= NumArgs)
9653        return true;
9654    }
9655    return false;
9656  }
9657
9658 private:
9659  unsigned NumArgs;
9660  bool HasExplicitTemplateArgs;
9661};
9662
9663// Callback that effectively disabled typo correction
9664class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9665 public:
9666  NoTypoCorrectionCCC() {
9667    WantTypeSpecifiers = false;
9668    WantExpressionKeywords = false;
9669    WantCXXNamedCasts = false;
9670    WantRemainingKeywords = false;
9671  }
9672
9673  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9674    return false;
9675  }
9676};
9677
9678class BuildRecoveryCallExprRAII {
9679  Sema &SemaRef;
9680public:
9681  BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9682    assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9683    SemaRef.IsBuildingRecoveryCallExpr = true;
9684  }
9685
9686  ~BuildRecoveryCallExprRAII() {
9687    SemaRef.IsBuildingRecoveryCallExpr = false;
9688  }
9689};
9690
9691}
9692
9693/// Attempts to recover from a call where no functions were found.
9694///
9695/// Returns true if new candidates were found.
9696static ExprResult
9697BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9698                      UnresolvedLookupExpr *ULE,
9699                      SourceLocation LParenLoc,
9700                      llvm::MutableArrayRef<Expr *> Args,
9701                      SourceLocation RParenLoc,
9702                      bool EmptyLookup, bool AllowTypoCorrection) {
9703  // Do not try to recover if it is already building a recovery call.
9704  // This stops infinite loops for template instantiations like
9705  //
9706  // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9707  // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9708  //
9709  if (SemaRef.IsBuildingRecoveryCallExpr)
9710    return ExprError();
9711  BuildRecoveryCallExprRAII RCE(SemaRef);
9712
9713  CXXScopeSpec SS;
9714  SS.Adopt(ULE->getQualifierLoc());
9715  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9716
9717  TemplateArgumentListInfo TABuffer;
9718  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9719  if (ULE->hasExplicitTemplateArgs()) {
9720    ULE->copyTemplateArgumentsInto(TABuffer);
9721    ExplicitTemplateArgs = &TABuffer;
9722  }
9723
9724  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9725                 Sema::LookupOrdinaryName);
9726  RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
9727  NoTypoCorrectionCCC RejectAll;
9728  CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9729      (CorrectionCandidateCallback*)&Validator :
9730      (CorrectionCandidateCallback*)&RejectAll;
9731  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9732                              ExplicitTemplateArgs, Args) &&
9733      (!EmptyLookup ||
9734       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
9735                                   ExplicitTemplateArgs, Args)))
9736    return ExprError();
9737
9738  assert(!R.empty() && "lookup results empty despite recovery");
9739
9740  // Build an implicit member call if appropriate.  Just drop the
9741  // casts and such from the call, we don't really care.
9742  ExprResult NewFn = ExprError();
9743  if ((*R.begin())->isCXXClassMember())
9744    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9745                                                    R, ExplicitTemplateArgs);
9746  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
9747    NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9748                                        ExplicitTemplateArgs);
9749  else
9750    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9751
9752  if (NewFn.isInvalid())
9753    return ExprError();
9754
9755  // This shouldn't cause an infinite loop because we're giving it
9756  // an expression with viable lookup results, which should never
9757  // end up here.
9758  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
9759                               MultiExprArg(Args.data(), Args.size()),
9760                               RParenLoc);
9761}
9762
9763/// \brief Constructs and populates an OverloadedCandidateSet from
9764/// the given function.
9765/// \returns true when an the ExprResult output parameter has been set.
9766bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9767                                  UnresolvedLookupExpr *ULE,
9768                                  Expr **Args, unsigned NumArgs,
9769                                  SourceLocation RParenLoc,
9770                                  OverloadCandidateSet *CandidateSet,
9771                                  ExprResult *Result) {
9772#ifndef NDEBUG
9773  if (ULE->requiresADL()) {
9774    // To do ADL, we must have found an unqualified name.
9775    assert(!ULE->getQualifier() && "qualified name with ADL");
9776
9777    // We don't perform ADL for implicit declarations of builtins.
9778    // Verify that this was correctly set up.
9779    FunctionDecl *F;
9780    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9781        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9782        F->getBuiltinID() && F->isImplicit())
9783      llvm_unreachable("performing ADL for builtin");
9784
9785    // We don't perform ADL in C.
9786    assert(getLangOpts().CPlusPlus && "ADL enabled in C");
9787  }
9788#endif
9789
9790  UnbridgedCastsSet UnbridgedCasts;
9791  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9792    *Result = ExprError();
9793    return true;
9794  }
9795
9796  // Add the functions denoted by the callee to the set of candidate
9797  // functions, including those from argument-dependent lookup.
9798  AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9799                              *CandidateSet);
9800
9801  // If we found nothing, try to recover.
9802  // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9803  // out if it fails.
9804  if (CandidateSet->empty()) {
9805    // In Microsoft mode, if we are inside a template class member function then
9806    // create a type dependent CallExpr. The goal is to postpone name lookup
9807    // to instantiation time to be able to search into type dependent base
9808    // classes.
9809    if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
9810        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
9811      CallExpr *CE = new (Context) CallExpr(Context, Fn,
9812                                            llvm::makeArrayRef(Args, NumArgs),
9813                                            Context.DependentTy, VK_RValue,
9814                                            RParenLoc);
9815      CE->setTypeDependent(true);
9816      *Result = Owned(CE);
9817      return true;
9818    }
9819    return false;
9820  }
9821
9822  UnbridgedCasts.restore();
9823  return false;
9824}
9825
9826/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9827/// the completed call expression. If overload resolution fails, emits
9828/// diagnostics and returns ExprError()
9829static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9830                                           UnresolvedLookupExpr *ULE,
9831                                           SourceLocation LParenLoc,
9832                                           Expr **Args, unsigned NumArgs,
9833                                           SourceLocation RParenLoc,
9834                                           Expr *ExecConfig,
9835                                           OverloadCandidateSet *CandidateSet,
9836                                           OverloadCandidateSet::iterator *Best,
9837                                           OverloadingResult OverloadResult,
9838                                           bool AllowTypoCorrection) {
9839  if (CandidateSet->empty())
9840    return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9841                                 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9842                                 RParenLoc, /*EmptyLookup=*/true,
9843                                 AllowTypoCorrection);
9844
9845  switch (OverloadResult) {
9846  case OR_Success: {
9847    FunctionDecl *FDecl = (*Best)->Function;
9848    SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9849    SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9850    SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9851    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9852    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9853                                         RParenLoc, ExecConfig);
9854  }
9855
9856  case OR_No_Viable_Function: {
9857    // Try to recover by looking for viable functions which the user might
9858    // have meant to call.
9859    ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9860                                  llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9861                                                RParenLoc,
9862                                                /*EmptyLookup=*/false,
9863                                                AllowTypoCorrection);
9864    if (!Recovery.isInvalid())
9865      return Recovery;
9866
9867    SemaRef.Diag(Fn->getLocStart(),
9868         diag::err_ovl_no_viable_function_in_call)
9869      << ULE->getName() << Fn->getSourceRange();
9870    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9871                                 llvm::makeArrayRef(Args, NumArgs));
9872    break;
9873  }
9874
9875  case OR_Ambiguous:
9876    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
9877      << ULE->getName() << Fn->getSourceRange();
9878    CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9879                                 llvm::makeArrayRef(Args, NumArgs));
9880    break;
9881
9882  case OR_Deleted: {
9883    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9884      << (*Best)->Function->isDeleted()
9885      << ULE->getName()
9886      << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9887      << Fn->getSourceRange();
9888    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9889                                 llvm::makeArrayRef(Args, NumArgs));
9890
9891    // We emitted an error for the unvailable/deleted function call but keep
9892    // the call in the AST.
9893    FunctionDecl *FDecl = (*Best)->Function;
9894    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9895    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9896                                 RParenLoc, ExecConfig);
9897  }
9898  }
9899
9900  // Overload resolution failed.
9901  return ExprError();
9902}
9903
9904/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9905/// (which eventually refers to the declaration Func) and the call
9906/// arguments Args/NumArgs, attempt to resolve the function call down
9907/// to a specific function. If overload resolution succeeds, returns
9908/// the call expression produced by overload resolution.
9909/// Otherwise, emits diagnostics and returns ExprError.
9910ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9911                                         UnresolvedLookupExpr *ULE,
9912                                         SourceLocation LParenLoc,
9913                                         Expr **Args, unsigned NumArgs,
9914                                         SourceLocation RParenLoc,
9915                                         Expr *ExecConfig,
9916                                         bool AllowTypoCorrection) {
9917  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9918  ExprResult result;
9919
9920  if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9921                             &CandidateSet, &result))
9922    return result;
9923
9924  OverloadCandidateSet::iterator Best;
9925  OverloadingResult OverloadResult =
9926      CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9927
9928  return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9929                                  RParenLoc, ExecConfig, &CandidateSet,
9930                                  &Best, OverloadResult,
9931                                  AllowTypoCorrection);
9932}
9933
9934static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
9935  return Functions.size() > 1 ||
9936    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9937}
9938
9939/// \brief Create a unary operation that may resolve to an overloaded
9940/// operator.
9941///
9942/// \param OpLoc The location of the operator itself (e.g., '*').
9943///
9944/// \param OpcIn The UnaryOperator::Opcode that describes this
9945/// operator.
9946///
9947/// \param Fns The set of non-member functions that will be
9948/// considered by overload resolution. The caller needs to build this
9949/// set based on the context using, e.g.,
9950/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9951/// set should not contain any member functions; those will be added
9952/// by CreateOverloadedUnaryOp().
9953///
9954/// \param Input The input argument.
9955ExprResult
9956Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9957                              const UnresolvedSetImpl &Fns,
9958                              Expr *Input) {
9959  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
9960
9961  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9962  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9963  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9964  // TODO: provide better source location info.
9965  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
9966
9967  if (checkPlaceholderForOverload(*this, Input))
9968    return ExprError();
9969
9970  Expr *Args[2] = { Input, 0 };
9971  unsigned NumArgs = 1;
9972
9973  // For post-increment and post-decrement, add the implicit '0' as
9974  // the second argument, so that we know this is a post-increment or
9975  // post-decrement.
9976  if (Opc == UO_PostInc || Opc == UO_PostDec) {
9977    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
9978    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9979                                     SourceLocation());
9980    NumArgs = 2;
9981  }
9982
9983  if (Input->isTypeDependent()) {
9984    if (Fns.empty())
9985      return Owned(new (Context) UnaryOperator(Input,
9986                                               Opc,
9987                                               Context.DependentTy,
9988                                               VK_RValue, OK_Ordinary,
9989                                               OpLoc));
9990
9991    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
9992    UnresolvedLookupExpr *Fn
9993      = UnresolvedLookupExpr::Create(Context, NamingClass,
9994                                     NestedNameSpecifierLoc(), OpNameInfo,
9995                                     /*ADL*/ true, IsOverloaded(Fns),
9996                                     Fns.begin(), Fns.end());
9997    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
9998                                              llvm::makeArrayRef(Args, NumArgs),
9999                                                   Context.DependentTy,
10000                                                   VK_RValue,
10001                                                   OpLoc, false));
10002  }
10003
10004  // Build an empty overload set.
10005  OverloadCandidateSet CandidateSet(OpLoc);
10006
10007  // Add the candidates from the given function set.
10008  AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10009                        false);
10010
10011  // Add operator candidates that are member functions.
10012  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10013
10014  // Add candidates from ADL.
10015  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10016                                       OpLoc, llvm::makeArrayRef(Args, NumArgs),
10017                                       /*ExplicitTemplateArgs*/ 0,
10018                                       CandidateSet);
10019
10020  // Add builtin operator candidates.
10021  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10022
10023  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10024
10025  // Perform overload resolution.
10026  OverloadCandidateSet::iterator Best;
10027  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10028  case OR_Success: {
10029    // We found a built-in operator or an overloaded operator.
10030    FunctionDecl *FnDecl = Best->Function;
10031
10032    if (FnDecl) {
10033      // We matched an overloaded operator. Build a call to that
10034      // operator.
10035
10036      MarkFunctionReferenced(OpLoc, FnDecl);
10037
10038      // Convert the arguments.
10039      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10040        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
10041
10042        ExprResult InputRes =
10043          PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10044                                              Best->FoundDecl, Method);
10045        if (InputRes.isInvalid())
10046          return ExprError();
10047        Input = InputRes.take();
10048      } else {
10049        // Convert the arguments.
10050        ExprResult InputInit
10051          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10052                                                      Context,
10053                                                      FnDecl->getParamDecl(0)),
10054                                      SourceLocation(),
10055                                      Input);
10056        if (InputInit.isInvalid())
10057          return ExprError();
10058        Input = InputInit.take();
10059      }
10060
10061      DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10062
10063      // Determine the result type.
10064      QualType ResultTy = FnDecl->getResultType();
10065      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10066      ResultTy = ResultTy.getNonLValueExprType(Context);
10067
10068      // Build the actual expression node.
10069      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10070                                                HadMultipleCandidates, OpLoc);
10071      if (FnExpr.isInvalid())
10072        return ExprError();
10073
10074      Args[0] = Input;
10075      CallExpr *TheCall =
10076        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10077                                          llvm::makeArrayRef(Args, NumArgs),
10078                                          ResultTy, VK, OpLoc, false);
10079
10080      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10081                              FnDecl))
10082        return ExprError();
10083
10084      return MaybeBindToTemporary(TheCall);
10085    } else {
10086      // We matched a built-in operator. Convert the arguments, then
10087      // break out so that we will build the appropriate built-in
10088      // operator node.
10089      ExprResult InputRes =
10090        PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10091                                  Best->Conversions[0], AA_Passing);
10092      if (InputRes.isInvalid())
10093        return ExprError();
10094      Input = InputRes.take();
10095      break;
10096    }
10097  }
10098
10099  case OR_No_Viable_Function:
10100    // This is an erroneous use of an operator which can be overloaded by
10101    // a non-member function. Check for non-member operators which were
10102    // defined too late to be candidates.
10103    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10104                                       llvm::makeArrayRef(Args, NumArgs)))
10105      // FIXME: Recover by calling the found function.
10106      return ExprError();
10107
10108    // No viable function; fall through to handling this as a
10109    // built-in operator, which will produce an error message for us.
10110    break;
10111
10112  case OR_Ambiguous:
10113    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10114        << UnaryOperator::getOpcodeStr(Opc)
10115        << Input->getType()
10116        << Input->getSourceRange();
10117    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10118                                llvm::makeArrayRef(Args, NumArgs),
10119                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10120    return ExprError();
10121
10122  case OR_Deleted:
10123    Diag(OpLoc, diag::err_ovl_deleted_oper)
10124      << Best->Function->isDeleted()
10125      << UnaryOperator::getOpcodeStr(Opc)
10126      << getDeletedOrUnavailableSuffix(Best->Function)
10127      << Input->getSourceRange();
10128    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10129                                llvm::makeArrayRef(Args, NumArgs),
10130                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10131    return ExprError();
10132  }
10133
10134  // Either we found no viable overloaded operator or we matched a
10135  // built-in operator. In either case, fall through to trying to
10136  // build a built-in operation.
10137  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10138}
10139
10140/// \brief Create a binary operation that may resolve to an overloaded
10141/// operator.
10142///
10143/// \param OpLoc The location of the operator itself (e.g., '+').
10144///
10145/// \param OpcIn The BinaryOperator::Opcode that describes this
10146/// operator.
10147///
10148/// \param Fns The set of non-member functions that will be
10149/// considered by overload resolution. The caller needs to build this
10150/// set based on the context using, e.g.,
10151/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10152/// set should not contain any member functions; those will be added
10153/// by CreateOverloadedBinOp().
10154///
10155/// \param LHS Left-hand argument.
10156/// \param RHS Right-hand argument.
10157ExprResult
10158Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10159                            unsigned OpcIn,
10160                            const UnresolvedSetImpl &Fns,
10161                            Expr *LHS, Expr *RHS) {
10162  Expr *Args[2] = { LHS, RHS };
10163  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10164
10165  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10166  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10167  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10168
10169  // If either side is type-dependent, create an appropriate dependent
10170  // expression.
10171  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10172    if (Fns.empty()) {
10173      // If there are no functions to store, just build a dependent
10174      // BinaryOperator or CompoundAssignment.
10175      if (Opc <= BO_Assign || Opc > BO_OrAssign)
10176        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10177                                                  Context.DependentTy,
10178                                                  VK_RValue, OK_Ordinary,
10179                                                  OpLoc,
10180                                                  FPFeatures.fp_contract));
10181
10182      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10183                                                        Context.DependentTy,
10184                                                        VK_LValue,
10185                                                        OK_Ordinary,
10186                                                        Context.DependentTy,
10187                                                        Context.DependentTy,
10188                                                        OpLoc,
10189                                                        FPFeatures.fp_contract));
10190    }
10191
10192    // FIXME: save results of ADL from here?
10193    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10194    // TODO: provide better source location info in DNLoc component.
10195    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10196    UnresolvedLookupExpr *Fn
10197      = UnresolvedLookupExpr::Create(Context, NamingClass,
10198                                     NestedNameSpecifierLoc(), OpNameInfo,
10199                                     /*ADL*/ true, IsOverloaded(Fns),
10200                                     Fns.begin(), Fns.end());
10201    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10202                                                Context.DependentTy, VK_RValue,
10203                                                OpLoc, FPFeatures.fp_contract));
10204  }
10205
10206  // Always do placeholder-like conversions on the RHS.
10207  if (checkPlaceholderForOverload(*this, Args[1]))
10208    return ExprError();
10209
10210  // Do placeholder-like conversion on the LHS; note that we should
10211  // not get here with a PseudoObject LHS.
10212  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10213  if (checkPlaceholderForOverload(*this, Args[0]))
10214    return ExprError();
10215
10216  // If this is the assignment operator, we only perform overload resolution
10217  // if the left-hand side is a class or enumeration type. This is actually
10218  // a hack. The standard requires that we do overload resolution between the
10219  // various built-in candidates, but as DR507 points out, this can lead to
10220  // problems. So we do it this way, which pretty much follows what GCC does.
10221  // Note that we go the traditional code path for compound assignment forms.
10222  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10223    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10224
10225  // If this is the .* operator, which is not overloadable, just
10226  // create a built-in binary operator.
10227  if (Opc == BO_PtrMemD)
10228    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10229
10230  // Build an empty overload set.
10231  OverloadCandidateSet CandidateSet(OpLoc);
10232
10233  // Add the candidates from the given function set.
10234  AddFunctionCandidates(Fns, Args, CandidateSet, false);
10235
10236  // Add operator candidates that are member functions.
10237  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10238
10239  // Add candidates from ADL.
10240  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10241                                       OpLoc, Args,
10242                                       /*ExplicitTemplateArgs*/ 0,
10243                                       CandidateSet);
10244
10245  // Add builtin operator candidates.
10246  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10247
10248  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10249
10250  // Perform overload resolution.
10251  OverloadCandidateSet::iterator Best;
10252  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10253    case OR_Success: {
10254      // We found a built-in operator or an overloaded operator.
10255      FunctionDecl *FnDecl = Best->Function;
10256
10257      if (FnDecl) {
10258        // We matched an overloaded operator. Build a call to that
10259        // operator.
10260
10261        MarkFunctionReferenced(OpLoc, FnDecl);
10262
10263        // Convert the arguments.
10264        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10265          // Best->Access is only meaningful for class members.
10266          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10267
10268          ExprResult Arg1 =
10269            PerformCopyInitialization(
10270              InitializedEntity::InitializeParameter(Context,
10271                                                     FnDecl->getParamDecl(0)),
10272              SourceLocation(), Owned(Args[1]));
10273          if (Arg1.isInvalid())
10274            return ExprError();
10275
10276          ExprResult Arg0 =
10277            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10278                                                Best->FoundDecl, Method);
10279          if (Arg0.isInvalid())
10280            return ExprError();
10281          Args[0] = Arg0.takeAs<Expr>();
10282          Args[1] = RHS = Arg1.takeAs<Expr>();
10283        } else {
10284          // Convert the arguments.
10285          ExprResult Arg0 = PerformCopyInitialization(
10286            InitializedEntity::InitializeParameter(Context,
10287                                                   FnDecl->getParamDecl(0)),
10288            SourceLocation(), Owned(Args[0]));
10289          if (Arg0.isInvalid())
10290            return ExprError();
10291
10292          ExprResult Arg1 =
10293            PerformCopyInitialization(
10294              InitializedEntity::InitializeParameter(Context,
10295                                                     FnDecl->getParamDecl(1)),
10296              SourceLocation(), Owned(Args[1]));
10297          if (Arg1.isInvalid())
10298            return ExprError();
10299          Args[0] = LHS = Arg0.takeAs<Expr>();
10300          Args[1] = RHS = Arg1.takeAs<Expr>();
10301        }
10302
10303        DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10304
10305        // Determine the result type.
10306        QualType ResultTy = FnDecl->getResultType();
10307        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10308        ResultTy = ResultTy.getNonLValueExprType(Context);
10309
10310        // Build the actual expression node.
10311        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10312                                                  HadMultipleCandidates, OpLoc);
10313        if (FnExpr.isInvalid())
10314          return ExprError();
10315
10316        CXXOperatorCallExpr *TheCall =
10317          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10318                                            Args, ResultTy, VK, OpLoc,
10319                                            FPFeatures.fp_contract);
10320
10321        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10322                                FnDecl))
10323          return ExprError();
10324
10325        return MaybeBindToTemporary(TheCall);
10326      } else {
10327        // We matched a built-in operator. Convert the arguments, then
10328        // break out so that we will build the appropriate built-in
10329        // operator node.
10330        ExprResult ArgsRes0 =
10331          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10332                                    Best->Conversions[0], AA_Passing);
10333        if (ArgsRes0.isInvalid())
10334          return ExprError();
10335        Args[0] = ArgsRes0.take();
10336
10337        ExprResult ArgsRes1 =
10338          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10339                                    Best->Conversions[1], AA_Passing);
10340        if (ArgsRes1.isInvalid())
10341          return ExprError();
10342        Args[1] = ArgsRes1.take();
10343        break;
10344      }
10345    }
10346
10347    case OR_No_Viable_Function: {
10348      // C++ [over.match.oper]p9:
10349      //   If the operator is the operator , [...] and there are no
10350      //   viable functions, then the operator is assumed to be the
10351      //   built-in operator and interpreted according to clause 5.
10352      if (Opc == BO_Comma)
10353        break;
10354
10355      // For class as left operand for assignment or compound assigment
10356      // operator do not fall through to handling in built-in, but report that
10357      // no overloaded assignment operator found
10358      ExprResult Result = ExprError();
10359      if (Args[0]->getType()->isRecordType() &&
10360          Opc >= BO_Assign && Opc <= BO_OrAssign) {
10361        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10362             << BinaryOperator::getOpcodeStr(Opc)
10363             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10364      } else {
10365        // This is an erroneous use of an operator which can be overloaded by
10366        // a non-member function. Check for non-member operators which were
10367        // defined too late to be candidates.
10368        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10369          // FIXME: Recover by calling the found function.
10370          return ExprError();
10371
10372        // No viable function; try to create a built-in operation, which will
10373        // produce an error. Then, show the non-viable candidates.
10374        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10375      }
10376      assert(Result.isInvalid() &&
10377             "C++ binary operator overloading is missing candidates!");
10378      if (Result.isInvalid())
10379        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10380                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
10381      return Result;
10382    }
10383
10384    case OR_Ambiguous:
10385      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10386          << BinaryOperator::getOpcodeStr(Opc)
10387          << Args[0]->getType() << Args[1]->getType()
10388          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10389      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10390                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10391      return ExprError();
10392
10393    case OR_Deleted:
10394      if (isImplicitlyDeleted(Best->Function)) {
10395        CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10396        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10397          << Context.getRecordType(Method->getParent())
10398          << getSpecialMember(Method);
10399
10400        // The user probably meant to call this special member. Just
10401        // explain why it's deleted.
10402        NoteDeletedFunction(Method);
10403        return ExprError();
10404      } else {
10405        Diag(OpLoc, diag::err_ovl_deleted_oper)
10406          << Best->Function->isDeleted()
10407          << BinaryOperator::getOpcodeStr(Opc)
10408          << getDeletedOrUnavailableSuffix(Best->Function)
10409          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10410      }
10411      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10412                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10413      return ExprError();
10414  }
10415
10416  // We matched a built-in operator; build it.
10417  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10418}
10419
10420ExprResult
10421Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10422                                         SourceLocation RLoc,
10423                                         Expr *Base, Expr *Idx) {
10424  Expr *Args[2] = { Base, Idx };
10425  DeclarationName OpName =
10426      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10427
10428  // If either side is type-dependent, create an appropriate dependent
10429  // expression.
10430  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10431
10432    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10433    // CHECKME: no 'operator' keyword?
10434    DeclarationNameInfo OpNameInfo(OpName, LLoc);
10435    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10436    UnresolvedLookupExpr *Fn
10437      = UnresolvedLookupExpr::Create(Context, NamingClass,
10438                                     NestedNameSpecifierLoc(), OpNameInfo,
10439                                     /*ADL*/ true, /*Overloaded*/ false,
10440                                     UnresolvedSetIterator(),
10441                                     UnresolvedSetIterator());
10442    // Can't add any actual overloads yet
10443
10444    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10445                                                   Args,
10446                                                   Context.DependentTy,
10447                                                   VK_RValue,
10448                                                   RLoc, false));
10449  }
10450
10451  // Handle placeholders on both operands.
10452  if (checkPlaceholderForOverload(*this, Args[0]))
10453    return ExprError();
10454  if (checkPlaceholderForOverload(*this, Args[1]))
10455    return ExprError();
10456
10457  // Build an empty overload set.
10458  OverloadCandidateSet CandidateSet(LLoc);
10459
10460  // Subscript can only be overloaded as a member function.
10461
10462  // Add operator candidates that are member functions.
10463  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10464
10465  // Add builtin operator candidates.
10466  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10467
10468  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10469
10470  // Perform overload resolution.
10471  OverloadCandidateSet::iterator Best;
10472  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10473    case OR_Success: {
10474      // We found a built-in operator or an overloaded operator.
10475      FunctionDecl *FnDecl = Best->Function;
10476
10477      if (FnDecl) {
10478        // We matched an overloaded operator. Build a call to that
10479        // operator.
10480
10481        MarkFunctionReferenced(LLoc, FnDecl);
10482
10483        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10484        DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
10485
10486        // Convert the arguments.
10487        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10488        ExprResult Arg0 =
10489          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10490                                              Best->FoundDecl, Method);
10491        if (Arg0.isInvalid())
10492          return ExprError();
10493        Args[0] = Arg0.take();
10494
10495        // Convert the arguments.
10496        ExprResult InputInit
10497          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10498                                                      Context,
10499                                                      FnDecl->getParamDecl(0)),
10500                                      SourceLocation(),
10501                                      Owned(Args[1]));
10502        if (InputInit.isInvalid())
10503          return ExprError();
10504
10505        Args[1] = InputInit.takeAs<Expr>();
10506
10507        // Determine the result type
10508        QualType ResultTy = FnDecl->getResultType();
10509        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10510        ResultTy = ResultTy.getNonLValueExprType(Context);
10511
10512        // Build the actual expression node.
10513        DeclarationNameInfo OpLocInfo(OpName, LLoc);
10514        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10515        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10516                                                  HadMultipleCandidates,
10517                                                  OpLocInfo.getLoc(),
10518                                                  OpLocInfo.getInfo());
10519        if (FnExpr.isInvalid())
10520          return ExprError();
10521
10522        CXXOperatorCallExpr *TheCall =
10523          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10524                                            FnExpr.take(), Args,
10525                                            ResultTy, VK, RLoc,
10526                                            false);
10527
10528        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10529                                FnDecl))
10530          return ExprError();
10531
10532        return MaybeBindToTemporary(TheCall);
10533      } else {
10534        // We matched a built-in operator. Convert the arguments, then
10535        // break out so that we will build the appropriate built-in
10536        // operator node.
10537        ExprResult ArgsRes0 =
10538          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10539                                    Best->Conversions[0], AA_Passing);
10540        if (ArgsRes0.isInvalid())
10541          return ExprError();
10542        Args[0] = ArgsRes0.take();
10543
10544        ExprResult ArgsRes1 =
10545          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10546                                    Best->Conversions[1], AA_Passing);
10547        if (ArgsRes1.isInvalid())
10548          return ExprError();
10549        Args[1] = ArgsRes1.take();
10550
10551        break;
10552      }
10553    }
10554
10555    case OR_No_Viable_Function: {
10556      if (CandidateSet.empty())
10557        Diag(LLoc, diag::err_ovl_no_oper)
10558          << Args[0]->getType() << /*subscript*/ 0
10559          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10560      else
10561        Diag(LLoc, diag::err_ovl_no_viable_subscript)
10562          << Args[0]->getType()
10563          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10564      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10565                                  "[]", LLoc);
10566      return ExprError();
10567    }
10568
10569    case OR_Ambiguous:
10570      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10571          << "[]"
10572          << Args[0]->getType() << Args[1]->getType()
10573          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10574      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10575                                  "[]", LLoc);
10576      return ExprError();
10577
10578    case OR_Deleted:
10579      Diag(LLoc, diag::err_ovl_deleted_oper)
10580        << Best->Function->isDeleted() << "[]"
10581        << getDeletedOrUnavailableSuffix(Best->Function)
10582        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10583      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10584                                  "[]", LLoc);
10585      return ExprError();
10586    }
10587
10588  // We matched a built-in operator; build it.
10589  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10590}
10591
10592/// BuildCallToMemberFunction - Build a call to a member
10593/// function. MemExpr is the expression that refers to the member
10594/// function (and includes the object parameter), Args/NumArgs are the
10595/// arguments to the function call (not including the object
10596/// parameter). The caller needs to validate that the member
10597/// expression refers to a non-static member function or an overloaded
10598/// member function.
10599ExprResult
10600Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10601                                SourceLocation LParenLoc, Expr **Args,
10602                                unsigned NumArgs, SourceLocation RParenLoc) {
10603  assert(MemExprE->getType() == Context.BoundMemberTy ||
10604         MemExprE->getType() == Context.OverloadTy);
10605
10606  // Dig out the member expression. This holds both the object
10607  // argument and the member function we're referring to.
10608  Expr *NakedMemExpr = MemExprE->IgnoreParens();
10609
10610  // Determine whether this is a call to a pointer-to-member function.
10611  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10612    assert(op->getType() == Context.BoundMemberTy);
10613    assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10614
10615    QualType fnType =
10616      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10617
10618    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10619    QualType resultType = proto->getCallResultType(Context);
10620    ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10621
10622    // Check that the object type isn't more qualified than the
10623    // member function we're calling.
10624    Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10625
10626    QualType objectType = op->getLHS()->getType();
10627    if (op->getOpcode() == BO_PtrMemI)
10628      objectType = objectType->castAs<PointerType>()->getPointeeType();
10629    Qualifiers objectQuals = objectType.getQualifiers();
10630
10631    Qualifiers difference = objectQuals - funcQuals;
10632    difference.removeObjCGCAttr();
10633    difference.removeAddressSpace();
10634    if (difference) {
10635      std::string qualsString = difference.getAsString();
10636      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10637        << fnType.getUnqualifiedType()
10638        << qualsString
10639        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10640    }
10641
10642    CXXMemberCallExpr *call
10643      = new (Context) CXXMemberCallExpr(Context, MemExprE,
10644                                        llvm::makeArrayRef(Args, NumArgs),
10645                                        resultType, valueKind, RParenLoc);
10646
10647    if (CheckCallReturnType(proto->getResultType(),
10648                            op->getRHS()->getLocStart(),
10649                            call, 0))
10650      return ExprError();
10651
10652    if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10653      return ExprError();
10654
10655    return MaybeBindToTemporary(call);
10656  }
10657
10658  UnbridgedCastsSet UnbridgedCasts;
10659  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10660    return ExprError();
10661
10662  MemberExpr *MemExpr;
10663  CXXMethodDecl *Method = 0;
10664  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10665  NestedNameSpecifier *Qualifier = 0;
10666  if (isa<MemberExpr>(NakedMemExpr)) {
10667    MemExpr = cast<MemberExpr>(NakedMemExpr);
10668    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10669    FoundDecl = MemExpr->getFoundDecl();
10670    Qualifier = MemExpr->getQualifier();
10671    UnbridgedCasts.restore();
10672  } else {
10673    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10674    Qualifier = UnresExpr->getQualifier();
10675
10676    QualType ObjectType = UnresExpr->getBaseType();
10677    Expr::Classification ObjectClassification
10678      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10679                            : UnresExpr->getBase()->Classify(Context);
10680
10681    // Add overload candidates
10682    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10683
10684    // FIXME: avoid copy.
10685    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10686    if (UnresExpr->hasExplicitTemplateArgs()) {
10687      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10688      TemplateArgs = &TemplateArgsBuffer;
10689    }
10690
10691    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10692           E = UnresExpr->decls_end(); I != E; ++I) {
10693
10694      NamedDecl *Func = *I;
10695      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10696      if (isa<UsingShadowDecl>(Func))
10697        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10698
10699
10700      // Microsoft supports direct constructor calls.
10701      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10702        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10703                             llvm::makeArrayRef(Args, NumArgs), CandidateSet);
10704      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10705        // If explicit template arguments were provided, we can't call a
10706        // non-template member function.
10707        if (TemplateArgs)
10708          continue;
10709
10710        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10711                           ObjectClassification,
10712                           llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10713                           /*SuppressUserConversions=*/false);
10714      } else {
10715        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10716                                   I.getPair(), ActingDC, TemplateArgs,
10717                                   ObjectType,  ObjectClassification,
10718                                   llvm::makeArrayRef(Args, NumArgs),
10719                                   CandidateSet,
10720                                   /*SuppressUsedConversions=*/false);
10721      }
10722    }
10723
10724    DeclarationName DeclName = UnresExpr->getMemberName();
10725
10726    UnbridgedCasts.restore();
10727
10728    OverloadCandidateSet::iterator Best;
10729    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10730                                            Best)) {
10731    case OR_Success:
10732      Method = cast<CXXMethodDecl>(Best->Function);
10733      MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
10734      FoundDecl = Best->FoundDecl;
10735      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10736      DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
10737      break;
10738
10739    case OR_No_Viable_Function:
10740      Diag(UnresExpr->getMemberLoc(),
10741           diag::err_ovl_no_viable_member_function_in_call)
10742        << DeclName << MemExprE->getSourceRange();
10743      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10744                                  llvm::makeArrayRef(Args, NumArgs));
10745      // FIXME: Leaking incoming expressions!
10746      return ExprError();
10747
10748    case OR_Ambiguous:
10749      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10750        << DeclName << MemExprE->getSourceRange();
10751      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10752                                  llvm::makeArrayRef(Args, NumArgs));
10753      // FIXME: Leaking incoming expressions!
10754      return ExprError();
10755
10756    case OR_Deleted:
10757      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10758        << Best->Function->isDeleted()
10759        << DeclName
10760        << getDeletedOrUnavailableSuffix(Best->Function)
10761        << MemExprE->getSourceRange();
10762      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10763                                  llvm::makeArrayRef(Args, NumArgs));
10764      // FIXME: Leaking incoming expressions!
10765      return ExprError();
10766    }
10767
10768    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10769
10770    // If overload resolution picked a static member, build a
10771    // non-member call based on that function.
10772    if (Method->isStatic()) {
10773      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10774                                   Args, NumArgs, RParenLoc);
10775    }
10776
10777    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10778  }
10779
10780  QualType ResultType = Method->getResultType();
10781  ExprValueKind VK = Expr::getValueKindForType(ResultType);
10782  ResultType = ResultType.getNonLValueExprType(Context);
10783
10784  assert(Method && "Member call to something that isn't a method?");
10785  CXXMemberCallExpr *TheCall =
10786    new (Context) CXXMemberCallExpr(Context, MemExprE,
10787                                    llvm::makeArrayRef(Args, NumArgs),
10788                                    ResultType, VK, RParenLoc);
10789
10790  // Check for a valid return type.
10791  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10792                          TheCall, Method))
10793    return ExprError();
10794
10795  // Convert the object argument (for a non-static member function call).
10796  // We only need to do this if there was actually an overload; otherwise
10797  // it was done at lookup.
10798  if (!Method->isStatic()) {
10799    ExprResult ObjectArg =
10800      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10801                                          FoundDecl, Method);
10802    if (ObjectArg.isInvalid())
10803      return ExprError();
10804    MemExpr->setBase(ObjectArg.take());
10805  }
10806
10807  // Convert the rest of the arguments
10808  const FunctionProtoType *Proto =
10809    Method->getType()->getAs<FunctionProtoType>();
10810  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10811                              RParenLoc))
10812    return ExprError();
10813
10814  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10815
10816  if (CheckFunctionCall(Method, TheCall, Proto))
10817    return ExprError();
10818
10819  if ((isa<CXXConstructorDecl>(CurContext) ||
10820       isa<CXXDestructorDecl>(CurContext)) &&
10821      TheCall->getMethodDecl()->isPure()) {
10822    const CXXMethodDecl *MD = TheCall->getMethodDecl();
10823
10824    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10825      Diag(MemExpr->getLocStart(),
10826           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10827        << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10828        << MD->getParent()->getDeclName();
10829
10830      Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10831    }
10832  }
10833  return MaybeBindToTemporary(TheCall);
10834}
10835
10836/// BuildCallToObjectOfClassType - Build a call to an object of class
10837/// type (C++ [over.call.object]), which can end up invoking an
10838/// overloaded function call operator (@c operator()) or performing a
10839/// user-defined conversion on the object argument.
10840ExprResult
10841Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10842                                   SourceLocation LParenLoc,
10843                                   Expr **Args, unsigned NumArgs,
10844                                   SourceLocation RParenLoc) {
10845  if (checkPlaceholderForOverload(*this, Obj))
10846    return ExprError();
10847  ExprResult Object = Owned(Obj);
10848
10849  UnbridgedCastsSet UnbridgedCasts;
10850  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10851    return ExprError();
10852
10853  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10854  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10855
10856  // C++ [over.call.object]p1:
10857  //  If the primary-expression E in the function call syntax
10858  //  evaluates to a class object of type "cv T", then the set of
10859  //  candidate functions includes at least the function call
10860  //  operators of T. The function call operators of T are obtained by
10861  //  ordinary lookup of the name operator() in the context of
10862  //  (E).operator().
10863  OverloadCandidateSet CandidateSet(LParenLoc);
10864  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10865
10866  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10867                          diag::err_incomplete_object_call, Object.get()))
10868    return true;
10869
10870  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10871  LookupQualifiedName(R, Record->getDecl());
10872  R.suppressDiagnostics();
10873
10874  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10875       Oper != OperEnd; ++Oper) {
10876    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10877                       Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
10878                       /*SuppressUserConversions=*/ false);
10879  }
10880
10881  // C++ [over.call.object]p2:
10882  //   In addition, for each (non-explicit in C++0x) conversion function
10883  //   declared in T of the form
10884  //
10885  //        operator conversion-type-id () cv-qualifier;
10886  //
10887  //   where cv-qualifier is the same cv-qualification as, or a
10888  //   greater cv-qualification than, cv, and where conversion-type-id
10889  //   denotes the type "pointer to function of (P1,...,Pn) returning
10890  //   R", or the type "reference to pointer to function of
10891  //   (P1,...,Pn) returning R", or the type "reference to function
10892  //   of (P1,...,Pn) returning R", a surrogate call function [...]
10893  //   is also considered as a candidate function. Similarly,
10894  //   surrogate call functions are added to the set of candidate
10895  //   functions for each conversion function declared in an
10896  //   accessible base class provided the function is not hidden
10897  //   within T by another intervening declaration.
10898  std::pair<CXXRecordDecl::conversion_iterator,
10899            CXXRecordDecl::conversion_iterator> Conversions
10900    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
10901  for (CXXRecordDecl::conversion_iterator
10902         I = Conversions.first, E = Conversions.second; I != E; ++I) {
10903    NamedDecl *D = *I;
10904    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10905    if (isa<UsingShadowDecl>(D))
10906      D = cast<UsingShadowDecl>(D)->getTargetDecl();
10907
10908    // Skip over templated conversion functions; they aren't
10909    // surrogates.
10910    if (isa<FunctionTemplateDecl>(D))
10911      continue;
10912
10913    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
10914    if (!Conv->isExplicit()) {
10915      // Strip the reference type (if any) and then the pointer type (if
10916      // any) to get down to what might be a function type.
10917      QualType ConvType = Conv->getConversionType().getNonReferenceType();
10918      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10919        ConvType = ConvPtrType->getPointeeType();
10920
10921      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10922      {
10923        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10924                              Object.get(), llvm::makeArrayRef(Args, NumArgs),
10925                              CandidateSet);
10926      }
10927    }
10928  }
10929
10930  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10931
10932  // Perform overload resolution.
10933  OverloadCandidateSet::iterator Best;
10934  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
10935                             Best)) {
10936  case OR_Success:
10937    // Overload resolution succeeded; we'll build the appropriate call
10938    // below.
10939    break;
10940
10941  case OR_No_Viable_Function:
10942    if (CandidateSet.empty())
10943      Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
10944        << Object.get()->getType() << /*call*/ 1
10945        << Object.get()->getSourceRange();
10946    else
10947      Diag(Object.get()->getLocStart(),
10948           diag::err_ovl_no_viable_object_call)
10949        << Object.get()->getType() << Object.get()->getSourceRange();
10950    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10951                                llvm::makeArrayRef(Args, NumArgs));
10952    break;
10953
10954  case OR_Ambiguous:
10955    Diag(Object.get()->getLocStart(),
10956         diag::err_ovl_ambiguous_object_call)
10957      << Object.get()->getType() << Object.get()->getSourceRange();
10958    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10959                                llvm::makeArrayRef(Args, NumArgs));
10960    break;
10961
10962  case OR_Deleted:
10963    Diag(Object.get()->getLocStart(),
10964         diag::err_ovl_deleted_object_call)
10965      << Best->Function->isDeleted()
10966      << Object.get()->getType()
10967      << getDeletedOrUnavailableSuffix(Best->Function)
10968      << Object.get()->getSourceRange();
10969    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10970                                llvm::makeArrayRef(Args, NumArgs));
10971    break;
10972  }
10973
10974  if (Best == CandidateSet.end())
10975    return true;
10976
10977  UnbridgedCasts.restore();
10978
10979  if (Best->Function == 0) {
10980    // Since there is no function declaration, this is one of the
10981    // surrogate candidates. Dig out the conversion function.
10982    CXXConversionDecl *Conv
10983      = cast<CXXConversionDecl>(
10984                         Best->Conversions[0].UserDefined.ConversionFunction);
10985
10986    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10987    DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10988
10989    // We selected one of the surrogate functions that converts the
10990    // object parameter to a function pointer. Perform the conversion
10991    // on the object argument, then let ActOnCallExpr finish the job.
10992
10993    // Create an implicit member expr to refer to the conversion operator.
10994    // and then call it.
10995    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10996                                             Conv, HadMultipleCandidates);
10997    if (Call.isInvalid())
10998      return ExprError();
10999    // Record usage of conversion in an implicit cast.
11000    Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11001                                          CK_UserDefinedConversion,
11002                                          Call.get(), 0, VK_RValue));
11003
11004    return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
11005                         RParenLoc);
11006  }
11007
11008  MarkFunctionReferenced(LParenLoc, Best->Function);
11009  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11010  DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
11011
11012  // We found an overloaded operator(). Build a CXXOperatorCallExpr
11013  // that calls this method, using Object for the implicit object
11014  // parameter and passing along the remaining arguments.
11015  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11016
11017  // An error diagnostic has already been printed when parsing the declaration.
11018  if (Method->isInvalidDecl())
11019    return ExprError();
11020
11021  const FunctionProtoType *Proto =
11022    Method->getType()->getAs<FunctionProtoType>();
11023
11024  unsigned NumArgsInProto = Proto->getNumArgs();
11025  unsigned NumArgsToCheck = NumArgs;
11026
11027  // Build the full argument list for the method call (the
11028  // implicit object parameter is placed at the beginning of the
11029  // list).
11030  Expr **MethodArgs;
11031  if (NumArgs < NumArgsInProto) {
11032    NumArgsToCheck = NumArgsInProto;
11033    MethodArgs = new Expr*[NumArgsInProto + 1];
11034  } else {
11035    MethodArgs = new Expr*[NumArgs + 1];
11036  }
11037  MethodArgs[0] = Object.get();
11038  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11039    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
11040
11041  DeclarationNameInfo OpLocInfo(
11042               Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11043  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11044  ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
11045                                           HadMultipleCandidates,
11046                                           OpLocInfo.getLoc(),
11047                                           OpLocInfo.getInfo());
11048  if (NewFn.isInvalid())
11049    return true;
11050
11051  // Once we've built TheCall, all of the expressions are properly
11052  // owned.
11053  QualType ResultTy = Method->getResultType();
11054  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11055  ResultTy = ResultTy.getNonLValueExprType(Context);
11056
11057  CXXOperatorCallExpr *TheCall =
11058    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11059                                      llvm::makeArrayRef(MethodArgs, NumArgs+1),
11060                                      ResultTy, VK, RParenLoc, false);
11061  delete [] MethodArgs;
11062
11063  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11064                          Method))
11065    return true;
11066
11067  // We may have default arguments. If so, we need to allocate more
11068  // slots in the call for them.
11069  if (NumArgs < NumArgsInProto)
11070    TheCall->setNumArgs(Context, NumArgsInProto + 1);
11071  else if (NumArgs > NumArgsInProto)
11072    NumArgsToCheck = NumArgsInProto;
11073
11074  bool IsError = false;
11075
11076  // Initialize the implicit object parameter.
11077  ExprResult ObjRes =
11078    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11079                                        Best->FoundDecl, Method);
11080  if (ObjRes.isInvalid())
11081    IsError = true;
11082  else
11083    Object = ObjRes;
11084  TheCall->setArg(0, Object.take());
11085
11086  // Check the argument types.
11087  for (unsigned i = 0; i != NumArgsToCheck; i++) {
11088    Expr *Arg;
11089    if (i < NumArgs) {
11090      Arg = Args[i];
11091
11092      // Pass the argument.
11093
11094      ExprResult InputInit
11095        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11096                                                    Context,
11097                                                    Method->getParamDecl(i)),
11098                                    SourceLocation(), Arg);
11099
11100      IsError |= InputInit.isInvalid();
11101      Arg = InputInit.takeAs<Expr>();
11102    } else {
11103      ExprResult DefArg
11104        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11105      if (DefArg.isInvalid()) {
11106        IsError = true;
11107        break;
11108      }
11109
11110      Arg = DefArg.takeAs<Expr>();
11111    }
11112
11113    TheCall->setArg(i + 1, Arg);
11114  }
11115
11116  // If this is a variadic call, handle args passed through "...".
11117  if (Proto->isVariadic()) {
11118    // Promote the arguments (C99 6.5.2.2p7).
11119    for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
11120      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11121      IsError |= Arg.isInvalid();
11122      TheCall->setArg(i + 1, Arg.take());
11123    }
11124  }
11125
11126  if (IsError) return true;
11127
11128  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11129
11130  if (CheckFunctionCall(Method, TheCall, Proto))
11131    return true;
11132
11133  return MaybeBindToTemporary(TheCall);
11134}
11135
11136/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11137///  (if one exists), where @c Base is an expression of class type and
11138/// @c Member is the name of the member we're trying to find.
11139ExprResult
11140Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
11141  assert(Base->getType()->isRecordType() &&
11142         "left-hand side must have class type");
11143
11144  if (checkPlaceholderForOverload(*this, Base))
11145    return ExprError();
11146
11147  SourceLocation Loc = Base->getExprLoc();
11148
11149  // C++ [over.ref]p1:
11150  //
11151  //   [...] An expression x->m is interpreted as (x.operator->())->m
11152  //   for a class object x of type T if T::operator->() exists and if
11153  //   the operator is selected as the best match function by the
11154  //   overload resolution mechanism (13.3).
11155  DeclarationName OpName =
11156    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11157  OverloadCandidateSet CandidateSet(Loc);
11158  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11159
11160  if (RequireCompleteType(Loc, Base->getType(),
11161                          diag::err_typecheck_incomplete_tag, Base))
11162    return ExprError();
11163
11164  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11165  LookupQualifiedName(R, BaseRecord->getDecl());
11166  R.suppressDiagnostics();
11167
11168  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11169       Oper != OperEnd; ++Oper) {
11170    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11171                       0, 0, CandidateSet, /*SuppressUserConversions=*/false);
11172  }
11173
11174  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11175
11176  // Perform overload resolution.
11177  OverloadCandidateSet::iterator Best;
11178  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11179  case OR_Success:
11180    // Overload resolution succeeded; we'll build the call below.
11181    break;
11182
11183  case OR_No_Viable_Function:
11184    if (CandidateSet.empty())
11185      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11186        << Base->getType() << Base->getSourceRange();
11187    else
11188      Diag(OpLoc, diag::err_ovl_no_viable_oper)
11189        << "operator->" << Base->getSourceRange();
11190    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11191    return ExprError();
11192
11193  case OR_Ambiguous:
11194    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11195      << "->" << Base->getType() << Base->getSourceRange();
11196    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11197    return ExprError();
11198
11199  case OR_Deleted:
11200    Diag(OpLoc,  diag::err_ovl_deleted_oper)
11201      << Best->Function->isDeleted()
11202      << "->"
11203      << getDeletedOrUnavailableSuffix(Best->Function)
11204      << Base->getSourceRange();
11205    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11206    return ExprError();
11207  }
11208
11209  MarkFunctionReferenced(OpLoc, Best->Function);
11210  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11211  DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
11212
11213  // Convert the object parameter.
11214  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11215  ExprResult BaseResult =
11216    PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11217                                        Best->FoundDecl, Method);
11218  if (BaseResult.isInvalid())
11219    return ExprError();
11220  Base = BaseResult.take();
11221
11222  // Build the operator call.
11223  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
11224                                            HadMultipleCandidates, OpLoc);
11225  if (FnExpr.isInvalid())
11226    return ExprError();
11227
11228  QualType ResultTy = Method->getResultType();
11229  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11230  ResultTy = ResultTy.getNonLValueExprType(Context);
11231  CXXOperatorCallExpr *TheCall =
11232    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11233                                      Base, ResultTy, VK, OpLoc, false);
11234
11235  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11236                          Method))
11237          return ExprError();
11238
11239  return MaybeBindToTemporary(TheCall);
11240}
11241
11242/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11243/// a literal operator described by the provided lookup results.
11244ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11245                                          DeclarationNameInfo &SuffixInfo,
11246                                          ArrayRef<Expr*> Args,
11247                                          SourceLocation LitEndLoc,
11248                                       TemplateArgumentListInfo *TemplateArgs) {
11249  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11250
11251  OverloadCandidateSet CandidateSet(UDSuffixLoc);
11252  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11253                        TemplateArgs);
11254
11255  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11256
11257  // Perform overload resolution. This will usually be trivial, but might need
11258  // to perform substitutions for a literal operator template.
11259  OverloadCandidateSet::iterator Best;
11260  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11261  case OR_Success:
11262  case OR_Deleted:
11263    break;
11264
11265  case OR_No_Viable_Function:
11266    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11267      << R.getLookupName();
11268    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11269    return ExprError();
11270
11271  case OR_Ambiguous:
11272    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11273    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11274    return ExprError();
11275  }
11276
11277  FunctionDecl *FD = Best->Function;
11278  MarkFunctionReferenced(UDSuffixLoc, FD);
11279  DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
11280
11281  ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11282                                        SuffixInfo.getLoc(),
11283                                        SuffixInfo.getInfo());
11284  if (Fn.isInvalid())
11285    return true;
11286
11287  // Check the argument types. This should almost always be a no-op, except
11288  // that array-to-pointer decay is applied to string literals.
11289  Expr *ConvArgs[2];
11290  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11291    ExprResult InputInit = PerformCopyInitialization(
11292      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11293      SourceLocation(), Args[ArgIdx]);
11294    if (InputInit.isInvalid())
11295      return true;
11296    ConvArgs[ArgIdx] = InputInit.take();
11297  }
11298
11299  QualType ResultTy = FD->getResultType();
11300  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11301  ResultTy = ResultTy.getNonLValueExprType(Context);
11302
11303  UserDefinedLiteral *UDL =
11304    new (Context) UserDefinedLiteral(Context, Fn.take(),
11305                                     llvm::makeArrayRef(ConvArgs, Args.size()),
11306                                     ResultTy, VK, LitEndLoc, UDSuffixLoc);
11307
11308  if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11309    return ExprError();
11310
11311  if (CheckFunctionCall(FD, UDL, NULL))
11312    return ExprError();
11313
11314  return MaybeBindToTemporary(UDL);
11315}
11316
11317/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11318/// given LookupResult is non-empty, it is assumed to describe a member which
11319/// will be invoked. Otherwise, the function will be found via argument
11320/// dependent lookup.
11321/// CallExpr is set to a valid expression and FRS_Success returned on success,
11322/// otherwise CallExpr is set to ExprError() and some non-success value
11323/// is returned.
11324Sema::ForRangeStatus
11325Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11326                                SourceLocation RangeLoc, VarDecl *Decl,
11327                                BeginEndFunction BEF,
11328                                const DeclarationNameInfo &NameInfo,
11329                                LookupResult &MemberLookup,
11330                                OverloadCandidateSet *CandidateSet,
11331                                Expr *Range, ExprResult *CallExpr) {
11332  CandidateSet->clear();
11333  if (!MemberLookup.empty()) {
11334    ExprResult MemberRef =
11335        BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11336                                 /*IsPtr=*/false, CXXScopeSpec(),
11337                                 /*TemplateKWLoc=*/SourceLocation(),
11338                                 /*FirstQualifierInScope=*/0,
11339                                 MemberLookup,
11340                                 /*TemplateArgs=*/0);
11341    if (MemberRef.isInvalid()) {
11342      *CallExpr = ExprError();
11343      Diag(Range->getLocStart(), diag::note_in_for_range)
11344          << RangeLoc << BEF << Range->getType();
11345      return FRS_DiagnosticIssued;
11346    }
11347    *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11348    if (CallExpr->isInvalid()) {
11349      *CallExpr = ExprError();
11350      Diag(Range->getLocStart(), diag::note_in_for_range)
11351          << RangeLoc << BEF << Range->getType();
11352      return FRS_DiagnosticIssued;
11353    }
11354  } else {
11355    UnresolvedSet<0> FoundNames;
11356    UnresolvedLookupExpr *Fn =
11357      UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11358                                   NestedNameSpecifierLoc(), NameInfo,
11359                                   /*NeedsADL=*/true, /*Overloaded=*/false,
11360                                   FoundNames.begin(), FoundNames.end());
11361
11362    bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11363                                                    CandidateSet, CallExpr);
11364    if (CandidateSet->empty() || CandidateSetError) {
11365      *CallExpr = ExprError();
11366      return FRS_NoViableFunction;
11367    }
11368    OverloadCandidateSet::iterator Best;
11369    OverloadingResult OverloadResult =
11370        CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11371
11372    if (OverloadResult == OR_No_Viable_Function) {
11373      *CallExpr = ExprError();
11374      return FRS_NoViableFunction;
11375    }
11376    *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11377                                         Loc, 0, CandidateSet, &Best,
11378                                         OverloadResult,
11379                                         /*AllowTypoCorrection=*/false);
11380    if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11381      *CallExpr = ExprError();
11382      Diag(Range->getLocStart(), diag::note_in_for_range)
11383          << RangeLoc << BEF << Range->getType();
11384      return FRS_DiagnosticIssued;
11385    }
11386  }
11387  return FRS_Success;
11388}
11389
11390
11391/// FixOverloadedFunctionReference - E is an expression that refers to
11392/// a C++ overloaded function (possibly with some parentheses and
11393/// perhaps a '&' around it). We have resolved the overloaded function
11394/// to the function declaration Fn, so patch up the expression E to
11395/// refer (possibly indirectly) to Fn. Returns the new expr.
11396Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11397                                           FunctionDecl *Fn) {
11398  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11399    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11400                                                   Found, Fn);
11401    if (SubExpr == PE->getSubExpr())
11402      return PE;
11403
11404    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11405  }
11406
11407  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11408    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11409                                                   Found, Fn);
11410    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11411                               SubExpr->getType()) &&
11412           "Implicit cast type cannot be determined from overload");
11413    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11414    if (SubExpr == ICE->getSubExpr())
11415      return ICE;
11416
11417    return ImplicitCastExpr::Create(Context, ICE->getType(),
11418                                    ICE->getCastKind(),
11419                                    SubExpr, 0,
11420                                    ICE->getValueKind());
11421  }
11422
11423  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11424    assert(UnOp->getOpcode() == UO_AddrOf &&
11425           "Can only take the address of an overloaded function");
11426    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11427      if (Method->isStatic()) {
11428        // Do nothing: static member functions aren't any different
11429        // from non-member functions.
11430      } else {
11431        // Fix the sub expression, which really has to be an
11432        // UnresolvedLookupExpr holding an overloaded member function
11433        // or template.
11434        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11435                                                       Found, Fn);
11436        if (SubExpr == UnOp->getSubExpr())
11437          return UnOp;
11438
11439        assert(isa<DeclRefExpr>(SubExpr)
11440               && "fixed to something other than a decl ref");
11441        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11442               && "fixed to a member ref with no nested name qualifier");
11443
11444        // We have taken the address of a pointer to member
11445        // function. Perform the computation here so that we get the
11446        // appropriate pointer to member type.
11447        QualType ClassType
11448          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11449        QualType MemPtrType
11450          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11451
11452        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11453                                           VK_RValue, OK_Ordinary,
11454                                           UnOp->getOperatorLoc());
11455      }
11456    }
11457    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11458                                                   Found, Fn);
11459    if (SubExpr == UnOp->getSubExpr())
11460      return UnOp;
11461
11462    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11463                                     Context.getPointerType(SubExpr->getType()),
11464                                       VK_RValue, OK_Ordinary,
11465                                       UnOp->getOperatorLoc());
11466  }
11467
11468  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11469    // FIXME: avoid copy.
11470    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11471    if (ULE->hasExplicitTemplateArgs()) {
11472      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11473      TemplateArgs = &TemplateArgsBuffer;
11474    }
11475
11476    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11477                                           ULE->getQualifierLoc(),
11478                                           ULE->getTemplateKeywordLoc(),
11479                                           Fn,
11480                                           /*enclosing*/ false, // FIXME?
11481                                           ULE->getNameLoc(),
11482                                           Fn->getType(),
11483                                           VK_LValue,
11484                                           Found.getDecl(),
11485                                           TemplateArgs);
11486    MarkDeclRefReferenced(DRE);
11487    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11488    return DRE;
11489  }
11490
11491  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11492    // FIXME: avoid copy.
11493    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11494    if (MemExpr->hasExplicitTemplateArgs()) {
11495      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11496      TemplateArgs = &TemplateArgsBuffer;
11497    }
11498
11499    Expr *Base;
11500
11501    // If we're filling in a static method where we used to have an
11502    // implicit member access, rewrite to a simple decl ref.
11503    if (MemExpr->isImplicitAccess()) {
11504      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11505        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11506                                               MemExpr->getQualifierLoc(),
11507                                               MemExpr->getTemplateKeywordLoc(),
11508                                               Fn,
11509                                               /*enclosing*/ false,
11510                                               MemExpr->getMemberLoc(),
11511                                               Fn->getType(),
11512                                               VK_LValue,
11513                                               Found.getDecl(),
11514                                               TemplateArgs);
11515        MarkDeclRefReferenced(DRE);
11516        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11517        return DRE;
11518      } else {
11519        SourceLocation Loc = MemExpr->getMemberLoc();
11520        if (MemExpr->getQualifier())
11521          Loc = MemExpr->getQualifierLoc().getBeginLoc();
11522        CheckCXXThisCapture(Loc);
11523        Base = new (Context) CXXThisExpr(Loc,
11524                                         MemExpr->getBaseType(),
11525                                         /*isImplicit=*/true);
11526      }
11527    } else
11528      Base = MemExpr->getBase();
11529
11530    ExprValueKind valueKind;
11531    QualType type;
11532    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11533      valueKind = VK_LValue;
11534      type = Fn->getType();
11535    } else {
11536      valueKind = VK_RValue;
11537      type = Context.BoundMemberTy;
11538    }
11539
11540    MemberExpr *ME = MemberExpr::Create(Context, Base,
11541                                        MemExpr->isArrow(),
11542                                        MemExpr->getQualifierLoc(),
11543                                        MemExpr->getTemplateKeywordLoc(),
11544                                        Fn,
11545                                        Found,
11546                                        MemExpr->getMemberNameInfo(),
11547                                        TemplateArgs,
11548                                        type, valueKind, OK_Ordinary);
11549    ME->setHadMultipleCandidates(true);
11550    MarkMemberReferenced(ME);
11551    return ME;
11552  }
11553
11554  llvm_unreachable("Invalid reference to overloaded function");
11555}
11556
11557ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11558                                                DeclAccessPair Found,
11559                                                FunctionDecl *Fn) {
11560  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11561}
11562
11563} // end namespace clang
11564