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