SemaOverload.cpp revision 14d0aee957f11b9613fa4312919bec3cc5456a1c
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 Expr *
40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41                      SourceLocation Loc = SourceLocation()) {
42  Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
43  S.DefaultFunctionArrayConversion(E);
44  return E;
45}
46
47static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
48                                 bool InOverloadResolution,
49                                 StandardConversionSequence &SCS,
50                                 bool CStyle);
51static OverloadingResult
52IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
53                        UserDefinedConversionSequence& User,
54                        OverloadCandidateSet& Conversions,
55                        bool AllowExplicit);
56
57
58static ImplicitConversionSequence::CompareKind
59CompareStandardConversionSequences(Sema &S,
60                                   const StandardConversionSequence& SCS1,
61                                   const StandardConversionSequence& SCS2);
62
63static ImplicitConversionSequence::CompareKind
64CompareQualificationConversions(Sema &S,
65                                const StandardConversionSequence& SCS1,
66                                const StandardConversionSequence& SCS2);
67
68static ImplicitConversionSequence::CompareKind
69CompareDerivedToBaseConversions(Sema &S,
70                                const StandardConversionSequence& SCS1,
71                                const StandardConversionSequence& SCS2);
72
73
74
75/// GetConversionCategory - Retrieve the implicit conversion
76/// category corresponding to the given implicit conversion kind.
77ImplicitConversionCategory
78GetConversionCategory(ImplicitConversionKind Kind) {
79  static const ImplicitConversionCategory
80    Category[(int)ICK_Num_Conversion_Kinds] = {
81    ICC_Identity,
82    ICC_Lvalue_Transformation,
83    ICC_Lvalue_Transformation,
84    ICC_Lvalue_Transformation,
85    ICC_Identity,
86    ICC_Qualification_Adjustment,
87    ICC_Promotion,
88    ICC_Promotion,
89    ICC_Promotion,
90    ICC_Conversion,
91    ICC_Conversion,
92    ICC_Conversion,
93    ICC_Conversion,
94    ICC_Conversion,
95    ICC_Conversion,
96    ICC_Conversion,
97    ICC_Conversion,
98    ICC_Conversion,
99    ICC_Conversion,
100    ICC_Conversion,
101    ICC_Conversion
102  };
103  return Category[(int)Kind];
104}
105
106/// GetConversionRank - Retrieve the implicit conversion rank
107/// corresponding to the given implicit conversion kind.
108ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
109  static const ImplicitConversionRank
110    Rank[(int)ICK_Num_Conversion_Kinds] = {
111    ICR_Exact_Match,
112    ICR_Exact_Match,
113    ICR_Exact_Match,
114    ICR_Exact_Match,
115    ICR_Exact_Match,
116    ICR_Exact_Match,
117    ICR_Promotion,
118    ICR_Promotion,
119    ICR_Promotion,
120    ICR_Conversion,
121    ICR_Conversion,
122    ICR_Conversion,
123    ICR_Conversion,
124    ICR_Conversion,
125    ICR_Conversion,
126    ICR_Conversion,
127    ICR_Conversion,
128    ICR_Conversion,
129    ICR_Conversion,
130    ICR_Conversion,
131    ICR_Complex_Real_Conversion
132  };
133  return Rank[(int)Kind];
134}
135
136/// GetImplicitConversionName - Return the name of this kind of
137/// implicit conversion.
138const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
139  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
140    "No conversion",
141    "Lvalue-to-rvalue",
142    "Array-to-pointer",
143    "Function-to-pointer",
144    "Noreturn adjustment",
145    "Qualification",
146    "Integral promotion",
147    "Floating point promotion",
148    "Complex promotion",
149    "Integral conversion",
150    "Floating conversion",
151    "Complex conversion",
152    "Floating-integral conversion",
153    "Pointer conversion",
154    "Pointer-to-member conversion",
155    "Boolean conversion",
156    "Compatible-types conversion",
157    "Derived-to-base conversion",
158    "Vector conversion",
159    "Vector splat",
160    "Complex-real conversion"
161  };
162  return Name[Kind];
163}
164
165/// StandardConversionSequence - Set the standard conversion
166/// sequence to the identity conversion.
167void StandardConversionSequence::setAsIdentityConversion() {
168  First = ICK_Identity;
169  Second = ICK_Identity;
170  Third = ICK_Identity;
171  DeprecatedStringLiteralToCharPtr = false;
172  ReferenceBinding = false;
173  DirectBinding = false;
174  IsLvalueReference = true;
175  BindsToFunctionLvalue = false;
176  BindsToRvalue = false;
177  BindsImplicitObjectArgumentWithoutRefQualifier = false;
178  CopyConstructor = 0;
179}
180
181/// getRank - Retrieve the rank of this standard conversion sequence
182/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
183/// implicit conversions.
184ImplicitConversionRank StandardConversionSequence::getRank() const {
185  ImplicitConversionRank Rank = ICR_Exact_Match;
186  if  (GetConversionRank(First) > Rank)
187    Rank = GetConversionRank(First);
188  if  (GetConversionRank(Second) > Rank)
189    Rank = GetConversionRank(Second);
190  if  (GetConversionRank(Third) > Rank)
191    Rank = GetConversionRank(Third);
192  return Rank;
193}
194
195/// isPointerConversionToBool - Determines whether this conversion is
196/// a conversion of a pointer or pointer-to-member to bool. This is
197/// used as part of the ranking of standard conversion sequences
198/// (C++ 13.3.3.2p4).
199bool StandardConversionSequence::isPointerConversionToBool() const {
200  // Note that FromType has not necessarily been transformed by the
201  // array-to-pointer or function-to-pointer implicit conversions, so
202  // check for their presence as well as checking whether FromType is
203  // a pointer.
204  if (getToType(1)->isBooleanType() &&
205      (getFromType()->isPointerType() ||
206       getFromType()->isObjCObjectPointerType() ||
207       getFromType()->isBlockPointerType() ||
208       getFromType()->isNullPtrType() ||
209       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
210    return true;
211
212  return false;
213}
214
215/// isPointerConversionToVoidPointer - Determines whether this
216/// conversion is a conversion of a pointer to a void pointer. This is
217/// used as part of the ranking of standard conversion sequences (C++
218/// 13.3.3.2p4).
219bool
220StandardConversionSequence::
221isPointerConversionToVoidPointer(ASTContext& Context) const {
222  QualType FromType = getFromType();
223  QualType ToType = getToType(1);
224
225  // Note that FromType has not necessarily been transformed by the
226  // array-to-pointer implicit conversion, so check for its presence
227  // and redo the conversion to get a pointer.
228  if (First == ICK_Array_To_Pointer)
229    FromType = Context.getArrayDecayedType(FromType);
230
231  if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
232    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
233      return ToPtrType->getPointeeType()->isVoidType();
234
235  return false;
236}
237
238/// DebugPrint - Print this standard conversion sequence to standard
239/// error. Useful for debugging overloading issues.
240void StandardConversionSequence::DebugPrint() const {
241  llvm::raw_ostream &OS = llvm::errs();
242  bool PrintedSomething = false;
243  if (First != ICK_Identity) {
244    OS << GetImplicitConversionName(First);
245    PrintedSomething = true;
246  }
247
248  if (Second != ICK_Identity) {
249    if (PrintedSomething) {
250      OS << " -> ";
251    }
252    OS << GetImplicitConversionName(Second);
253
254    if (CopyConstructor) {
255      OS << " (by copy constructor)";
256    } else if (DirectBinding) {
257      OS << " (direct reference binding)";
258    } else if (ReferenceBinding) {
259      OS << " (reference binding)";
260    }
261    PrintedSomething = true;
262  }
263
264  if (Third != ICK_Identity) {
265    if (PrintedSomething) {
266      OS << " -> ";
267    }
268    OS << GetImplicitConversionName(Third);
269    PrintedSomething = true;
270  }
271
272  if (!PrintedSomething) {
273    OS << "No conversions required";
274  }
275}
276
277/// DebugPrint - Print this user-defined conversion sequence to standard
278/// error. Useful for debugging overloading issues.
279void UserDefinedConversionSequence::DebugPrint() const {
280  llvm::raw_ostream &OS = llvm::errs();
281  if (Before.First || Before.Second || Before.Third) {
282    Before.DebugPrint();
283    OS << " -> ";
284  }
285  OS << '\'' << ConversionFunction << '\'';
286  if (After.First || After.Second || After.Third) {
287    OS << " -> ";
288    After.DebugPrint();
289  }
290}
291
292/// DebugPrint - Print this implicit conversion sequence to standard
293/// error. Useful for debugging overloading issues.
294void ImplicitConversionSequence::DebugPrint() const {
295  llvm::raw_ostream &OS = llvm::errs();
296  switch (ConversionKind) {
297  case StandardConversion:
298    OS << "Standard conversion: ";
299    Standard.DebugPrint();
300    break;
301  case UserDefinedConversion:
302    OS << "User-defined conversion: ";
303    UserDefined.DebugPrint();
304    break;
305  case EllipsisConversion:
306    OS << "Ellipsis conversion";
307    break;
308  case AmbiguousConversion:
309    OS << "Ambiguous conversion";
310    break;
311  case BadConversion:
312    OS << "Bad conversion";
313    break;
314  }
315
316  OS << "\n";
317}
318
319void AmbiguousConversionSequence::construct() {
320  new (&conversions()) ConversionSet();
321}
322
323void AmbiguousConversionSequence::destruct() {
324  conversions().~ConversionSet();
325}
326
327void
328AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
329  FromTypePtr = O.FromTypePtr;
330  ToTypePtr = O.ToTypePtr;
331  new (&conversions()) ConversionSet(O.conversions());
332}
333
334namespace {
335  // Structure used by OverloadCandidate::DeductionFailureInfo to store
336  // template parameter and template argument information.
337  struct DFIParamWithArguments {
338    TemplateParameter Param;
339    TemplateArgument FirstArg;
340    TemplateArgument SecondArg;
341  };
342}
343
344/// \brief Convert from Sema's representation of template deduction information
345/// to the form used in overload-candidate information.
346OverloadCandidate::DeductionFailureInfo
347static MakeDeductionFailureInfo(ASTContext &Context,
348                                Sema::TemplateDeductionResult TDK,
349                                TemplateDeductionInfo &Info) {
350  OverloadCandidate::DeductionFailureInfo Result;
351  Result.Result = static_cast<unsigned>(TDK);
352  Result.Data = 0;
353  switch (TDK) {
354  case Sema::TDK_Success:
355  case Sema::TDK_InstantiationDepth:
356  case Sema::TDK_TooManyArguments:
357  case Sema::TDK_TooFewArguments:
358    break;
359
360  case Sema::TDK_Incomplete:
361  case Sema::TDK_InvalidExplicitArguments:
362    Result.Data = Info.Param.getOpaqueValue();
363    break;
364
365  case Sema::TDK_Inconsistent:
366  case Sema::TDK_Underqualified: {
367    // FIXME: Should allocate from normal heap so that we can free this later.
368    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
369    Saved->Param = Info.Param;
370    Saved->FirstArg = Info.FirstArg;
371    Saved->SecondArg = Info.SecondArg;
372    Result.Data = Saved;
373    break;
374  }
375
376  case Sema::TDK_SubstitutionFailure:
377    Result.Data = Info.take();
378    break;
379
380  case Sema::TDK_NonDeducedMismatch:
381  case Sema::TDK_FailedOverloadResolution:
382    break;
383  }
384
385  return Result;
386}
387
388void OverloadCandidate::DeductionFailureInfo::Destroy() {
389  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
390  case Sema::TDK_Success:
391  case Sema::TDK_InstantiationDepth:
392  case Sema::TDK_Incomplete:
393  case Sema::TDK_TooManyArguments:
394  case Sema::TDK_TooFewArguments:
395  case Sema::TDK_InvalidExplicitArguments:
396    break;
397
398  case Sema::TDK_Inconsistent:
399  case Sema::TDK_Underqualified:
400    // FIXME: Destroy the data?
401    Data = 0;
402    break;
403
404  case Sema::TDK_SubstitutionFailure:
405    // FIXME: Destroy the template arugment list?
406    Data = 0;
407    break;
408
409  // Unhandled
410  case Sema::TDK_NonDeducedMismatch:
411  case Sema::TDK_FailedOverloadResolution:
412    break;
413  }
414}
415
416TemplateParameter
417OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
418  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
419  case Sema::TDK_Success:
420  case Sema::TDK_InstantiationDepth:
421  case Sema::TDK_TooManyArguments:
422  case Sema::TDK_TooFewArguments:
423  case Sema::TDK_SubstitutionFailure:
424    return TemplateParameter();
425
426  case Sema::TDK_Incomplete:
427  case Sema::TDK_InvalidExplicitArguments:
428    return TemplateParameter::getFromOpaqueValue(Data);
429
430  case Sema::TDK_Inconsistent:
431  case Sema::TDK_Underqualified:
432    return static_cast<DFIParamWithArguments*>(Data)->Param;
433
434  // Unhandled
435  case Sema::TDK_NonDeducedMismatch:
436  case Sema::TDK_FailedOverloadResolution:
437    break;
438  }
439
440  return TemplateParameter();
441}
442
443TemplateArgumentList *
444OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
445  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
446    case Sema::TDK_Success:
447    case Sema::TDK_InstantiationDepth:
448    case Sema::TDK_TooManyArguments:
449    case Sema::TDK_TooFewArguments:
450    case Sema::TDK_Incomplete:
451    case Sema::TDK_InvalidExplicitArguments:
452    case Sema::TDK_Inconsistent:
453    case Sema::TDK_Underqualified:
454      return 0;
455
456    case Sema::TDK_SubstitutionFailure:
457      return static_cast<TemplateArgumentList*>(Data);
458
459    // Unhandled
460    case Sema::TDK_NonDeducedMismatch:
461    case Sema::TDK_FailedOverloadResolution:
462      break;
463  }
464
465  return 0;
466}
467
468const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
469  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
470  case Sema::TDK_Success:
471  case Sema::TDK_InstantiationDepth:
472  case Sema::TDK_Incomplete:
473  case Sema::TDK_TooManyArguments:
474  case Sema::TDK_TooFewArguments:
475  case Sema::TDK_InvalidExplicitArguments:
476  case Sema::TDK_SubstitutionFailure:
477    return 0;
478
479  case Sema::TDK_Inconsistent:
480  case Sema::TDK_Underqualified:
481    return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
482
483  // Unhandled
484  case Sema::TDK_NonDeducedMismatch:
485  case Sema::TDK_FailedOverloadResolution:
486    break;
487  }
488
489  return 0;
490}
491
492const TemplateArgument *
493OverloadCandidate::DeductionFailureInfo::getSecondArg() {
494  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
495  case Sema::TDK_Success:
496  case Sema::TDK_InstantiationDepth:
497  case Sema::TDK_Incomplete:
498  case Sema::TDK_TooManyArguments:
499  case Sema::TDK_TooFewArguments:
500  case Sema::TDK_InvalidExplicitArguments:
501  case Sema::TDK_SubstitutionFailure:
502    return 0;
503
504  case Sema::TDK_Inconsistent:
505  case Sema::TDK_Underqualified:
506    return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
507
508  // Unhandled
509  case Sema::TDK_NonDeducedMismatch:
510  case Sema::TDK_FailedOverloadResolution:
511    break;
512  }
513
514  return 0;
515}
516
517void OverloadCandidateSet::clear() {
518  inherited::clear();
519  Functions.clear();
520}
521
522// IsOverload - Determine whether the given New declaration is an
523// overload of the declarations in Old. This routine returns false if
524// New and Old cannot be overloaded, e.g., if New has the same
525// signature as some function in Old (C++ 1.3.10) or if the Old
526// declarations aren't functions (or function templates) at all. When
527// it does return false, MatchedDecl will point to the decl that New
528// cannot be overloaded with.  This decl may be a UsingShadowDecl on
529// top of the underlying declaration.
530//
531// Example: Given the following input:
532//
533//   void f(int, float); // #1
534//   void f(int, int); // #2
535//   int f(int, int); // #3
536//
537// When we process #1, there is no previous declaration of "f",
538// so IsOverload will not be used.
539//
540// When we process #2, Old contains only the FunctionDecl for #1.  By
541// comparing the parameter types, we see that #1 and #2 are overloaded
542// (since they have different signatures), so this routine returns
543// false; MatchedDecl is unchanged.
544//
545// When we process #3, Old is an overload set containing #1 and #2. We
546// compare the signatures of #3 to #1 (they're overloaded, so we do
547// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
548// identical (return types of functions are not part of the
549// signature), IsOverload returns false and MatchedDecl will be set to
550// point to the FunctionDecl for #2.
551//
552// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
553// into a class by a using declaration.  The rules for whether to hide
554// shadow declarations ignore some properties which otherwise figure
555// into a function template's signature.
556Sema::OverloadKind
557Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
558                    NamedDecl *&Match, bool NewIsUsingDecl) {
559  for (LookupResult::iterator I = Old.begin(), E = Old.end();
560         I != E; ++I) {
561    NamedDecl *OldD = *I;
562
563    bool OldIsUsingDecl = false;
564    if (isa<UsingShadowDecl>(OldD)) {
565      OldIsUsingDecl = true;
566
567      // We can always introduce two using declarations into the same
568      // context, even if they have identical signatures.
569      if (NewIsUsingDecl) continue;
570
571      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
572    }
573
574    // If either declaration was introduced by a using declaration,
575    // we'll need to use slightly different rules for matching.
576    // Essentially, these rules are the normal rules, except that
577    // function templates hide function templates with different
578    // return types or template parameter lists.
579    bool UseMemberUsingDeclRules =
580      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
581
582    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
583      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
584        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
585          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
586          continue;
587        }
588
589        Match = *I;
590        return Ovl_Match;
591      }
592    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
593      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
594        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
595          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
596          continue;
597        }
598
599        Match = *I;
600        return Ovl_Match;
601      }
602    } else if (isa<UsingDecl>(OldD)) {
603      // We can overload with these, which can show up when doing
604      // redeclaration checks for UsingDecls.
605      assert(Old.getLookupKind() == LookupUsingDeclName);
606    } else if (isa<TagDecl>(OldD)) {
607      // We can always overload with tags by hiding them.
608    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
609      // Optimistically assume that an unresolved using decl will
610      // overload; if it doesn't, we'll have to diagnose during
611      // template instantiation.
612    } else {
613      // (C++ 13p1):
614      //   Only function declarations can be overloaded; object and type
615      //   declarations cannot be overloaded.
616      Match = *I;
617      return Ovl_NonFunction;
618    }
619  }
620
621  return Ovl_Overload;
622}
623
624bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
625                      bool UseUsingDeclRules) {
626  // If both of the functions are extern "C", then they are not
627  // overloads.
628  if (Old->isExternC() && New->isExternC())
629    return false;
630
631  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
632  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
633
634  // C++ [temp.fct]p2:
635  //   A function template can be overloaded with other function templates
636  //   and with normal (non-template) functions.
637  if ((OldTemplate == 0) != (NewTemplate == 0))
638    return true;
639
640  // Is the function New an overload of the function Old?
641  QualType OldQType = Context.getCanonicalType(Old->getType());
642  QualType NewQType = Context.getCanonicalType(New->getType());
643
644  // Compare the signatures (C++ 1.3.10) of the two functions to
645  // determine whether they are overloads. If we find any mismatch
646  // in the signature, they are overloads.
647
648  // If either of these functions is a K&R-style function (no
649  // prototype), then we consider them to have matching signatures.
650  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
651      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
652    return false;
653
654  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
655  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
656
657  // The signature of a function includes the types of its
658  // parameters (C++ 1.3.10), which includes the presence or absence
659  // of the ellipsis; see C++ DR 357).
660  if (OldQType != NewQType &&
661      (OldType->getNumArgs() != NewType->getNumArgs() ||
662       OldType->isVariadic() != NewType->isVariadic() ||
663       !FunctionArgTypesAreEqual(OldType, NewType)))
664    return true;
665
666  // C++ [temp.over.link]p4:
667  //   The signature of a function template consists of its function
668  //   signature, its return type and its template parameter list. The names
669  //   of the template parameters are significant only for establishing the
670  //   relationship between the template parameters and the rest of the
671  //   signature.
672  //
673  // We check the return type and template parameter lists for function
674  // templates first; the remaining checks follow.
675  //
676  // However, we don't consider either of these when deciding whether
677  // a member introduced by a shadow declaration is hidden.
678  if (!UseUsingDeclRules && NewTemplate &&
679      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
680                                       OldTemplate->getTemplateParameters(),
681                                       false, TPL_TemplateMatch) ||
682       OldType->getResultType() != NewType->getResultType()))
683    return true;
684
685  // If the function is a class member, its signature includes the
686  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
687  //
688  // As part of this, also check whether one of the member functions
689  // is static, in which case they are not overloads (C++
690  // 13.1p2). While not part of the definition of the signature,
691  // this check is important to determine whether these functions
692  // can be overloaded.
693  CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
694  CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
695  if (OldMethod && NewMethod &&
696      !OldMethod->isStatic() && !NewMethod->isStatic() &&
697      (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
698       OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
699    if (!UseUsingDeclRules &&
700        OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
701        (OldMethod->getRefQualifier() == RQ_None ||
702         NewMethod->getRefQualifier() == RQ_None)) {
703      // C++0x [over.load]p2:
704      //   - Member function declarations with the same name and the same
705      //     parameter-type-list as well as member function template
706      //     declarations with the same name, the same parameter-type-list, and
707      //     the same template parameter lists cannot be overloaded if any of
708      //     them, but not all, have a ref-qualifier (8.3.5).
709      Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
710        << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
711      Diag(OldMethod->getLocation(), diag::note_previous_declaration);
712    }
713
714    return true;
715  }
716
717  // The signatures match; this is not an overload.
718  return false;
719}
720
721/// TryImplicitConversion - Attempt to perform an implicit conversion
722/// from the given expression (Expr) to the given type (ToType). This
723/// function returns an implicit conversion sequence that can be used
724/// to perform the initialization. Given
725///
726///   void f(float f);
727///   void g(int i) { f(i); }
728///
729/// this routine would produce an implicit conversion sequence to
730/// describe the initialization of f from i, which will be a standard
731/// conversion sequence containing an lvalue-to-rvalue conversion (C++
732/// 4.1) followed by a floating-integral conversion (C++ 4.9).
733//
734/// Note that this routine only determines how the conversion can be
735/// performed; it does not actually perform the conversion. As such,
736/// it will not produce any diagnostics if no conversion is available,
737/// but will instead return an implicit conversion sequence of kind
738/// "BadConversion".
739///
740/// If @p SuppressUserConversions, then user-defined conversions are
741/// not permitted.
742/// If @p AllowExplicit, then explicit user-defined conversions are
743/// permitted.
744static ImplicitConversionSequence
745TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
746                      bool SuppressUserConversions,
747                      bool AllowExplicit,
748                      bool InOverloadResolution,
749                      bool CStyle) {
750  ImplicitConversionSequence ICS;
751  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
752                           ICS.Standard, CStyle)) {
753    ICS.setStandard();
754    return ICS;
755  }
756
757  if (!S.getLangOptions().CPlusPlus) {
758    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
759    return ICS;
760  }
761
762  // C++ [over.ics.user]p4:
763  //   A conversion of an expression of class type to the same class
764  //   type is given Exact Match rank, and a conversion of an
765  //   expression of class type to a base class of that type is
766  //   given Conversion rank, in spite of the fact that a copy/move
767  //   constructor (i.e., a user-defined conversion function) is
768  //   called for those cases.
769  QualType FromType = From->getType();
770  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
771      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
772       S.IsDerivedFrom(FromType, ToType))) {
773    ICS.setStandard();
774    ICS.Standard.setAsIdentityConversion();
775    ICS.Standard.setFromType(FromType);
776    ICS.Standard.setAllToTypes(ToType);
777
778    // We don't actually check at this point whether there is a valid
779    // copy/move constructor, since overloading just assumes that it
780    // exists. When we actually perform initialization, we'll find the
781    // appropriate constructor to copy the returned object, if needed.
782    ICS.Standard.CopyConstructor = 0;
783
784    // Determine whether this is considered a derived-to-base conversion.
785    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
786      ICS.Standard.Second = ICK_Derived_To_Base;
787
788    return ICS;
789  }
790
791  if (SuppressUserConversions) {
792    // We're not in the case above, so there is no conversion that
793    // we can perform.
794    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
795    return ICS;
796  }
797
798  // Attempt user-defined conversion.
799  OverloadCandidateSet Conversions(From->getExprLoc());
800  OverloadingResult UserDefResult
801    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
802                              AllowExplicit);
803
804  if (UserDefResult == OR_Success) {
805    ICS.setUserDefined();
806    // C++ [over.ics.user]p4:
807    //   A conversion of an expression of class type to the same class
808    //   type is given Exact Match rank, and a conversion of an
809    //   expression of class type to a base class of that type is
810    //   given Conversion rank, in spite of the fact that a copy
811    //   constructor (i.e., a user-defined conversion function) is
812    //   called for those cases.
813    if (CXXConstructorDecl *Constructor
814          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
815      QualType FromCanon
816        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
817      QualType ToCanon
818        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
819      if (Constructor->isCopyConstructor() &&
820          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
821        // Turn this into a "standard" conversion sequence, so that it
822        // gets ranked with standard conversion sequences.
823        ICS.setStandard();
824        ICS.Standard.setAsIdentityConversion();
825        ICS.Standard.setFromType(From->getType());
826        ICS.Standard.setAllToTypes(ToType);
827        ICS.Standard.CopyConstructor = Constructor;
828        if (ToCanon != FromCanon)
829          ICS.Standard.Second = ICK_Derived_To_Base;
830      }
831    }
832
833    // C++ [over.best.ics]p4:
834    //   However, when considering the argument of a user-defined
835    //   conversion function that is a candidate by 13.3.1.3 when
836    //   invoked for the copying of the temporary in the second step
837    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
838    //   13.3.1.6 in all cases, only standard conversion sequences and
839    //   ellipsis conversion sequences are allowed.
840    if (SuppressUserConversions && ICS.isUserDefined()) {
841      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
842    }
843  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
844    ICS.setAmbiguous();
845    ICS.Ambiguous.setFromType(From->getType());
846    ICS.Ambiguous.setToType(ToType);
847    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
848         Cand != Conversions.end(); ++Cand)
849      if (Cand->Viable)
850        ICS.Ambiguous.addConversion(Cand->Function);
851  } else {
852    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
853  }
854
855  return ICS;
856}
857
858bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
859                                 const InitializedEntity &Entity,
860                                 Expr *Initializer,
861                                 bool SuppressUserConversions,
862                                 bool AllowExplicitConversions,
863                                 bool InOverloadResolution,
864                                 bool CStyle) {
865  ImplicitConversionSequence ICS
866    = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
867                                   SuppressUserConversions,
868                                   AllowExplicitConversions,
869                                   InOverloadResolution,
870                                   CStyle);
871  if (ICS.isBad()) return true;
872
873  // Perform the actual conversion.
874  Sequence.AddConversionSequenceStep(ICS, Entity.getType());
875  return false;
876}
877
878/// PerformImplicitConversion - Perform an implicit conversion of the
879/// expression From to the type ToType. Returns true if there was an
880/// error, false otherwise. The expression From is replaced with the
881/// converted expression. Flavor is the kind of conversion we're
882/// performing, used in the error message. If @p AllowExplicit,
883/// explicit user-defined conversions are permitted.
884bool
885Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
886                                AssignmentAction Action, bool AllowExplicit) {
887  ImplicitConversionSequence ICS;
888  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
889}
890
891bool
892Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
893                                AssignmentAction Action, bool AllowExplicit,
894                                ImplicitConversionSequence& ICS) {
895  ICS = clang::TryImplicitConversion(*this, From, ToType,
896                                     /*SuppressUserConversions=*/false,
897                                     AllowExplicit,
898                                     /*InOverloadResolution=*/false,
899                                     /*CStyle=*/false);
900  return PerformImplicitConversion(From, ToType, ICS, Action);
901}
902
903/// \brief Determine whether the conversion from FromType to ToType is a valid
904/// conversion that strips "noreturn" off the nested function type.
905static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
906                                 QualType ToType, QualType &ResultTy) {
907  if (Context.hasSameUnqualifiedType(FromType, ToType))
908    return false;
909
910  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
911  // where F adds one of the following at most once:
912  //   - a pointer
913  //   - a member pointer
914  //   - a block pointer
915  CanQualType CanTo = Context.getCanonicalType(ToType);
916  CanQualType CanFrom = Context.getCanonicalType(FromType);
917  Type::TypeClass TyClass = CanTo->getTypeClass();
918  if (TyClass != CanFrom->getTypeClass()) return false;
919  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
920    if (TyClass == Type::Pointer) {
921      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
922      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
923    } else if (TyClass == Type::BlockPointer) {
924      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
925      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
926    } else if (TyClass == Type::MemberPointer) {
927      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
928      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
929    } else {
930      return false;
931    }
932
933    TyClass = CanTo->getTypeClass();
934    if (TyClass != CanFrom->getTypeClass()) return false;
935    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
936      return false;
937  }
938
939  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
940  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
941  if (!EInfo.getNoReturn()) return false;
942
943  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
944  assert(QualType(FromFn, 0).isCanonical());
945  if (QualType(FromFn, 0) != CanTo) return false;
946
947  ResultTy = ToType;
948  return true;
949}
950
951/// \brief Determine whether the conversion from FromType to ToType is a valid
952/// vector conversion.
953///
954/// \param ICK Will be set to the vector conversion kind, if this is a vector
955/// conversion.
956static bool IsVectorConversion(ASTContext &Context, QualType FromType,
957                               QualType ToType, ImplicitConversionKind &ICK) {
958  // We need at least one of these types to be a vector type to have a vector
959  // conversion.
960  if (!ToType->isVectorType() && !FromType->isVectorType())
961    return false;
962
963  // Identical types require no conversions.
964  if (Context.hasSameUnqualifiedType(FromType, ToType))
965    return false;
966
967  // There are no conversions between extended vector types, only identity.
968  if (ToType->isExtVectorType()) {
969    // There are no conversions between extended vector types other than the
970    // identity conversion.
971    if (FromType->isExtVectorType())
972      return false;
973
974    // Vector splat from any arithmetic type to a vector.
975    if (FromType->isArithmeticType()) {
976      ICK = ICK_Vector_Splat;
977      return true;
978    }
979  }
980
981  // We can perform the conversion between vector types in the following cases:
982  // 1)vector types are equivalent AltiVec and GCC vector types
983  // 2)lax vector conversions are permitted and the vector types are of the
984  //   same size
985  if (ToType->isVectorType() && FromType->isVectorType()) {
986    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
987        (Context.getLangOptions().LaxVectorConversions &&
988         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
989      ICK = ICK_Vector_Conversion;
990      return true;
991    }
992  }
993
994  return false;
995}
996
997/// IsStandardConversion - Determines whether there is a standard
998/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
999/// expression From to the type ToType. Standard conversion sequences
1000/// only consider non-class types; for conversions that involve class
1001/// types, use TryImplicitConversion. If a conversion exists, SCS will
1002/// contain the standard conversion sequence required to perform this
1003/// conversion and this routine will return true. Otherwise, this
1004/// routine will return false and the value of SCS is unspecified.
1005static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1006                                 bool InOverloadResolution,
1007                                 StandardConversionSequence &SCS,
1008                                 bool CStyle) {
1009  QualType FromType = From->getType();
1010
1011  // Standard conversions (C++ [conv])
1012  SCS.setAsIdentityConversion();
1013  SCS.DeprecatedStringLiteralToCharPtr = false;
1014  SCS.IncompatibleObjC = false;
1015  SCS.setFromType(FromType);
1016  SCS.CopyConstructor = 0;
1017
1018  // There are no standard conversions for class types in C++, so
1019  // abort early. When overloading in C, however, we do permit
1020  if (FromType->isRecordType() || ToType->isRecordType()) {
1021    if (S.getLangOptions().CPlusPlus)
1022      return false;
1023
1024    // When we're overloading in C, we allow, as standard conversions,
1025  }
1026
1027  // The first conversion can be an lvalue-to-rvalue conversion,
1028  // array-to-pointer conversion, or function-to-pointer conversion
1029  // (C++ 4p1).
1030
1031  if (FromType == S.Context.OverloadTy) {
1032    DeclAccessPair AccessPair;
1033    if (FunctionDecl *Fn
1034          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1035                                                 AccessPair)) {
1036      // We were able to resolve the address of the overloaded function,
1037      // so we can convert to the type of that function.
1038      FromType = Fn->getType();
1039      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1040        if (!Method->isStatic()) {
1041          const Type *ClassType
1042            = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1043          FromType = S.Context.getMemberPointerType(FromType, ClassType);
1044        }
1045      }
1046
1047      // If the "from" expression takes the address of the overloaded
1048      // function, update the type of the resulting expression accordingly.
1049      if (FromType->getAs<FunctionType>())
1050        if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
1051          if (UnOp->getOpcode() == UO_AddrOf)
1052            FromType = S.Context.getPointerType(FromType);
1053
1054      // Check that we've computed the proper type after overload resolution.
1055      assert(S.Context.hasSameType(FromType,
1056            S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1057    } else {
1058      return false;
1059    }
1060  }
1061  // Lvalue-to-rvalue conversion (C++ 4.1):
1062  //   An lvalue (3.10) of a non-function, non-array type T can be
1063  //   converted to an rvalue.
1064  bool argIsLValue = From->isLValue();
1065  if (argIsLValue &&
1066      !FromType->isFunctionType() && !FromType->isArrayType() &&
1067      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1068    SCS.First = ICK_Lvalue_To_Rvalue;
1069
1070    // If T is a non-class type, the type of the rvalue is the
1071    // cv-unqualified version of T. Otherwise, the type of the rvalue
1072    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1073    // just strip the qualifiers because they don't matter.
1074    FromType = FromType.getUnqualifiedType();
1075  } else if (FromType->isArrayType()) {
1076    // Array-to-pointer conversion (C++ 4.2)
1077    SCS.First = ICK_Array_To_Pointer;
1078
1079    // An lvalue or rvalue of type "array of N T" or "array of unknown
1080    // bound of T" can be converted to an rvalue of type "pointer to
1081    // T" (C++ 4.2p1).
1082    FromType = S.Context.getArrayDecayedType(FromType);
1083
1084    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1085      // This conversion is deprecated. (C++ D.4).
1086      SCS.DeprecatedStringLiteralToCharPtr = true;
1087
1088      // For the purpose of ranking in overload resolution
1089      // (13.3.3.1.1), this conversion is considered an
1090      // array-to-pointer conversion followed by a qualification
1091      // conversion (4.4). (C++ 4.2p2)
1092      SCS.Second = ICK_Identity;
1093      SCS.Third = ICK_Qualification;
1094      SCS.setAllToTypes(FromType);
1095      return true;
1096    }
1097  } else if (FromType->isFunctionType() && argIsLValue) {
1098    // Function-to-pointer conversion (C++ 4.3).
1099    SCS.First = ICK_Function_To_Pointer;
1100
1101    // An lvalue of function type T can be converted to an rvalue of
1102    // type "pointer to T." The result is a pointer to the
1103    // function. (C++ 4.3p1).
1104    FromType = S.Context.getPointerType(FromType);
1105  } else {
1106    // We don't require any conversions for the first step.
1107    SCS.First = ICK_Identity;
1108  }
1109  SCS.setToType(0, FromType);
1110
1111  // The second conversion can be an integral promotion, floating
1112  // point promotion, integral conversion, floating point conversion,
1113  // floating-integral conversion, pointer conversion,
1114  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1115  // For overloading in C, this can also be a "compatible-type"
1116  // conversion.
1117  bool IncompatibleObjC = false;
1118  ImplicitConversionKind SecondICK = ICK_Identity;
1119  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1120    // The unqualified versions of the types are the same: there's no
1121    // conversion to do.
1122    SCS.Second = ICK_Identity;
1123  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1124    // Integral promotion (C++ 4.5).
1125    SCS.Second = ICK_Integral_Promotion;
1126    FromType = ToType.getUnqualifiedType();
1127  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1128    // Floating point promotion (C++ 4.6).
1129    SCS.Second = ICK_Floating_Promotion;
1130    FromType = ToType.getUnqualifiedType();
1131  } else if (S.IsComplexPromotion(FromType, ToType)) {
1132    // Complex promotion (Clang extension)
1133    SCS.Second = ICK_Complex_Promotion;
1134    FromType = ToType.getUnqualifiedType();
1135  } else if (ToType->isBooleanType() &&
1136             (FromType->isArithmeticType() ||
1137              FromType->isAnyPointerType() ||
1138              FromType->isBlockPointerType() ||
1139              FromType->isMemberPointerType() ||
1140              FromType->isNullPtrType())) {
1141    // Boolean conversions (C++ 4.12).
1142    SCS.Second = ICK_Boolean_Conversion;
1143    FromType = S.Context.BoolTy;
1144  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1145             ToType->isIntegralType(S.Context)) {
1146    // Integral conversions (C++ 4.7).
1147    SCS.Second = ICK_Integral_Conversion;
1148    FromType = ToType.getUnqualifiedType();
1149  } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1150    // Complex conversions (C99 6.3.1.6)
1151    SCS.Second = ICK_Complex_Conversion;
1152    FromType = ToType.getUnqualifiedType();
1153  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1154             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1155    // Complex-real conversions (C99 6.3.1.7)
1156    SCS.Second = ICK_Complex_Real;
1157    FromType = ToType.getUnqualifiedType();
1158  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1159    // Floating point conversions (C++ 4.8).
1160    SCS.Second = ICK_Floating_Conversion;
1161    FromType = ToType.getUnqualifiedType();
1162  } else if ((FromType->isRealFloatingType() &&
1163              ToType->isIntegralType(S.Context)) ||
1164             (FromType->isIntegralOrUnscopedEnumerationType() &&
1165              ToType->isRealFloatingType())) {
1166    // Floating-integral conversions (C++ 4.9).
1167    SCS.Second = ICK_Floating_Integral;
1168    FromType = ToType.getUnqualifiedType();
1169  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1170                                   FromType, IncompatibleObjC)) {
1171    // Pointer conversions (C++ 4.10).
1172    SCS.Second = ICK_Pointer_Conversion;
1173    SCS.IncompatibleObjC = IncompatibleObjC;
1174  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1175                                         InOverloadResolution, FromType)) {
1176    // Pointer to member conversions (4.11).
1177    SCS.Second = ICK_Pointer_Member;
1178  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1179    SCS.Second = SecondICK;
1180    FromType = ToType.getUnqualifiedType();
1181  } else if (!S.getLangOptions().CPlusPlus &&
1182             S.Context.typesAreCompatible(ToType, FromType)) {
1183    // Compatible conversions (Clang extension for C function overloading)
1184    SCS.Second = ICK_Compatible_Conversion;
1185    FromType = ToType.getUnqualifiedType();
1186  } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
1187    // Treat a conversion that strips "noreturn" as an identity conversion.
1188    SCS.Second = ICK_NoReturn_Adjustment;
1189  } else {
1190    // No second conversion required.
1191    SCS.Second = ICK_Identity;
1192  }
1193  SCS.setToType(1, FromType);
1194
1195  QualType CanonFrom;
1196  QualType CanonTo;
1197  // The third conversion can be a qualification conversion (C++ 4p1).
1198  if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
1199    SCS.Third = ICK_Qualification;
1200    FromType = ToType;
1201    CanonFrom = S.Context.getCanonicalType(FromType);
1202    CanonTo = S.Context.getCanonicalType(ToType);
1203  } else {
1204    // No conversion required
1205    SCS.Third = ICK_Identity;
1206
1207    // C++ [over.best.ics]p6:
1208    //   [...] Any difference in top-level cv-qualification is
1209    //   subsumed by the initialization itself and does not constitute
1210    //   a conversion. [...]
1211    CanonFrom = S.Context.getCanonicalType(FromType);
1212    CanonTo = S.Context.getCanonicalType(ToType);
1213    if (CanonFrom.getLocalUnqualifiedType()
1214                                       == CanonTo.getLocalUnqualifiedType() &&
1215        (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1216         || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
1217      FromType = ToType;
1218      CanonFrom = CanonTo;
1219    }
1220  }
1221  SCS.setToType(2, FromType);
1222
1223  // If we have not converted the argument type to the parameter type,
1224  // this is a bad conversion sequence.
1225  if (CanonFrom != CanonTo)
1226    return false;
1227
1228  return true;
1229}
1230
1231/// IsIntegralPromotion - Determines whether the conversion from the
1232/// expression From (whose potentially-adjusted type is FromType) to
1233/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1234/// sets PromotedType to the promoted type.
1235bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1236  const BuiltinType *To = ToType->getAs<BuiltinType>();
1237  // All integers are built-in.
1238  if (!To) {
1239    return false;
1240  }
1241
1242  // An rvalue of type char, signed char, unsigned char, short int, or
1243  // unsigned short int can be converted to an rvalue of type int if
1244  // int can represent all the values of the source type; otherwise,
1245  // the source rvalue can be converted to an rvalue of type unsigned
1246  // int (C++ 4.5p1).
1247  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1248      !FromType->isEnumeralType()) {
1249    if (// We can promote any signed, promotable integer type to an int
1250        (FromType->isSignedIntegerType() ||
1251         // We can promote any unsigned integer type whose size is
1252         // less than int to an int.
1253         (!FromType->isSignedIntegerType() &&
1254          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1255      return To->getKind() == BuiltinType::Int;
1256    }
1257
1258    return To->getKind() == BuiltinType::UInt;
1259  }
1260
1261  // C++0x [conv.prom]p3:
1262  //   A prvalue of an unscoped enumeration type whose underlying type is not
1263  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1264  //   following types that can represent all the values of the enumeration
1265  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1266  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1267  //   long long int. If none of the types in that list can represent all the
1268  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1269  //   type can be converted to an rvalue a prvalue of the extended integer type
1270  //   with lowest integer conversion rank (4.13) greater than the rank of long
1271  //   long in which all the values of the enumeration can be represented. If
1272  //   there are two such extended types, the signed one is chosen.
1273  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1274    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1275    // provided for a scoped enumeration.
1276    if (FromEnumType->getDecl()->isScoped())
1277      return false;
1278
1279    // We have already pre-calculated the promotion type, so this is trivial.
1280    if (ToType->isIntegerType() &&
1281        !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
1282      return Context.hasSameUnqualifiedType(ToType,
1283                                FromEnumType->getDecl()->getPromotionType());
1284  }
1285
1286  // C++0x [conv.prom]p2:
1287  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1288  //   to an rvalue a prvalue of the first of the following types that can
1289  //   represent all the values of its underlying type: int, unsigned int,
1290  //   long int, unsigned long int, long long int, or unsigned long long int.
1291  //   If none of the types in that list can represent all the values of its
1292  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1293  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1294  //   type.
1295  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1296      ToType->isIntegerType()) {
1297    // Determine whether the type we're converting from is signed or
1298    // unsigned.
1299    bool FromIsSigned;
1300    uint64_t FromSize = Context.getTypeSize(FromType);
1301
1302    // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1303    FromIsSigned = true;
1304
1305    // The types we'll try to promote to, in the appropriate
1306    // order. Try each of these types.
1307    QualType PromoteTypes[6] = {
1308      Context.IntTy, Context.UnsignedIntTy,
1309      Context.LongTy, Context.UnsignedLongTy ,
1310      Context.LongLongTy, Context.UnsignedLongLongTy
1311    };
1312    for (int Idx = 0; Idx < 6; ++Idx) {
1313      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1314      if (FromSize < ToSize ||
1315          (FromSize == ToSize &&
1316           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1317        // We found the type that we can promote to. If this is the
1318        // type we wanted, we have a promotion. Otherwise, no
1319        // promotion.
1320        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1321      }
1322    }
1323  }
1324
1325  // An rvalue for an integral bit-field (9.6) can be converted to an
1326  // rvalue of type int if int can represent all the values of the
1327  // bit-field; otherwise, it can be converted to unsigned int if
1328  // unsigned int can represent all the values of the bit-field. If
1329  // the bit-field is larger yet, no integral promotion applies to
1330  // it. If the bit-field has an enumerated type, it is treated as any
1331  // other value of that type for promotion purposes (C++ 4.5p3).
1332  // FIXME: We should delay checking of bit-fields until we actually perform the
1333  // conversion.
1334  using llvm::APSInt;
1335  if (From)
1336    if (FieldDecl *MemberDecl = From->getBitField()) {
1337      APSInt BitWidth;
1338      if (FromType->isIntegralType(Context) &&
1339          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1340        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1341        ToSize = Context.getTypeSize(ToType);
1342
1343        // Are we promoting to an int from a bitfield that fits in an int?
1344        if (BitWidth < ToSize ||
1345            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1346          return To->getKind() == BuiltinType::Int;
1347        }
1348
1349        // Are we promoting to an unsigned int from an unsigned bitfield
1350        // that fits into an unsigned int?
1351        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1352          return To->getKind() == BuiltinType::UInt;
1353        }
1354
1355        return false;
1356      }
1357    }
1358
1359  // An rvalue of type bool can be converted to an rvalue of type int,
1360  // with false becoming zero and true becoming one (C++ 4.5p4).
1361  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1362    return true;
1363  }
1364
1365  return false;
1366}
1367
1368/// IsFloatingPointPromotion - Determines whether the conversion from
1369/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1370/// returns true and sets PromotedType to the promoted type.
1371bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1372  /// An rvalue of type float can be converted to an rvalue of type
1373  /// double. (C++ 4.6p1).
1374  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1375    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1376      if (FromBuiltin->getKind() == BuiltinType::Float &&
1377          ToBuiltin->getKind() == BuiltinType::Double)
1378        return true;
1379
1380      // C99 6.3.1.5p1:
1381      //   When a float is promoted to double or long double, or a
1382      //   double is promoted to long double [...].
1383      if (!getLangOptions().CPlusPlus &&
1384          (FromBuiltin->getKind() == BuiltinType::Float ||
1385           FromBuiltin->getKind() == BuiltinType::Double) &&
1386          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1387        return true;
1388    }
1389
1390  return false;
1391}
1392
1393/// \brief Determine if a conversion is a complex promotion.
1394///
1395/// A complex promotion is defined as a complex -> complex conversion
1396/// where the conversion between the underlying real types is a
1397/// floating-point or integral promotion.
1398bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1399  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1400  if (!FromComplex)
1401    return false;
1402
1403  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1404  if (!ToComplex)
1405    return false;
1406
1407  return IsFloatingPointPromotion(FromComplex->getElementType(),
1408                                  ToComplex->getElementType()) ||
1409    IsIntegralPromotion(0, FromComplex->getElementType(),
1410                        ToComplex->getElementType());
1411}
1412
1413/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1414/// the pointer type FromPtr to a pointer to type ToPointee, with the
1415/// same type qualifiers as FromPtr has on its pointee type. ToType,
1416/// if non-empty, will be a pointer to ToType that may or may not have
1417/// the right set of qualifiers on its pointee.
1418static QualType
1419BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1420                                   QualType ToPointee, QualType ToType,
1421                                   ASTContext &Context) {
1422  assert((FromPtr->getTypeClass() == Type::Pointer ||
1423          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1424         "Invalid similarly-qualified pointer type");
1425
1426  /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1427  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1428    return ToType.getUnqualifiedType();
1429
1430  QualType CanonFromPointee
1431    = Context.getCanonicalType(FromPtr->getPointeeType());
1432  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1433  Qualifiers Quals = CanonFromPointee.getQualifiers();
1434
1435  // Exact qualifier match -> return the pointer type we're converting to.
1436  if (CanonToPointee.getLocalQualifiers() == Quals) {
1437    // ToType is exactly what we need. Return it.
1438    if (!ToType.isNull())
1439      return ToType.getUnqualifiedType();
1440
1441    // Build a pointer to ToPointee. It has the right qualifiers
1442    // already.
1443    if (isa<ObjCObjectPointerType>(ToType))
1444      return Context.getObjCObjectPointerType(ToPointee);
1445    return Context.getPointerType(ToPointee);
1446  }
1447
1448  // Just build a canonical type that has the right qualifiers.
1449  QualType QualifiedCanonToPointee
1450    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1451
1452  if (isa<ObjCObjectPointerType>(ToType))
1453    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1454  return Context.getPointerType(QualifiedCanonToPointee);
1455}
1456
1457static bool isNullPointerConstantForConversion(Expr *Expr,
1458                                               bool InOverloadResolution,
1459                                               ASTContext &Context) {
1460  // Handle value-dependent integral null pointer constants correctly.
1461  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1462  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1463      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1464    return !InOverloadResolution;
1465
1466  return Expr->isNullPointerConstant(Context,
1467                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1468                                        : Expr::NPC_ValueDependentIsNull);
1469}
1470
1471/// IsPointerConversion - Determines whether the conversion of the
1472/// expression From, which has the (possibly adjusted) type FromType,
1473/// can be converted to the type ToType via a pointer conversion (C++
1474/// 4.10). If so, returns true and places the converted type (that
1475/// might differ from ToType in its cv-qualifiers at some level) into
1476/// ConvertedType.
1477///
1478/// This routine also supports conversions to and from block pointers
1479/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1480/// pointers to interfaces. FIXME: Once we've determined the
1481/// appropriate overloading rules for Objective-C, we may want to
1482/// split the Objective-C checks into a different routine; however,
1483/// GCC seems to consider all of these conversions to be pointer
1484/// conversions, so for now they live here. IncompatibleObjC will be
1485/// set if the conversion is an allowed Objective-C conversion that
1486/// should result in a warning.
1487bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1488                               bool InOverloadResolution,
1489                               QualType& ConvertedType,
1490                               bool &IncompatibleObjC) {
1491  IncompatibleObjC = false;
1492  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1493                              IncompatibleObjC))
1494    return true;
1495
1496  // Conversion from a null pointer constant to any Objective-C pointer type.
1497  if (ToType->isObjCObjectPointerType() &&
1498      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1499    ConvertedType = ToType;
1500    return true;
1501  }
1502
1503  // Blocks: Block pointers can be converted to void*.
1504  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1505      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1506    ConvertedType = ToType;
1507    return true;
1508  }
1509  // Blocks: A null pointer constant can be converted to a block
1510  // pointer type.
1511  if (ToType->isBlockPointerType() &&
1512      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1513    ConvertedType = ToType;
1514    return true;
1515  }
1516
1517  // If the left-hand-side is nullptr_t, the right side can be a null
1518  // pointer constant.
1519  if (ToType->isNullPtrType() &&
1520      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1521    ConvertedType = ToType;
1522    return true;
1523  }
1524
1525  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1526  if (!ToTypePtr)
1527    return false;
1528
1529  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1530  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1531    ConvertedType = ToType;
1532    return true;
1533  }
1534
1535  // Beyond this point, both types need to be pointers
1536  // , including objective-c pointers.
1537  QualType ToPointeeType = ToTypePtr->getPointeeType();
1538  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1539    ConvertedType = BuildSimilarlyQualifiedPointerType(
1540                                      FromType->getAs<ObjCObjectPointerType>(),
1541                                                       ToPointeeType,
1542                                                       ToType, Context);
1543    return true;
1544  }
1545  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1546  if (!FromTypePtr)
1547    return false;
1548
1549  QualType FromPointeeType = FromTypePtr->getPointeeType();
1550
1551  // If the unqualified pointee types are the same, this can't be a
1552  // pointer conversion, so don't do all of the work below.
1553  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1554    return false;
1555
1556  // An rvalue of type "pointer to cv T," where T is an object type,
1557  // can be converted to an rvalue of type "pointer to cv void" (C++
1558  // 4.10p2).
1559  if (FromPointeeType->isIncompleteOrObjectType() &&
1560      ToPointeeType->isVoidType()) {
1561    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1562                                                       ToPointeeType,
1563                                                       ToType, Context);
1564    return true;
1565  }
1566
1567  // When we're overloading in C, we allow a special kind of pointer
1568  // conversion for compatible-but-not-identical pointee types.
1569  if (!getLangOptions().CPlusPlus &&
1570      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1571    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1572                                                       ToPointeeType,
1573                                                       ToType, Context);
1574    return true;
1575  }
1576
1577  // C++ [conv.ptr]p3:
1578  //
1579  //   An rvalue of type "pointer to cv D," where D is a class type,
1580  //   can be converted to an rvalue of type "pointer to cv B," where
1581  //   B is a base class (clause 10) of D. If B is an inaccessible
1582  //   (clause 11) or ambiguous (10.2) base class of D, a program that
1583  //   necessitates this conversion is ill-formed. The result of the
1584  //   conversion is a pointer to the base class sub-object of the
1585  //   derived class object. The null pointer value is converted to
1586  //   the null pointer value of the destination type.
1587  //
1588  // Note that we do not check for ambiguity or inaccessibility
1589  // here. That is handled by CheckPointerConversion.
1590  if (getLangOptions().CPlusPlus &&
1591      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1592      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
1593      !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1594      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1595    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1596                                                       ToPointeeType,
1597                                                       ToType, Context);
1598    return true;
1599  }
1600
1601  return false;
1602}
1603
1604/// isObjCPointerConversion - Determines whether this is an
1605/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1606/// with the same arguments and return values.
1607bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1608                                   QualType& ConvertedType,
1609                                   bool &IncompatibleObjC) {
1610  if (!getLangOptions().ObjC1)
1611    return false;
1612
1613  // First, we handle all conversions on ObjC object pointer types.
1614  const ObjCObjectPointerType* ToObjCPtr =
1615    ToType->getAs<ObjCObjectPointerType>();
1616  const ObjCObjectPointerType *FromObjCPtr =
1617    FromType->getAs<ObjCObjectPointerType>();
1618
1619  if (ToObjCPtr && FromObjCPtr) {
1620    // If the pointee types are the same (ignoring qualifications),
1621    // then this is not a pointer conversion.
1622    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1623                                       FromObjCPtr->getPointeeType()))
1624      return false;
1625
1626    // Objective C++: We're able to convert between "id" or "Class" and a
1627    // pointer to any interface (in both directions).
1628    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1629      ConvertedType = ToType;
1630      return true;
1631    }
1632    // Conversions with Objective-C's id<...>.
1633    if ((FromObjCPtr->isObjCQualifiedIdType() ||
1634         ToObjCPtr->isObjCQualifiedIdType()) &&
1635        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1636                                                  /*compare=*/false)) {
1637      ConvertedType = ToType;
1638      return true;
1639    }
1640    // Objective C++: We're able to convert from a pointer to an
1641    // interface to a pointer to a different interface.
1642    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1643      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1644      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1645      if (getLangOptions().CPlusPlus && LHS && RHS &&
1646          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1647                                                FromObjCPtr->getPointeeType()))
1648        return false;
1649      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1650                                                   ToObjCPtr->getPointeeType(),
1651                                                         ToType, Context);
1652      return true;
1653    }
1654
1655    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1656      // Okay: this is some kind of implicit downcast of Objective-C
1657      // interfaces, which is permitted. However, we're going to
1658      // complain about it.
1659      IncompatibleObjC = true;
1660      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1661                                                   ToObjCPtr->getPointeeType(),
1662                                                         ToType, Context);
1663      return true;
1664    }
1665  }
1666  // Beyond this point, both types need to be C pointers or block pointers.
1667  QualType ToPointeeType;
1668  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1669    ToPointeeType = ToCPtr->getPointeeType();
1670  else if (const BlockPointerType *ToBlockPtr =
1671            ToType->getAs<BlockPointerType>()) {
1672    // Objective C++: We're able to convert from a pointer to any object
1673    // to a block pointer type.
1674    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1675      ConvertedType = ToType;
1676      return true;
1677    }
1678    ToPointeeType = ToBlockPtr->getPointeeType();
1679  }
1680  else if (FromType->getAs<BlockPointerType>() &&
1681           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1682    // Objective C++: We're able to convert from a block pointer type to a
1683    // pointer to any object.
1684    ConvertedType = ToType;
1685    return true;
1686  }
1687  else
1688    return false;
1689
1690  QualType FromPointeeType;
1691  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1692    FromPointeeType = FromCPtr->getPointeeType();
1693  else if (const BlockPointerType *FromBlockPtr =
1694           FromType->getAs<BlockPointerType>())
1695    FromPointeeType = FromBlockPtr->getPointeeType();
1696  else
1697    return false;
1698
1699  // If we have pointers to pointers, recursively check whether this
1700  // is an Objective-C conversion.
1701  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1702      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1703                              IncompatibleObjC)) {
1704    // We always complain about this conversion.
1705    IncompatibleObjC = true;
1706    ConvertedType = Context.getPointerType(ConvertedType);
1707    return true;
1708  }
1709  // Allow conversion of pointee being objective-c pointer to another one;
1710  // as in I* to id.
1711  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1712      ToPointeeType->getAs<ObjCObjectPointerType>() &&
1713      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1714                              IncompatibleObjC)) {
1715    ConvertedType = Context.getPointerType(ConvertedType);
1716    return true;
1717  }
1718
1719  // If we have pointers to functions or blocks, check whether the only
1720  // differences in the argument and result types are in Objective-C
1721  // pointer conversions. If so, we permit the conversion (but
1722  // complain about it).
1723  const FunctionProtoType *FromFunctionType
1724    = FromPointeeType->getAs<FunctionProtoType>();
1725  const FunctionProtoType *ToFunctionType
1726    = ToPointeeType->getAs<FunctionProtoType>();
1727  if (FromFunctionType && ToFunctionType) {
1728    // If the function types are exactly the same, this isn't an
1729    // Objective-C pointer conversion.
1730    if (Context.getCanonicalType(FromPointeeType)
1731          == Context.getCanonicalType(ToPointeeType))
1732      return false;
1733
1734    // Perform the quick checks that will tell us whether these
1735    // function types are obviously different.
1736    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1737        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1738        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1739      return false;
1740
1741    bool HasObjCConversion = false;
1742    if (Context.getCanonicalType(FromFunctionType->getResultType())
1743          == Context.getCanonicalType(ToFunctionType->getResultType())) {
1744      // Okay, the types match exactly. Nothing to do.
1745    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1746                                       ToFunctionType->getResultType(),
1747                                       ConvertedType, IncompatibleObjC)) {
1748      // Okay, we have an Objective-C pointer conversion.
1749      HasObjCConversion = true;
1750    } else {
1751      // Function types are too different. Abort.
1752      return false;
1753    }
1754
1755    // Check argument types.
1756    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1757         ArgIdx != NumArgs; ++ArgIdx) {
1758      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1759      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1760      if (Context.getCanonicalType(FromArgType)
1761            == Context.getCanonicalType(ToArgType)) {
1762        // Okay, the types match exactly. Nothing to do.
1763      } else if (isObjCPointerConversion(FromArgType, ToArgType,
1764                                         ConvertedType, IncompatibleObjC)) {
1765        // Okay, we have an Objective-C pointer conversion.
1766        HasObjCConversion = true;
1767      } else {
1768        // Argument types are too different. Abort.
1769        return false;
1770      }
1771    }
1772
1773    if (HasObjCConversion) {
1774      // We had an Objective-C conversion. Allow this pointer
1775      // conversion, but complain about it.
1776      ConvertedType = ToType;
1777      IncompatibleObjC = true;
1778      return true;
1779    }
1780  }
1781
1782  return false;
1783}
1784
1785/// FunctionArgTypesAreEqual - This routine checks two function proto types
1786/// for equlity of their argument types. Caller has already checked that
1787/// they have same number of arguments. This routine assumes that Objective-C
1788/// pointer types which only differ in their protocol qualifiers are equal.
1789bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1790                                    const FunctionProtoType *NewType) {
1791  if (!getLangOptions().ObjC1)
1792    return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1793                      NewType->arg_type_begin());
1794
1795  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1796       N = NewType->arg_type_begin(),
1797       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1798    QualType ToType = (*O);
1799    QualType FromType = (*N);
1800    if (ToType != FromType) {
1801      if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1802        if (const PointerType *PTFr = FromType->getAs<PointerType>())
1803          if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1804               PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1805              (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1806               PTFr->getPointeeType()->isObjCQualifiedClassType()))
1807            continue;
1808      }
1809      else if (const ObjCObjectPointerType *PTTo =
1810                 ToType->getAs<ObjCObjectPointerType>()) {
1811        if (const ObjCObjectPointerType *PTFr =
1812              FromType->getAs<ObjCObjectPointerType>())
1813          if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1814            continue;
1815      }
1816      return false;
1817    }
1818  }
1819  return true;
1820}
1821
1822/// CheckPointerConversion - Check the pointer conversion from the
1823/// expression From to the type ToType. This routine checks for
1824/// ambiguous or inaccessible derived-to-base pointer
1825/// conversions for which IsPointerConversion has already returned
1826/// true. It returns true and produces a diagnostic if there was an
1827/// error, or returns false otherwise.
1828bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1829                                  CastKind &Kind,
1830                                  CXXCastPath& BasePath,
1831                                  bool IgnoreBaseAccess) {
1832  QualType FromType = From->getType();
1833  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
1834
1835  Kind = CK_BitCast;
1836
1837  if (CXXBoolLiteralExpr* LitBool
1838                          = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1839    if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
1840      Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1841        << ToType;
1842
1843  if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1844    if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
1845      QualType FromPointeeType = FromPtrType->getPointeeType(),
1846               ToPointeeType   = ToPtrType->getPointeeType();
1847
1848      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1849          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
1850        // We must have a derived-to-base conversion. Check an
1851        // ambiguous or inaccessible conversion.
1852        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1853                                         From->getExprLoc(),
1854                                         From->getSourceRange(), &BasePath,
1855                                         IgnoreBaseAccess))
1856          return true;
1857
1858        // The conversion was successful.
1859        Kind = CK_DerivedToBase;
1860      }
1861    }
1862  if (const ObjCObjectPointerType *FromPtrType =
1863        FromType->getAs<ObjCObjectPointerType>()) {
1864    if (const ObjCObjectPointerType *ToPtrType =
1865          ToType->getAs<ObjCObjectPointerType>()) {
1866      // Objective-C++ conversions are always okay.
1867      // FIXME: We should have a different class of conversions for the
1868      // Objective-C++ implicit conversions.
1869      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
1870        return false;
1871    }
1872  }
1873
1874  // We shouldn't fall into this case unless it's valid for other
1875  // reasons.
1876  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1877    Kind = CK_NullToPointer;
1878
1879  return false;
1880}
1881
1882/// IsMemberPointerConversion - Determines whether the conversion of the
1883/// expression From, which has the (possibly adjusted) type FromType, can be
1884/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1885/// If so, returns true and places the converted type (that might differ from
1886/// ToType in its cv-qualifiers at some level) into ConvertedType.
1887bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1888                                     QualType ToType,
1889                                     bool InOverloadResolution,
1890                                     QualType &ConvertedType) {
1891  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
1892  if (!ToTypePtr)
1893    return false;
1894
1895  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1896  if (From->isNullPointerConstant(Context,
1897                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1898                                        : Expr::NPC_ValueDependentIsNull)) {
1899    ConvertedType = ToType;
1900    return true;
1901  }
1902
1903  // Otherwise, both types have to be member pointers.
1904  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
1905  if (!FromTypePtr)
1906    return false;
1907
1908  // A pointer to member of B can be converted to a pointer to member of D,
1909  // where D is derived from B (C++ 4.11p2).
1910  QualType FromClass(FromTypePtr->getClass(), 0);
1911  QualType ToClass(ToTypePtr->getClass(), 0);
1912
1913  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
1914      !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
1915      IsDerivedFrom(ToClass, FromClass)) {
1916    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1917                                                 ToClass.getTypePtr());
1918    return true;
1919  }
1920
1921  return false;
1922}
1923
1924/// CheckMemberPointerConversion - Check the member pointer conversion from the
1925/// expression From to the type ToType. This routine checks for ambiguous or
1926/// virtual or inaccessible base-to-derived member pointer conversions
1927/// for which IsMemberPointerConversion has already returned true. It returns
1928/// true and produces a diagnostic if there was an error, or returns false
1929/// otherwise.
1930bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1931                                        CastKind &Kind,
1932                                        CXXCastPath &BasePath,
1933                                        bool IgnoreBaseAccess) {
1934  QualType FromType = From->getType();
1935  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
1936  if (!FromPtrType) {
1937    // This must be a null pointer to member pointer conversion
1938    assert(From->isNullPointerConstant(Context,
1939                                       Expr::NPC_ValueDependentIsNull) &&
1940           "Expr must be null pointer constant!");
1941    Kind = CK_NullToMemberPointer;
1942    return false;
1943  }
1944
1945  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
1946  assert(ToPtrType && "No member pointer cast has a target type "
1947                      "that is not a member pointer.");
1948
1949  QualType FromClass = QualType(FromPtrType->getClass(), 0);
1950  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
1951
1952  // FIXME: What about dependent types?
1953  assert(FromClass->isRecordType() && "Pointer into non-class.");
1954  assert(ToClass->isRecordType() && "Pointer into non-class.");
1955
1956  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1957                     /*DetectVirtual=*/true);
1958  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1959  assert(DerivationOkay &&
1960         "Should not have been called if derivation isn't OK.");
1961  (void)DerivationOkay;
1962
1963  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1964                                  getUnqualifiedType())) {
1965    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1966    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1967      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1968    return true;
1969  }
1970
1971  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1972    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1973      << FromClass << ToClass << QualType(VBase, 0)
1974      << From->getSourceRange();
1975    return true;
1976  }
1977
1978  if (!IgnoreBaseAccess)
1979    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1980                         Paths.front(),
1981                         diag::err_downcast_from_inaccessible_base);
1982
1983  // Must be a base to derived member conversion.
1984  BuildBasePathArray(Paths, BasePath);
1985  Kind = CK_BaseToDerivedMemberPointer;
1986  return false;
1987}
1988
1989/// IsQualificationConversion - Determines whether the conversion from
1990/// an rvalue of type FromType to ToType is a qualification conversion
1991/// (C++ 4.4).
1992bool
1993Sema::IsQualificationConversion(QualType FromType, QualType ToType,
1994                                bool CStyle) {
1995  FromType = Context.getCanonicalType(FromType);
1996  ToType = Context.getCanonicalType(ToType);
1997
1998  // If FromType and ToType are the same type, this is not a
1999  // qualification conversion.
2000  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2001    return false;
2002
2003  // (C++ 4.4p4):
2004  //   A conversion can add cv-qualifiers at levels other than the first
2005  //   in multi-level pointers, subject to the following rules: [...]
2006  bool PreviousToQualsIncludeConst = true;
2007  bool UnwrappedAnyPointer = false;
2008  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2009    // Within each iteration of the loop, we check the qualifiers to
2010    // determine if this still looks like a qualification
2011    // conversion. Then, if all is well, we unwrap one more level of
2012    // pointers or pointers-to-members and do it all again
2013    // until there are no more pointers or pointers-to-members left to
2014    // unwrap.
2015    UnwrappedAnyPointer = true;
2016
2017    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2018    //      2,j, and similarly for volatile.
2019    if (!CStyle && !ToType.isAtLeastAsQualifiedAs(FromType))
2020      return false;
2021
2022    //   -- if the cv 1,j and cv 2,j are different, then const is in
2023    //      every cv for 0 < k < j.
2024    if (!CStyle && FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
2025        && !PreviousToQualsIncludeConst)
2026      return false;
2027
2028    // Keep track of whether all prior cv-qualifiers in the "to" type
2029    // include const.
2030    PreviousToQualsIncludeConst
2031      = PreviousToQualsIncludeConst && ToType.isConstQualified();
2032  }
2033
2034  // We are left with FromType and ToType being the pointee types
2035  // after unwrapping the original FromType and ToType the same number
2036  // of types. If we unwrapped any pointers, and if FromType and
2037  // ToType have the same unqualified type (since we checked
2038  // qualifiers above), then this is a qualification conversion.
2039  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2040}
2041
2042/// Determines whether there is a user-defined conversion sequence
2043/// (C++ [over.ics.user]) that converts expression From to the type
2044/// ToType. If such a conversion exists, User will contain the
2045/// user-defined conversion sequence that performs such a conversion
2046/// and this routine will return true. Otherwise, this routine returns
2047/// false and User is unspecified.
2048///
2049/// \param AllowExplicit  true if the conversion should consider C++0x
2050/// "explicit" conversion functions as well as non-explicit conversion
2051/// functions (C++0x [class.conv.fct]p2).
2052static OverloadingResult
2053IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2054                        UserDefinedConversionSequence& User,
2055                        OverloadCandidateSet& CandidateSet,
2056                        bool AllowExplicit) {
2057  // Whether we will only visit constructors.
2058  bool ConstructorsOnly = false;
2059
2060  // If the type we are conversion to is a class type, enumerate its
2061  // constructors.
2062  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2063    // C++ [over.match.ctor]p1:
2064    //   When objects of class type are direct-initialized (8.5), or
2065    //   copy-initialized from an expression of the same or a
2066    //   derived class type (8.5), overload resolution selects the
2067    //   constructor. [...] For copy-initialization, the candidate
2068    //   functions are all the converting constructors (12.3.1) of
2069    //   that class. The argument list is the expression-list within
2070    //   the parentheses of the initializer.
2071    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2072        (From->getType()->getAs<RecordType>() &&
2073         S.IsDerivedFrom(From->getType(), ToType)))
2074      ConstructorsOnly = true;
2075
2076    if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
2077      // We're not going to find any constructors.
2078    } else if (CXXRecordDecl *ToRecordDecl
2079                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
2080      DeclContext::lookup_iterator Con, ConEnd;
2081      for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
2082           Con != ConEnd; ++Con) {
2083        NamedDecl *D = *Con;
2084        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2085
2086        // Find the constructor (which may be a template).
2087        CXXConstructorDecl *Constructor = 0;
2088        FunctionTemplateDecl *ConstructorTmpl
2089          = dyn_cast<FunctionTemplateDecl>(D);
2090        if (ConstructorTmpl)
2091          Constructor
2092            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2093        else
2094          Constructor = cast<CXXConstructorDecl>(D);
2095
2096        if (!Constructor->isInvalidDecl() &&
2097            Constructor->isConvertingConstructor(AllowExplicit)) {
2098          if (ConstructorTmpl)
2099            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2100                                           /*ExplicitArgs*/ 0,
2101                                           &From, 1, CandidateSet,
2102                                           /*SuppressUserConversions=*/
2103                                             !ConstructorsOnly);
2104          else
2105            // Allow one user-defined conversion when user specifies a
2106            // From->ToType conversion via an static cast (c-style, etc).
2107            S.AddOverloadCandidate(Constructor, FoundDecl,
2108                                   &From, 1, CandidateSet,
2109                                   /*SuppressUserConversions=*/
2110                                     !ConstructorsOnly);
2111        }
2112      }
2113    }
2114  }
2115
2116  // Enumerate conversion functions, if we're allowed to.
2117  if (ConstructorsOnly) {
2118  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2119                                   S.PDiag(0) << From->getSourceRange())) {
2120    // No conversion functions from incomplete types.
2121  } else if (const RecordType *FromRecordType
2122                                   = From->getType()->getAs<RecordType>()) {
2123    if (CXXRecordDecl *FromRecordDecl
2124         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2125      // Add all of the conversion functions as candidates.
2126      const UnresolvedSetImpl *Conversions
2127        = FromRecordDecl->getVisibleConversionFunctions();
2128      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2129             E = Conversions->end(); I != E; ++I) {
2130        DeclAccessPair FoundDecl = I.getPair();
2131        NamedDecl *D = FoundDecl.getDecl();
2132        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2133        if (isa<UsingShadowDecl>(D))
2134          D = cast<UsingShadowDecl>(D)->getTargetDecl();
2135
2136        CXXConversionDecl *Conv;
2137        FunctionTemplateDecl *ConvTemplate;
2138        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2139          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2140        else
2141          Conv = cast<CXXConversionDecl>(D);
2142
2143        if (AllowExplicit || !Conv->isExplicit()) {
2144          if (ConvTemplate)
2145            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2146                                             ActingContext, From, ToType,
2147                                             CandidateSet);
2148          else
2149            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2150                                     From, ToType, CandidateSet);
2151        }
2152      }
2153    }
2154  }
2155
2156  OverloadCandidateSet::iterator Best;
2157  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2158  case OR_Success:
2159    // Record the standard conversion we used and the conversion function.
2160    if (CXXConstructorDecl *Constructor
2161          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2162      // C++ [over.ics.user]p1:
2163      //   If the user-defined conversion is specified by a
2164      //   constructor (12.3.1), the initial standard conversion
2165      //   sequence converts the source type to the type required by
2166      //   the argument of the constructor.
2167      //
2168      QualType ThisType = Constructor->getThisType(S.Context);
2169      if (Best->Conversions[0].isEllipsis())
2170        User.EllipsisConversion = true;
2171      else {
2172        User.Before = Best->Conversions[0].Standard;
2173        User.EllipsisConversion = false;
2174      }
2175      User.ConversionFunction = Constructor;
2176      User.FoundConversionFunction = Best->FoundDecl.getDecl();
2177      User.After.setAsIdentityConversion();
2178      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2179      User.After.setAllToTypes(ToType);
2180      return OR_Success;
2181    } else if (CXXConversionDecl *Conversion
2182                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2183      // C++ [over.ics.user]p1:
2184      //
2185      //   [...] If the user-defined conversion is specified by a
2186      //   conversion function (12.3.2), the initial standard
2187      //   conversion sequence converts the source type to the
2188      //   implicit object parameter of the conversion function.
2189      User.Before = Best->Conversions[0].Standard;
2190      User.ConversionFunction = Conversion;
2191      User.FoundConversionFunction = Best->FoundDecl.getDecl();
2192      User.EllipsisConversion = false;
2193
2194      // C++ [over.ics.user]p2:
2195      //   The second standard conversion sequence converts the
2196      //   result of the user-defined conversion to the target type
2197      //   for the sequence. Since an implicit conversion sequence
2198      //   is an initialization, the special rules for
2199      //   initialization by user-defined conversion apply when
2200      //   selecting the best user-defined conversion for a
2201      //   user-defined conversion sequence (see 13.3.3 and
2202      //   13.3.3.1).
2203      User.After = Best->FinalConversion;
2204      return OR_Success;
2205    } else {
2206      llvm_unreachable("Not a constructor or conversion function?");
2207      return OR_No_Viable_Function;
2208    }
2209
2210  case OR_No_Viable_Function:
2211    return OR_No_Viable_Function;
2212  case OR_Deleted:
2213    // No conversion here! We're done.
2214    return OR_Deleted;
2215
2216  case OR_Ambiguous:
2217    return OR_Ambiguous;
2218  }
2219
2220  return OR_No_Viable_Function;
2221}
2222
2223bool
2224Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
2225  ImplicitConversionSequence ICS;
2226  OverloadCandidateSet CandidateSet(From->getExprLoc());
2227  OverloadingResult OvResult =
2228    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
2229                            CandidateSet, false);
2230  if (OvResult == OR_Ambiguous)
2231    Diag(From->getSourceRange().getBegin(),
2232         diag::err_typecheck_ambiguous_condition)
2233          << From->getType() << ToType << From->getSourceRange();
2234  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2235    Diag(From->getSourceRange().getBegin(),
2236         diag::err_typecheck_nonviable_condition)
2237    << From->getType() << ToType << From->getSourceRange();
2238  else
2239    return false;
2240  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
2241  return true;
2242}
2243
2244/// CompareImplicitConversionSequences - Compare two implicit
2245/// conversion sequences to determine whether one is better than the
2246/// other or if they are indistinguishable (C++ 13.3.3.2).
2247static ImplicitConversionSequence::CompareKind
2248CompareImplicitConversionSequences(Sema &S,
2249                                   const ImplicitConversionSequence& ICS1,
2250                                   const ImplicitConversionSequence& ICS2)
2251{
2252  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2253  // conversion sequences (as defined in 13.3.3.1)
2254  //   -- a standard conversion sequence (13.3.3.1.1) is a better
2255  //      conversion sequence than a user-defined conversion sequence or
2256  //      an ellipsis conversion sequence, and
2257  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
2258  //      conversion sequence than an ellipsis conversion sequence
2259  //      (13.3.3.1.3).
2260  //
2261  // C++0x [over.best.ics]p10:
2262  //   For the purpose of ranking implicit conversion sequences as
2263  //   described in 13.3.3.2, the ambiguous conversion sequence is
2264  //   treated as a user-defined sequence that is indistinguishable
2265  //   from any other user-defined conversion sequence.
2266  if (ICS1.getKindRank() < ICS2.getKindRank())
2267    return ImplicitConversionSequence::Better;
2268  else if (ICS2.getKindRank() < ICS1.getKindRank())
2269    return ImplicitConversionSequence::Worse;
2270
2271  // The following checks require both conversion sequences to be of
2272  // the same kind.
2273  if (ICS1.getKind() != ICS2.getKind())
2274    return ImplicitConversionSequence::Indistinguishable;
2275
2276  // Two implicit conversion sequences of the same form are
2277  // indistinguishable conversion sequences unless one of the
2278  // following rules apply: (C++ 13.3.3.2p3):
2279  if (ICS1.isStandard())
2280    return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
2281  else if (ICS1.isUserDefined()) {
2282    // User-defined conversion sequence U1 is a better conversion
2283    // sequence than another user-defined conversion sequence U2 if
2284    // they contain the same user-defined conversion function or
2285    // constructor and if the second standard conversion sequence of
2286    // U1 is better than the second standard conversion sequence of
2287    // U2 (C++ 13.3.3.2p3).
2288    if (ICS1.UserDefined.ConversionFunction ==
2289          ICS2.UserDefined.ConversionFunction)
2290      return CompareStandardConversionSequences(S,
2291                                                ICS1.UserDefined.After,
2292                                                ICS2.UserDefined.After);
2293  }
2294
2295  return ImplicitConversionSequence::Indistinguishable;
2296}
2297
2298static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2299  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2300    Qualifiers Quals;
2301    T1 = Context.getUnqualifiedArrayType(T1, Quals);
2302    T2 = Context.getUnqualifiedArrayType(T2, Quals);
2303  }
2304
2305  return Context.hasSameUnqualifiedType(T1, T2);
2306}
2307
2308// Per 13.3.3.2p3, compare the given standard conversion sequences to
2309// determine if one is a proper subset of the other.
2310static ImplicitConversionSequence::CompareKind
2311compareStandardConversionSubsets(ASTContext &Context,
2312                                 const StandardConversionSequence& SCS1,
2313                                 const StandardConversionSequence& SCS2) {
2314  ImplicitConversionSequence::CompareKind Result
2315    = ImplicitConversionSequence::Indistinguishable;
2316
2317  // the identity conversion sequence is considered to be a subsequence of
2318  // any non-identity conversion sequence
2319  if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2320    if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2321      return ImplicitConversionSequence::Better;
2322    else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2323      return ImplicitConversionSequence::Worse;
2324  }
2325
2326  if (SCS1.Second != SCS2.Second) {
2327    if (SCS1.Second == ICK_Identity)
2328      Result = ImplicitConversionSequence::Better;
2329    else if (SCS2.Second == ICK_Identity)
2330      Result = ImplicitConversionSequence::Worse;
2331    else
2332      return ImplicitConversionSequence::Indistinguishable;
2333  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
2334    return ImplicitConversionSequence::Indistinguishable;
2335
2336  if (SCS1.Third == SCS2.Third) {
2337    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2338                             : ImplicitConversionSequence::Indistinguishable;
2339  }
2340
2341  if (SCS1.Third == ICK_Identity)
2342    return Result == ImplicitConversionSequence::Worse
2343             ? ImplicitConversionSequence::Indistinguishable
2344             : ImplicitConversionSequence::Better;
2345
2346  if (SCS2.Third == ICK_Identity)
2347    return Result == ImplicitConversionSequence::Better
2348             ? ImplicitConversionSequence::Indistinguishable
2349             : ImplicitConversionSequence::Worse;
2350
2351  return ImplicitConversionSequence::Indistinguishable;
2352}
2353
2354/// \brief Determine whether one of the given reference bindings is better
2355/// than the other based on what kind of bindings they are.
2356static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2357                                       const StandardConversionSequence &SCS2) {
2358  // C++0x [over.ics.rank]p3b4:
2359  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2360  //      implicit object parameter of a non-static member function declared
2361  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
2362  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
2363  //      lvalue reference to a function lvalue and S2 binds an rvalue
2364  //      reference*.
2365  //
2366  // FIXME: Rvalue references. We're going rogue with the above edits,
2367  // because the semantics in the current C++0x working paper (N3225 at the
2368  // time of this writing) break the standard definition of std::forward
2369  // and std::reference_wrapper when dealing with references to functions.
2370  // Proposed wording changes submitted to CWG for consideration.
2371  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2372      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2373    return false;
2374
2375  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2376          SCS2.IsLvalueReference) ||
2377         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2378          !SCS2.IsLvalueReference);
2379}
2380
2381/// CompareStandardConversionSequences - Compare two standard
2382/// conversion sequences to determine whether one is better than the
2383/// other or if they are indistinguishable (C++ 13.3.3.2p3).
2384static ImplicitConversionSequence::CompareKind
2385CompareStandardConversionSequences(Sema &S,
2386                                   const StandardConversionSequence& SCS1,
2387                                   const StandardConversionSequence& SCS2)
2388{
2389  // Standard conversion sequence S1 is a better conversion sequence
2390  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2391
2392  //  -- S1 is a proper subsequence of S2 (comparing the conversion
2393  //     sequences in the canonical form defined by 13.3.3.1.1,
2394  //     excluding any Lvalue Transformation; the identity conversion
2395  //     sequence is considered to be a subsequence of any
2396  //     non-identity conversion sequence) or, if not that,
2397  if (ImplicitConversionSequence::CompareKind CK
2398        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
2399    return CK;
2400
2401  //  -- the rank of S1 is better than the rank of S2 (by the rules
2402  //     defined below), or, if not that,
2403  ImplicitConversionRank Rank1 = SCS1.getRank();
2404  ImplicitConversionRank Rank2 = SCS2.getRank();
2405  if (Rank1 < Rank2)
2406    return ImplicitConversionSequence::Better;
2407  else if (Rank2 < Rank1)
2408    return ImplicitConversionSequence::Worse;
2409
2410  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2411  // are indistinguishable unless one of the following rules
2412  // applies:
2413
2414  //   A conversion that is not a conversion of a pointer, or
2415  //   pointer to member, to bool is better than another conversion
2416  //   that is such a conversion.
2417  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2418    return SCS2.isPointerConversionToBool()
2419             ? ImplicitConversionSequence::Better
2420             : ImplicitConversionSequence::Worse;
2421
2422  // C++ [over.ics.rank]p4b2:
2423  //
2424  //   If class B is derived directly or indirectly from class A,
2425  //   conversion of B* to A* is better than conversion of B* to
2426  //   void*, and conversion of A* to void* is better than conversion
2427  //   of B* to void*.
2428  bool SCS1ConvertsToVoid
2429    = SCS1.isPointerConversionToVoidPointer(S.Context);
2430  bool SCS2ConvertsToVoid
2431    = SCS2.isPointerConversionToVoidPointer(S.Context);
2432  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2433    // Exactly one of the conversion sequences is a conversion to
2434    // a void pointer; it's the worse conversion.
2435    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2436                              : ImplicitConversionSequence::Worse;
2437  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2438    // Neither conversion sequence converts to a void pointer; compare
2439    // their derived-to-base conversions.
2440    if (ImplicitConversionSequence::CompareKind DerivedCK
2441          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
2442      return DerivedCK;
2443  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2444    // Both conversion sequences are conversions to void
2445    // pointers. Compare the source types to determine if there's an
2446    // inheritance relationship in their sources.
2447    QualType FromType1 = SCS1.getFromType();
2448    QualType FromType2 = SCS2.getFromType();
2449
2450    // Adjust the types we're converting from via the array-to-pointer
2451    // conversion, if we need to.
2452    if (SCS1.First == ICK_Array_To_Pointer)
2453      FromType1 = S.Context.getArrayDecayedType(FromType1);
2454    if (SCS2.First == ICK_Array_To_Pointer)
2455      FromType2 = S.Context.getArrayDecayedType(FromType2);
2456
2457    QualType FromPointee1
2458      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2459    QualType FromPointee2
2460      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2461
2462    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
2463      return ImplicitConversionSequence::Better;
2464    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
2465      return ImplicitConversionSequence::Worse;
2466
2467    // Objective-C++: If one interface is more specific than the
2468    // other, it is the better one.
2469    const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2470    const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2471    if (FromIface1 && FromIface1) {
2472      if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2473        return ImplicitConversionSequence::Better;
2474      else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2475        return ImplicitConversionSequence::Worse;
2476    }
2477  }
2478
2479  // Compare based on qualification conversions (C++ 13.3.3.2p3,
2480  // bullet 3).
2481  if (ImplicitConversionSequence::CompareKind QualCK
2482        = CompareQualificationConversions(S, SCS1, SCS2))
2483    return QualCK;
2484
2485  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
2486    // Check for a better reference binding based on the kind of bindings.
2487    if (isBetterReferenceBindingKind(SCS1, SCS2))
2488      return ImplicitConversionSequence::Better;
2489    else if (isBetterReferenceBindingKind(SCS2, SCS1))
2490      return ImplicitConversionSequence::Worse;
2491
2492    // C++ [over.ics.rank]p3b4:
2493    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
2494    //      which the references refer are the same type except for
2495    //      top-level cv-qualifiers, and the type to which the reference
2496    //      initialized by S2 refers is more cv-qualified than the type
2497    //      to which the reference initialized by S1 refers.
2498    QualType T1 = SCS1.getToType(2);
2499    QualType T2 = SCS2.getToType(2);
2500    T1 = S.Context.getCanonicalType(T1);
2501    T2 = S.Context.getCanonicalType(T2);
2502    Qualifiers T1Quals, T2Quals;
2503    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2504    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
2505    if (UnqualT1 == UnqualT2) {
2506      // If the type is an array type, promote the element qualifiers to the
2507      // type for comparison.
2508      if (isa<ArrayType>(T1) && T1Quals)
2509        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
2510      if (isa<ArrayType>(T2) && T2Quals)
2511        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
2512      if (T2.isMoreQualifiedThan(T1))
2513        return ImplicitConversionSequence::Better;
2514      else if (T1.isMoreQualifiedThan(T2))
2515        return ImplicitConversionSequence::Worse;
2516    }
2517  }
2518
2519  return ImplicitConversionSequence::Indistinguishable;
2520}
2521
2522/// CompareQualificationConversions - Compares two standard conversion
2523/// sequences to determine whether they can be ranked based on their
2524/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2525ImplicitConversionSequence::CompareKind
2526CompareQualificationConversions(Sema &S,
2527                                const StandardConversionSequence& SCS1,
2528                                const StandardConversionSequence& SCS2) {
2529  // C++ 13.3.3.2p3:
2530  //  -- S1 and S2 differ only in their qualification conversion and
2531  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
2532  //     cv-qualification signature of type T1 is a proper subset of
2533  //     the cv-qualification signature of type T2, and S1 is not the
2534  //     deprecated string literal array-to-pointer conversion (4.2).
2535  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2536      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2537    return ImplicitConversionSequence::Indistinguishable;
2538
2539  // FIXME: the example in the standard doesn't use a qualification
2540  // conversion (!)
2541  QualType T1 = SCS1.getToType(2);
2542  QualType T2 = SCS2.getToType(2);
2543  T1 = S.Context.getCanonicalType(T1);
2544  T2 = S.Context.getCanonicalType(T2);
2545  Qualifiers T1Quals, T2Quals;
2546  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2547  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
2548
2549  // If the types are the same, we won't learn anything by unwrapped
2550  // them.
2551  if (UnqualT1 == UnqualT2)
2552    return ImplicitConversionSequence::Indistinguishable;
2553
2554  // If the type is an array type, promote the element qualifiers to the type
2555  // for comparison.
2556  if (isa<ArrayType>(T1) && T1Quals)
2557    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
2558  if (isa<ArrayType>(T2) && T2Quals)
2559    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
2560
2561  ImplicitConversionSequence::CompareKind Result
2562    = ImplicitConversionSequence::Indistinguishable;
2563  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
2564    // Within each iteration of the loop, we check the qualifiers to
2565    // determine if this still looks like a qualification
2566    // conversion. Then, if all is well, we unwrap one more level of
2567    // pointers or pointers-to-members and do it all again
2568    // until there are no more pointers or pointers-to-members left
2569    // to unwrap. This essentially mimics what
2570    // IsQualificationConversion does, but here we're checking for a
2571    // strict subset of qualifiers.
2572    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2573      // The qualifiers are the same, so this doesn't tell us anything
2574      // about how the sequences rank.
2575      ;
2576    else if (T2.isMoreQualifiedThan(T1)) {
2577      // T1 has fewer qualifiers, so it could be the better sequence.
2578      if (Result == ImplicitConversionSequence::Worse)
2579        // Neither has qualifiers that are a subset of the other's
2580        // qualifiers.
2581        return ImplicitConversionSequence::Indistinguishable;
2582
2583      Result = ImplicitConversionSequence::Better;
2584    } else if (T1.isMoreQualifiedThan(T2)) {
2585      // T2 has fewer qualifiers, so it could be the better sequence.
2586      if (Result == ImplicitConversionSequence::Better)
2587        // Neither has qualifiers that are a subset of the other's
2588        // qualifiers.
2589        return ImplicitConversionSequence::Indistinguishable;
2590
2591      Result = ImplicitConversionSequence::Worse;
2592    } else {
2593      // Qualifiers are disjoint.
2594      return ImplicitConversionSequence::Indistinguishable;
2595    }
2596
2597    // If the types after this point are equivalent, we're done.
2598    if (S.Context.hasSameUnqualifiedType(T1, T2))
2599      break;
2600  }
2601
2602  // Check that the winning standard conversion sequence isn't using
2603  // the deprecated string literal array to pointer conversion.
2604  switch (Result) {
2605  case ImplicitConversionSequence::Better:
2606    if (SCS1.DeprecatedStringLiteralToCharPtr)
2607      Result = ImplicitConversionSequence::Indistinguishable;
2608    break;
2609
2610  case ImplicitConversionSequence::Indistinguishable:
2611    break;
2612
2613  case ImplicitConversionSequence::Worse:
2614    if (SCS2.DeprecatedStringLiteralToCharPtr)
2615      Result = ImplicitConversionSequence::Indistinguishable;
2616    break;
2617  }
2618
2619  return Result;
2620}
2621
2622/// CompareDerivedToBaseConversions - Compares two standard conversion
2623/// sequences to determine whether they can be ranked based on their
2624/// various kinds of derived-to-base conversions (C++
2625/// [over.ics.rank]p4b3).  As part of these checks, we also look at
2626/// conversions between Objective-C interface types.
2627ImplicitConversionSequence::CompareKind
2628CompareDerivedToBaseConversions(Sema &S,
2629                                const StandardConversionSequence& SCS1,
2630                                const StandardConversionSequence& SCS2) {
2631  QualType FromType1 = SCS1.getFromType();
2632  QualType ToType1 = SCS1.getToType(1);
2633  QualType FromType2 = SCS2.getFromType();
2634  QualType ToType2 = SCS2.getToType(1);
2635
2636  // Adjust the types we're converting from via the array-to-pointer
2637  // conversion, if we need to.
2638  if (SCS1.First == ICK_Array_To_Pointer)
2639    FromType1 = S.Context.getArrayDecayedType(FromType1);
2640  if (SCS2.First == ICK_Array_To_Pointer)
2641    FromType2 = S.Context.getArrayDecayedType(FromType2);
2642
2643  // Canonicalize all of the types.
2644  FromType1 = S.Context.getCanonicalType(FromType1);
2645  ToType1 = S.Context.getCanonicalType(ToType1);
2646  FromType2 = S.Context.getCanonicalType(FromType2);
2647  ToType2 = S.Context.getCanonicalType(ToType2);
2648
2649  // C++ [over.ics.rank]p4b3:
2650  //
2651  //   If class B is derived directly or indirectly from class A and
2652  //   class C is derived directly or indirectly from B,
2653  //
2654  // For Objective-C, we let A, B, and C also be Objective-C
2655  // interfaces.
2656
2657  // Compare based on pointer conversions.
2658  if (SCS1.Second == ICK_Pointer_Conversion &&
2659      SCS2.Second == ICK_Pointer_Conversion &&
2660      /*FIXME: Remove if Objective-C id conversions get their own rank*/
2661      FromType1->isPointerType() && FromType2->isPointerType() &&
2662      ToType1->isPointerType() && ToType2->isPointerType()) {
2663    QualType FromPointee1
2664      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2665    QualType ToPointee1
2666      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2667    QualType FromPointee2
2668      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2669    QualType ToPointee2
2670      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2671
2672    const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2673    const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2674    const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2675    const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
2676
2677    //   -- conversion of C* to B* is better than conversion of C* to A*,
2678    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2679      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
2680        return ImplicitConversionSequence::Better;
2681      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
2682        return ImplicitConversionSequence::Worse;
2683
2684      if (ToIface1 && ToIface2) {
2685        if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2686          return ImplicitConversionSequence::Better;
2687        else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2688          return ImplicitConversionSequence::Worse;
2689      }
2690    }
2691
2692    //   -- conversion of B* to A* is better than conversion of C* to A*,
2693    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2694      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
2695        return ImplicitConversionSequence::Better;
2696      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
2697        return ImplicitConversionSequence::Worse;
2698
2699      if (FromIface1 && FromIface2) {
2700        if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2701          return ImplicitConversionSequence::Better;
2702        else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2703          return ImplicitConversionSequence::Worse;
2704      }
2705    }
2706  }
2707
2708  // Ranking of member-pointer types.
2709  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2710      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2711      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2712    const MemberPointerType * FromMemPointer1 =
2713                                        FromType1->getAs<MemberPointerType>();
2714    const MemberPointerType * ToMemPointer1 =
2715                                          ToType1->getAs<MemberPointerType>();
2716    const MemberPointerType * FromMemPointer2 =
2717                                          FromType2->getAs<MemberPointerType>();
2718    const MemberPointerType * ToMemPointer2 =
2719                                          ToType2->getAs<MemberPointerType>();
2720    const Type *FromPointeeType1 = FromMemPointer1->getClass();
2721    const Type *ToPointeeType1 = ToMemPointer1->getClass();
2722    const Type *FromPointeeType2 = FromMemPointer2->getClass();
2723    const Type *ToPointeeType2 = ToMemPointer2->getClass();
2724    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2725    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2726    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2727    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
2728    // conversion of A::* to B::* is better than conversion of A::* to C::*,
2729    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2730      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
2731        return ImplicitConversionSequence::Worse;
2732      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
2733        return ImplicitConversionSequence::Better;
2734    }
2735    // conversion of B::* to C::* is better than conversion of A::* to C::*
2736    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2737      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
2738        return ImplicitConversionSequence::Better;
2739      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
2740        return ImplicitConversionSequence::Worse;
2741    }
2742  }
2743
2744  if (SCS1.Second == ICK_Derived_To_Base) {
2745    //   -- conversion of C to B is better than conversion of C to A,
2746    //   -- binding of an expression of type C to a reference of type
2747    //      B& is better than binding an expression of type C to a
2748    //      reference of type A&,
2749    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2750        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2751      if (S.IsDerivedFrom(ToType1, ToType2))
2752        return ImplicitConversionSequence::Better;
2753      else if (S.IsDerivedFrom(ToType2, ToType1))
2754        return ImplicitConversionSequence::Worse;
2755    }
2756
2757    //   -- conversion of B to A is better than conversion of C to A.
2758    //   -- binding of an expression of type B to a reference of type
2759    //      A& is better than binding an expression of type C to a
2760    //      reference of type A&,
2761    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2762        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2763      if (S.IsDerivedFrom(FromType2, FromType1))
2764        return ImplicitConversionSequence::Better;
2765      else if (S.IsDerivedFrom(FromType1, FromType2))
2766        return ImplicitConversionSequence::Worse;
2767    }
2768  }
2769
2770  return ImplicitConversionSequence::Indistinguishable;
2771}
2772
2773/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2774/// determine whether they are reference-related,
2775/// reference-compatible, reference-compatible with added
2776/// qualification, or incompatible, for use in C++ initialization by
2777/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2778/// type, and the first type (T1) is the pointee type of the reference
2779/// type being initialized.
2780Sema::ReferenceCompareResult
2781Sema::CompareReferenceRelationship(SourceLocation Loc,
2782                                   QualType OrigT1, QualType OrigT2,
2783                                   bool &DerivedToBase,
2784                                   bool &ObjCConversion) {
2785  assert(!OrigT1->isReferenceType() &&
2786    "T1 must be the pointee type of the reference type");
2787  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2788
2789  QualType T1 = Context.getCanonicalType(OrigT1);
2790  QualType T2 = Context.getCanonicalType(OrigT2);
2791  Qualifiers T1Quals, T2Quals;
2792  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2793  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2794
2795  // C++ [dcl.init.ref]p4:
2796  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2797  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
2798  //   T1 is a base class of T2.
2799  DerivedToBase = false;
2800  ObjCConversion = false;
2801  if (UnqualT1 == UnqualT2) {
2802    // Nothing to do.
2803  } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
2804           IsDerivedFrom(UnqualT2, UnqualT1))
2805    DerivedToBase = true;
2806  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2807           UnqualT2->isObjCObjectOrInterfaceType() &&
2808           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2809    ObjCConversion = true;
2810  else
2811    return Ref_Incompatible;
2812
2813  // At this point, we know that T1 and T2 are reference-related (at
2814  // least).
2815
2816  // If the type is an array type, promote the element qualifiers to the type
2817  // for comparison.
2818  if (isa<ArrayType>(T1) && T1Quals)
2819    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2820  if (isa<ArrayType>(T2) && T2Quals)
2821    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2822
2823  // C++ [dcl.init.ref]p4:
2824  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2825  //   reference-related to T2 and cv1 is the same cv-qualification
2826  //   as, or greater cv-qualification than, cv2. For purposes of
2827  //   overload resolution, cases for which cv1 is greater
2828  //   cv-qualification than cv2 are identified as
2829  //   reference-compatible with added qualification (see 13.3.3.2).
2830  if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2831    return Ref_Compatible;
2832  else if (T1.isMoreQualifiedThan(T2))
2833    return Ref_Compatible_With_Added_Qualification;
2834  else
2835    return Ref_Related;
2836}
2837
2838/// \brief Look for a user-defined conversion to an value reference-compatible
2839///        with DeclType. Return true if something definite is found.
2840static bool
2841FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2842                         QualType DeclType, SourceLocation DeclLoc,
2843                         Expr *Init, QualType T2, bool AllowRvalues,
2844                         bool AllowExplicit) {
2845  assert(T2->isRecordType() && "Can only find conversions of record types.");
2846  CXXRecordDecl *T2RecordDecl
2847    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2848
2849  OverloadCandidateSet CandidateSet(DeclLoc);
2850  const UnresolvedSetImpl *Conversions
2851    = T2RecordDecl->getVisibleConversionFunctions();
2852  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2853         E = Conversions->end(); I != E; ++I) {
2854    NamedDecl *D = *I;
2855    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2856    if (isa<UsingShadowDecl>(D))
2857      D = cast<UsingShadowDecl>(D)->getTargetDecl();
2858
2859    FunctionTemplateDecl *ConvTemplate
2860      = dyn_cast<FunctionTemplateDecl>(D);
2861    CXXConversionDecl *Conv;
2862    if (ConvTemplate)
2863      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2864    else
2865      Conv = cast<CXXConversionDecl>(D);
2866
2867    // If this is an explicit conversion, and we're not allowed to consider
2868    // explicit conversions, skip it.
2869    if (!AllowExplicit && Conv->isExplicit())
2870      continue;
2871
2872    if (AllowRvalues) {
2873      bool DerivedToBase = false;
2874      bool ObjCConversion = false;
2875      if (!ConvTemplate &&
2876          S.CompareReferenceRelationship(
2877            DeclLoc,
2878            Conv->getConversionType().getNonReferenceType()
2879              .getUnqualifiedType(),
2880            DeclType.getNonReferenceType().getUnqualifiedType(),
2881            DerivedToBase, ObjCConversion) ==
2882          Sema::Ref_Incompatible)
2883        continue;
2884    } else {
2885      // If the conversion function doesn't return a reference type,
2886      // it can't be considered for this conversion. An rvalue reference
2887      // is only acceptable if its referencee is a function type.
2888
2889      const ReferenceType *RefType =
2890        Conv->getConversionType()->getAs<ReferenceType>();
2891      if (!RefType ||
2892          (!RefType->isLValueReferenceType() &&
2893           !RefType->getPointeeType()->isFunctionType()))
2894        continue;
2895    }
2896
2897    if (ConvTemplate)
2898      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2899                                       Init, DeclType, CandidateSet);
2900    else
2901      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2902                               DeclType, CandidateSet);
2903  }
2904
2905  OverloadCandidateSet::iterator Best;
2906  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
2907  case OR_Success:
2908    // C++ [over.ics.ref]p1:
2909    //
2910    //   [...] If the parameter binds directly to the result of
2911    //   applying a conversion function to the argument
2912    //   expression, the implicit conversion sequence is a
2913    //   user-defined conversion sequence (13.3.3.1.2), with the
2914    //   second standard conversion sequence either an identity
2915    //   conversion or, if the conversion function returns an
2916    //   entity of a type that is a derived class of the parameter
2917    //   type, a derived-to-base Conversion.
2918    if (!Best->FinalConversion.DirectBinding)
2919      return false;
2920
2921    ICS.setUserDefined();
2922    ICS.UserDefined.Before = Best->Conversions[0].Standard;
2923    ICS.UserDefined.After = Best->FinalConversion;
2924    ICS.UserDefined.ConversionFunction = Best->Function;
2925    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
2926    ICS.UserDefined.EllipsisConversion = false;
2927    assert(ICS.UserDefined.After.ReferenceBinding &&
2928           ICS.UserDefined.After.DirectBinding &&
2929           "Expected a direct reference binding!");
2930    return true;
2931
2932  case OR_Ambiguous:
2933    ICS.setAmbiguous();
2934    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2935         Cand != CandidateSet.end(); ++Cand)
2936      if (Cand->Viable)
2937        ICS.Ambiguous.addConversion(Cand->Function);
2938    return true;
2939
2940  case OR_No_Viable_Function:
2941  case OR_Deleted:
2942    // There was no suitable conversion, or we found a deleted
2943    // conversion; continue with other checks.
2944    return false;
2945  }
2946
2947  return false;
2948}
2949
2950/// \brief Compute an implicit conversion sequence for reference
2951/// initialization.
2952static ImplicitConversionSequence
2953TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2954                 SourceLocation DeclLoc,
2955                 bool SuppressUserConversions,
2956                 bool AllowExplicit) {
2957  assert(DeclType->isReferenceType() && "Reference init needs a reference");
2958
2959  // Most paths end in a failed conversion.
2960  ImplicitConversionSequence ICS;
2961  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2962
2963  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2964  QualType T2 = Init->getType();
2965
2966  // If the initializer is the address of an overloaded function, try
2967  // to resolve the overloaded function. If all goes well, T2 is the
2968  // type of the resulting function.
2969  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2970    DeclAccessPair Found;
2971    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2972                                                                false, Found))
2973      T2 = Fn->getType();
2974  }
2975
2976  // Compute some basic properties of the types and the initializer.
2977  bool isRValRef = DeclType->isRValueReferenceType();
2978  bool DerivedToBase = false;
2979  bool ObjCConversion = false;
2980  Expr::Classification InitCategory = Init->Classify(S.Context);
2981  Sema::ReferenceCompareResult RefRelationship
2982    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2983                                     ObjCConversion);
2984
2985
2986  // C++0x [dcl.init.ref]p5:
2987  //   A reference to type "cv1 T1" is initialized by an expression
2988  //   of type "cv2 T2" as follows:
2989
2990  //     -- If reference is an lvalue reference and the initializer expression
2991  if (!isRValRef) {
2992    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2993    //        reference-compatible with "cv2 T2," or
2994    //
2995    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2996    if (InitCategory.isLValue() &&
2997        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2998      // C++ [over.ics.ref]p1:
2999      //   When a parameter of reference type binds directly (8.5.3)
3000      //   to an argument expression, the implicit conversion sequence
3001      //   is the identity conversion, unless the argument expression
3002      //   has a type that is a derived class of the parameter type,
3003      //   in which case the implicit conversion sequence is a
3004      //   derived-to-base Conversion (13.3.3.1).
3005      ICS.setStandard();
3006      ICS.Standard.First = ICK_Identity;
3007      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3008                         : ObjCConversion? ICK_Compatible_Conversion
3009                         : ICK_Identity;
3010      ICS.Standard.Third = ICK_Identity;
3011      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3012      ICS.Standard.setToType(0, T2);
3013      ICS.Standard.setToType(1, T1);
3014      ICS.Standard.setToType(2, T1);
3015      ICS.Standard.ReferenceBinding = true;
3016      ICS.Standard.DirectBinding = true;
3017      ICS.Standard.IsLvalueReference = !isRValRef;
3018      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3019      ICS.Standard.BindsToRvalue = false;
3020      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3021      ICS.Standard.CopyConstructor = 0;
3022
3023      // Nothing more to do: the inaccessibility/ambiguity check for
3024      // derived-to-base conversions is suppressed when we're
3025      // computing the implicit conversion sequence (C++
3026      // [over.best.ics]p2).
3027      return ICS;
3028    }
3029
3030    //       -- has a class type (i.e., T2 is a class type), where T1 is
3031    //          not reference-related to T2, and can be implicitly
3032    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
3033    //          is reference-compatible with "cv3 T3" 92) (this
3034    //          conversion is selected by enumerating the applicable
3035    //          conversion functions (13.3.1.6) and choosing the best
3036    //          one through overload resolution (13.3)),
3037    if (!SuppressUserConversions && T2->isRecordType() &&
3038        !S.RequireCompleteType(DeclLoc, T2, 0) &&
3039        RefRelationship == Sema::Ref_Incompatible) {
3040      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3041                                   Init, T2, /*AllowRvalues=*/false,
3042                                   AllowExplicit))
3043        return ICS;
3044    }
3045  }
3046
3047  //     -- Otherwise, the reference shall be an lvalue reference to a
3048  //        non-volatile const type (i.e., cv1 shall be const), or the reference
3049  //        shall be an rvalue reference.
3050  //
3051  // We actually handle one oddity of C++ [over.ics.ref] at this
3052  // point, which is that, due to p2 (which short-circuits reference
3053  // binding by only attempting a simple conversion for non-direct
3054  // bindings) and p3's strange wording, we allow a const volatile
3055  // reference to bind to an rvalue. Hence the check for the presence
3056  // of "const" rather than checking for "const" being the only
3057  // qualifier.
3058  // This is also the point where rvalue references and lvalue inits no longer
3059  // go together.
3060  if (!isRValRef && !T1.isConstQualified())
3061    return ICS;
3062
3063  //       -- If the initializer expression
3064  //
3065  //            -- is an xvalue, class prvalue, array prvalue or function
3066  //               lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3067  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3068      (InitCategory.isXValue() ||
3069      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3070      (InitCategory.isLValue() && T2->isFunctionType()))) {
3071    ICS.setStandard();
3072    ICS.Standard.First = ICK_Identity;
3073    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3074                      : ObjCConversion? ICK_Compatible_Conversion
3075                      : ICK_Identity;
3076    ICS.Standard.Third = ICK_Identity;
3077    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3078    ICS.Standard.setToType(0, T2);
3079    ICS.Standard.setToType(1, T1);
3080    ICS.Standard.setToType(2, T1);
3081    ICS.Standard.ReferenceBinding = true;
3082    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3083    // binding unless we're binding to a class prvalue.
3084    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3085    // allow the use of rvalue references in C++98/03 for the benefit of
3086    // standard library implementors; therefore, we need the xvalue check here.
3087    ICS.Standard.DirectBinding =
3088      S.getLangOptions().CPlusPlus0x ||
3089      (InitCategory.isPRValue() && !T2->isRecordType());
3090    ICS.Standard.IsLvalueReference = !isRValRef;
3091    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3092    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
3093    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3094    ICS.Standard.CopyConstructor = 0;
3095    return ICS;
3096  }
3097
3098  //            -- has a class type (i.e., T2 is a class type), where T1 is not
3099  //               reference-related to T2, and can be implicitly converted to
3100  //               an xvalue, class prvalue, or function lvalue of type
3101  //               "cv3 T3", where "cv1 T1" is reference-compatible with
3102  //               "cv3 T3",
3103  //
3104  //          then the reference is bound to the value of the initializer
3105  //          expression in the first case and to the result of the conversion
3106  //          in the second case (or, in either case, to an appropriate base
3107  //          class subobject).
3108  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3109      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
3110      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3111                               Init, T2, /*AllowRvalues=*/true,
3112                               AllowExplicit)) {
3113    // In the second case, if the reference is an rvalue reference
3114    // and the second standard conversion sequence of the
3115    // user-defined conversion sequence includes an lvalue-to-rvalue
3116    // conversion, the program is ill-formed.
3117    if (ICS.isUserDefined() && isRValRef &&
3118        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3119      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3120
3121    return ICS;
3122  }
3123
3124  //       -- Otherwise, a temporary of type "cv1 T1" is created and
3125  //          initialized from the initializer expression using the
3126  //          rules for a non-reference copy initialization (8.5). The
3127  //          reference is then bound to the temporary. If T1 is
3128  //          reference-related to T2, cv1 must be the same
3129  //          cv-qualification as, or greater cv-qualification than,
3130  //          cv2; otherwise, the program is ill-formed.
3131  if (RefRelationship == Sema::Ref_Related) {
3132    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3133    // we would be reference-compatible or reference-compatible with
3134    // added qualification. But that wasn't the case, so the reference
3135    // initialization fails.
3136    return ICS;
3137  }
3138
3139  // If at least one of the types is a class type, the types are not
3140  // related, and we aren't allowed any user conversions, the
3141  // reference binding fails. This case is important for breaking
3142  // recursion, since TryImplicitConversion below will attempt to
3143  // create a temporary through the use of a copy constructor.
3144  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3145      (T1->isRecordType() || T2->isRecordType()))
3146    return ICS;
3147
3148  // If T1 is reference-related to T2 and the reference is an rvalue
3149  // reference, the initializer expression shall not be an lvalue.
3150  if (RefRelationship >= Sema::Ref_Related &&
3151      isRValRef && Init->Classify(S.Context).isLValue())
3152    return ICS;
3153
3154  // C++ [over.ics.ref]p2:
3155  //   When a parameter of reference type is not bound directly to
3156  //   an argument expression, the conversion sequence is the one
3157  //   required to convert the argument expression to the
3158  //   underlying type of the reference according to
3159  //   13.3.3.1. Conceptually, this conversion sequence corresponds
3160  //   to copy-initializing a temporary of the underlying type with
3161  //   the argument expression. Any difference in top-level
3162  //   cv-qualification is subsumed by the initialization itself
3163  //   and does not constitute a conversion.
3164  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3165                              /*AllowExplicit=*/false,
3166                              /*InOverloadResolution=*/false,
3167                              /*CStyle=*/false);
3168
3169  // Of course, that's still a reference binding.
3170  if (ICS.isStandard()) {
3171    ICS.Standard.ReferenceBinding = true;
3172    ICS.Standard.IsLvalueReference = !isRValRef;
3173    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3174    ICS.Standard.BindsToRvalue = true;
3175    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3176  } else if (ICS.isUserDefined()) {
3177    ICS.UserDefined.After.ReferenceBinding = true;
3178    ICS.Standard.IsLvalueReference = !isRValRef;
3179    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3180    ICS.Standard.BindsToRvalue = true;
3181    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3182  }
3183
3184  return ICS;
3185}
3186
3187/// TryCopyInitialization - Try to copy-initialize a value of type
3188/// ToType from the expression From. Return the implicit conversion
3189/// sequence required to pass this argument, which may be a bad
3190/// conversion sequence (meaning that the argument cannot be passed to
3191/// a parameter of this type). If @p SuppressUserConversions, then we
3192/// do not permit any user-defined conversion sequences.
3193static ImplicitConversionSequence
3194TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3195                      bool SuppressUserConversions,
3196                      bool InOverloadResolution) {
3197  if (ToType->isReferenceType())
3198    return TryReferenceInit(S, From, ToType,
3199                            /*FIXME:*/From->getLocStart(),
3200                            SuppressUserConversions,
3201                            /*AllowExplicit=*/false);
3202
3203  return TryImplicitConversion(S, From, ToType,
3204                               SuppressUserConversions,
3205                               /*AllowExplicit=*/false,
3206                               InOverloadResolution,
3207                               /*CStyle=*/false);
3208}
3209
3210/// TryObjectArgumentInitialization - Try to initialize the object
3211/// parameter of the given member function (@c Method) from the
3212/// expression @p From.
3213static ImplicitConversionSequence
3214TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3215                                Expr::Classification FromClassification,
3216                                CXXMethodDecl *Method,
3217                                CXXRecordDecl *ActingContext) {
3218  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
3219  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3220  //                 const volatile object.
3221  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3222    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
3223  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
3224
3225  // Set up the conversion sequence as a "bad" conversion, to allow us
3226  // to exit early.
3227  ImplicitConversionSequence ICS;
3228
3229  // We need to have an object of class type.
3230  QualType FromType = OrigFromType;
3231  if (const PointerType *PT = FromType->getAs<PointerType>()) {
3232    FromType = PT->getPointeeType();
3233
3234    // When we had a pointer, it's implicitly dereferenced, so we
3235    // better have an lvalue.
3236    assert(FromClassification.isLValue());
3237  }
3238
3239  assert(FromType->isRecordType());
3240
3241  // C++0x [over.match.funcs]p4:
3242  //   For non-static member functions, the type of the implicit object
3243  //   parameter is
3244  //
3245  //     — "lvalue reference to cv X" for functions declared without a
3246  //       ref-qualifier or with the & ref-qualifier
3247  //     — "rvalue reference to cv X" for functions declared with the &&
3248  //        ref-qualifier
3249  //
3250  // where X is the class of which the function is a member and cv is the
3251  // cv-qualification on the member function declaration.
3252  //
3253  // However, when finding an implicit conversion sequence for the argument, we
3254  // are not allowed to create temporaries or perform user-defined conversions
3255  // (C++ [over.match.funcs]p5). We perform a simplified version of
3256  // reference binding here, that allows class rvalues to bind to
3257  // non-constant references.
3258
3259  // First check the qualifiers.
3260  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
3261  if (ImplicitParamType.getCVRQualifiers()
3262                                    != FromTypeCanon.getLocalCVRQualifiers() &&
3263      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
3264    ICS.setBad(BadConversionSequence::bad_qualifiers,
3265               OrigFromType, ImplicitParamType);
3266    return ICS;
3267  }
3268
3269  // Check that we have either the same type or a derived type. It
3270  // affects the conversion rank.
3271  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
3272  ImplicitConversionKind SecondKind;
3273  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3274    SecondKind = ICK_Identity;
3275  } else if (S.IsDerivedFrom(FromType, ClassType))
3276    SecondKind = ICK_Derived_To_Base;
3277  else {
3278    ICS.setBad(BadConversionSequence::unrelated_class,
3279               FromType, ImplicitParamType);
3280    return ICS;
3281  }
3282
3283  // Check the ref-qualifier.
3284  switch (Method->getRefQualifier()) {
3285  case RQ_None:
3286    // Do nothing; we don't care about lvalueness or rvalueness.
3287    break;
3288
3289  case RQ_LValue:
3290    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3291      // non-const lvalue reference cannot bind to an rvalue
3292      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
3293                 ImplicitParamType);
3294      return ICS;
3295    }
3296    break;
3297
3298  case RQ_RValue:
3299    if (!FromClassification.isRValue()) {
3300      // rvalue reference cannot bind to an lvalue
3301      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
3302                 ImplicitParamType);
3303      return ICS;
3304    }
3305    break;
3306  }
3307
3308  // Success. Mark this as a reference binding.
3309  ICS.setStandard();
3310  ICS.Standard.setAsIdentityConversion();
3311  ICS.Standard.Second = SecondKind;
3312  ICS.Standard.setFromType(FromType);
3313  ICS.Standard.setAllToTypes(ImplicitParamType);
3314  ICS.Standard.ReferenceBinding = true;
3315  ICS.Standard.DirectBinding = true;
3316  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
3317  ICS.Standard.BindsToFunctionLvalue = false;
3318  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3319  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3320    = (Method->getRefQualifier() == RQ_None);
3321  return ICS;
3322}
3323
3324/// PerformObjectArgumentInitialization - Perform initialization of
3325/// the implicit object parameter for the given Method with the given
3326/// expression.
3327bool
3328Sema::PerformObjectArgumentInitialization(Expr *&From,
3329                                          NestedNameSpecifier *Qualifier,
3330                                          NamedDecl *FoundDecl,
3331                                          CXXMethodDecl *Method) {
3332  QualType FromRecordType, DestType;
3333  QualType ImplicitParamRecordType  =
3334    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
3335
3336  Expr::Classification FromClassification;
3337  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
3338    FromRecordType = PT->getPointeeType();
3339    DestType = Method->getThisType(Context);
3340    FromClassification = Expr::Classification::makeSimpleLValue();
3341  } else {
3342    FromRecordType = From->getType();
3343    DestType = ImplicitParamRecordType;
3344    FromClassification = From->Classify(Context);
3345  }
3346
3347  // Note that we always use the true parent context when performing
3348  // the actual argument initialization.
3349  ImplicitConversionSequence ICS
3350    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3351                                      Method, Method->getParent());
3352  if (ICS.isBad()) {
3353    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3354      Qualifiers FromQs = FromRecordType.getQualifiers();
3355      Qualifiers ToQs = DestType.getQualifiers();
3356      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3357      if (CVR) {
3358        Diag(From->getSourceRange().getBegin(),
3359             diag::err_member_function_call_bad_cvr)
3360          << Method->getDeclName() << FromRecordType << (CVR - 1)
3361          << From->getSourceRange();
3362        Diag(Method->getLocation(), diag::note_previous_decl)
3363          << Method->getDeclName();
3364        return true;
3365      }
3366    }
3367
3368    return Diag(From->getSourceRange().getBegin(),
3369                diag::err_implicit_object_parameter_init)
3370       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
3371  }
3372
3373  if (ICS.Standard.Second == ICK_Derived_To_Base)
3374    return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3375
3376  if (!Context.hasSameType(From->getType(), DestType))
3377    ImpCastExprToType(From, DestType, CK_NoOp,
3378                      From->getType()->isPointerType() ? VK_RValue : VK_LValue);
3379  return false;
3380}
3381
3382/// TryContextuallyConvertToBool - Attempt to contextually convert the
3383/// expression From to bool (C++0x [conv]p3).
3384static ImplicitConversionSequence
3385TryContextuallyConvertToBool(Sema &S, Expr *From) {
3386  // FIXME: This is pretty broken.
3387  return TryImplicitConversion(S, From, S.Context.BoolTy,
3388                               // FIXME: Are these flags correct?
3389                               /*SuppressUserConversions=*/false,
3390                               /*AllowExplicit=*/true,
3391                               /*InOverloadResolution=*/false,
3392                               /*CStyle=*/false);
3393}
3394
3395/// PerformContextuallyConvertToBool - Perform a contextual conversion
3396/// of the expression From to bool (C++0x [conv]p3).
3397bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3398  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
3399  if (!ICS.isBad())
3400    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
3401
3402  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
3403    return  Diag(From->getSourceRange().getBegin(),
3404                 diag::err_typecheck_bool_condition)
3405                  << From->getType() << From->getSourceRange();
3406  return true;
3407}
3408
3409/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3410/// expression From to 'id'.
3411static ImplicitConversionSequence
3412TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3413  QualType Ty = S.Context.getObjCIdType();
3414  return TryImplicitConversion(S, From, Ty,
3415                               // FIXME: Are these flags correct?
3416                               /*SuppressUserConversions=*/false,
3417                               /*AllowExplicit=*/true,
3418                               /*InOverloadResolution=*/false,
3419                               /*CStyle=*/false);
3420}
3421
3422/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3423/// of the expression From to 'id'.
3424bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
3425  QualType Ty = Context.getObjCIdType();
3426  ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
3427  if (!ICS.isBad())
3428    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3429  return true;
3430}
3431
3432/// \brief Attempt to convert the given expression to an integral or
3433/// enumeration type.
3434///
3435/// This routine will attempt to convert an expression of class type to an
3436/// integral or enumeration type, if that class type only has a single
3437/// conversion to an integral or enumeration type.
3438///
3439/// \param Loc The source location of the construct that requires the
3440/// conversion.
3441///
3442/// \param FromE The expression we're converting from.
3443///
3444/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3445/// have integral or enumeration type.
3446///
3447/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3448/// incomplete class type.
3449///
3450/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3451/// explicit conversion function (because no implicit conversion functions
3452/// were available). This is a recovery mode.
3453///
3454/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3455/// showing which conversion was picked.
3456///
3457/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3458/// conversion function that could convert to integral or enumeration type.
3459///
3460/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3461/// usable conversion function.
3462///
3463/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3464/// function, which may be an extension in this case.
3465///
3466/// \returns The expression, converted to an integral or enumeration type if
3467/// successful.
3468ExprResult
3469Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
3470                                         const PartialDiagnostic &NotIntDiag,
3471                                       const PartialDiagnostic &IncompleteDiag,
3472                                     const PartialDiagnostic &ExplicitConvDiag,
3473                                     const PartialDiagnostic &ExplicitConvNote,
3474                                         const PartialDiagnostic &AmbigDiag,
3475                                         const PartialDiagnostic &AmbigNote,
3476                                         const PartialDiagnostic &ConvDiag) {
3477  // We can't perform any more checking for type-dependent expressions.
3478  if (From->isTypeDependent())
3479    return Owned(From);
3480
3481  // If the expression already has integral or enumeration type, we're golden.
3482  QualType T = From->getType();
3483  if (T->isIntegralOrEnumerationType())
3484    return Owned(From);
3485
3486  // FIXME: Check for missing '()' if T is a function type?
3487
3488  // If we don't have a class type in C++, there's no way we can get an
3489  // expression of integral or enumeration type.
3490  const RecordType *RecordTy = T->getAs<RecordType>();
3491  if (!RecordTy || !getLangOptions().CPlusPlus) {
3492    Diag(Loc, NotIntDiag)
3493      << T << From->getSourceRange();
3494    return Owned(From);
3495  }
3496
3497  // We must have a complete class type.
3498  if (RequireCompleteType(Loc, T, IncompleteDiag))
3499    return Owned(From);
3500
3501  // Look for a conversion to an integral or enumeration type.
3502  UnresolvedSet<4> ViableConversions;
3503  UnresolvedSet<4> ExplicitConversions;
3504  const UnresolvedSetImpl *Conversions
3505    = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3506
3507  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3508                                   E = Conversions->end();
3509       I != E;
3510       ++I) {
3511    if (CXXConversionDecl *Conversion
3512          = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3513      if (Conversion->getConversionType().getNonReferenceType()
3514            ->isIntegralOrEnumerationType()) {
3515        if (Conversion->isExplicit())
3516          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3517        else
3518          ViableConversions.addDecl(I.getDecl(), I.getAccess());
3519      }
3520  }
3521
3522  switch (ViableConversions.size()) {
3523  case 0:
3524    if (ExplicitConversions.size() == 1) {
3525      DeclAccessPair Found = ExplicitConversions[0];
3526      CXXConversionDecl *Conversion
3527        = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3528
3529      // The user probably meant to invoke the given explicit
3530      // conversion; use it.
3531      QualType ConvTy
3532        = Conversion->getConversionType().getNonReferenceType();
3533      std::string TypeStr;
3534      ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3535
3536      Diag(Loc, ExplicitConvDiag)
3537        << T << ConvTy
3538        << FixItHint::CreateInsertion(From->getLocStart(),
3539                                      "static_cast<" + TypeStr + ">(")
3540        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3541                                      ")");
3542      Diag(Conversion->getLocation(), ExplicitConvNote)
3543        << ConvTy->isEnumeralType() << ConvTy;
3544
3545      // If we aren't in a SFINAE context, build a call to the
3546      // explicit conversion function.
3547      if (isSFINAEContext())
3548        return ExprError();
3549
3550      CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3551      ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3552      if (Result.isInvalid())
3553        return ExprError();
3554
3555      From = Result.get();
3556    }
3557
3558    // We'll complain below about a non-integral condition type.
3559    break;
3560
3561  case 1: {
3562    // Apply this conversion.
3563    DeclAccessPair Found = ViableConversions[0];
3564    CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3565
3566    CXXConversionDecl *Conversion
3567      = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3568    QualType ConvTy
3569      = Conversion->getConversionType().getNonReferenceType();
3570    if (ConvDiag.getDiagID()) {
3571      if (isSFINAEContext())
3572        return ExprError();
3573
3574      Diag(Loc, ConvDiag)
3575        << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3576    }
3577
3578    ExprResult Result = BuildCXXMemberCallExpr(From, Found,
3579                          cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3580    if (Result.isInvalid())
3581      return ExprError();
3582
3583    From = Result.get();
3584    break;
3585  }
3586
3587  default:
3588    Diag(Loc, AmbigDiag)
3589      << T << From->getSourceRange();
3590    for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3591      CXXConversionDecl *Conv
3592        = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3593      QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3594      Diag(Conv->getLocation(), AmbigNote)
3595        << ConvTy->isEnumeralType() << ConvTy;
3596    }
3597    return Owned(From);
3598  }
3599
3600  if (!From->getType()->isIntegralOrEnumerationType())
3601    Diag(Loc, NotIntDiag)
3602      << From->getType() << From->getSourceRange();
3603
3604  return Owned(From);
3605}
3606
3607/// AddOverloadCandidate - Adds the given function to the set of
3608/// candidate functions, using the given function call arguments.  If
3609/// @p SuppressUserConversions, then don't allow user-defined
3610/// conversions via constructors or conversion operators.
3611///
3612/// \para PartialOverloading true if we are performing "partial" overloading
3613/// based on an incomplete set of function arguments. This feature is used by
3614/// code completion.
3615void
3616Sema::AddOverloadCandidate(FunctionDecl *Function,
3617                           DeclAccessPair FoundDecl,
3618                           Expr **Args, unsigned NumArgs,
3619                           OverloadCandidateSet& CandidateSet,
3620                           bool SuppressUserConversions,
3621                           bool PartialOverloading) {
3622  const FunctionProtoType* Proto
3623    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
3624  assert(Proto && "Functions without a prototype cannot be overloaded");
3625  assert(!Function->getDescribedFunctionTemplate() &&
3626         "Use AddTemp∫lateOverloadCandidate for function templates");
3627
3628  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3629    if (!isa<CXXConstructorDecl>(Method)) {
3630      // If we get here, it's because we're calling a member function
3631      // that is named without a member access expression (e.g.,
3632      // "this->f") that was either written explicitly or created
3633      // implicitly. This can happen with a qualified call to a member
3634      // function, e.g., X::f(). We use an empty type for the implied
3635      // object argument (C++ [over.call.func]p3), and the acting context
3636      // is irrelevant.
3637      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
3638                         QualType(), Expr::Classification::makeSimpleLValue(),
3639                         Args, NumArgs, CandidateSet,
3640                         SuppressUserConversions);
3641      return;
3642    }
3643    // We treat a constructor like a non-member function, since its object
3644    // argument doesn't participate in overload resolution.
3645  }
3646
3647  if (!CandidateSet.isNewCandidate(Function))
3648    return;
3649
3650  // Overload resolution is always an unevaluated context.
3651  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
3652
3653  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3654    // C++ [class.copy]p3:
3655    //   A member function template is never instantiated to perform the copy
3656    //   of a class object to an object of its class type.
3657    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3658    if (NumArgs == 1 &&
3659        Constructor->isSpecializationCopyingObject() &&
3660        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3661         IsDerivedFrom(Args[0]->getType(), ClassType)))
3662      return;
3663  }
3664
3665  // Add this candidate
3666  CandidateSet.push_back(OverloadCandidate());
3667  OverloadCandidate& Candidate = CandidateSet.back();
3668  Candidate.FoundDecl = FoundDecl;
3669  Candidate.Function = Function;
3670  Candidate.Viable = true;
3671  Candidate.IsSurrogate = false;
3672  Candidate.IgnoreObjectArgument = false;
3673  Candidate.ExplicitCallArguments = NumArgs;
3674
3675  unsigned NumArgsInProto = Proto->getNumArgs();
3676
3677  // (C++ 13.3.2p2): A candidate function having fewer than m
3678  // parameters is viable only if it has an ellipsis in its parameter
3679  // list (8.3.5).
3680  if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3681      !Proto->isVariadic()) {
3682    Candidate.Viable = false;
3683    Candidate.FailureKind = ovl_fail_too_many_arguments;
3684    return;
3685  }
3686
3687  // (C++ 13.3.2p2): A candidate function having more than m parameters
3688  // is viable only if the (m+1)st parameter has a default argument
3689  // (8.3.6). For the purposes of overload resolution, the
3690  // parameter list is truncated on the right, so that there are
3691  // exactly m parameters.
3692  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
3693  if (NumArgs < MinRequiredArgs && !PartialOverloading) {
3694    // Not enough arguments.
3695    Candidate.Viable = false;
3696    Candidate.FailureKind = ovl_fail_too_few_arguments;
3697    return;
3698  }
3699
3700  // Determine the implicit conversion sequences for each of the
3701  // arguments.
3702  Candidate.Conversions.resize(NumArgs);
3703  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3704    if (ArgIdx < NumArgsInProto) {
3705      // (C++ 13.3.2p3): for F to be a viable function, there shall
3706      // exist for each argument an implicit conversion sequence
3707      // (13.3.3.1) that converts that argument to the corresponding
3708      // parameter of F.
3709      QualType ParamType = Proto->getArgType(ArgIdx);
3710      Candidate.Conversions[ArgIdx]
3711        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
3712                                SuppressUserConversions,
3713                                /*InOverloadResolution=*/true);
3714      if (Candidate.Conversions[ArgIdx].isBad()) {
3715        Candidate.Viable = false;
3716        Candidate.FailureKind = ovl_fail_bad_conversion;
3717        break;
3718      }
3719    } else {
3720      // (C++ 13.3.2p2): For the purposes of overload resolution, any
3721      // argument for which there is no corresponding parameter is
3722      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
3723      Candidate.Conversions[ArgIdx].setEllipsis();
3724    }
3725  }
3726}
3727
3728/// \brief Add all of the function declarations in the given function set to
3729/// the overload canddiate set.
3730void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
3731                                 Expr **Args, unsigned NumArgs,
3732                                 OverloadCandidateSet& CandidateSet,
3733                                 bool SuppressUserConversions) {
3734  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
3735    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3736    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3737      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
3738        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
3739                           cast<CXXMethodDecl>(FD)->getParent(),
3740                           Args[0]->getType(), Args[0]->Classify(Context),
3741                           Args + 1, NumArgs - 1,
3742                           CandidateSet, SuppressUserConversions);
3743      else
3744        AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
3745                             SuppressUserConversions);
3746    } else {
3747      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
3748      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3749          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
3750        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
3751                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
3752                                   /*FIXME: explicit args */ 0,
3753                                   Args[0]->getType(),
3754                                   Args[0]->Classify(Context),
3755                                   Args + 1, NumArgs - 1,
3756                                   CandidateSet,
3757                                   SuppressUserConversions);
3758      else
3759        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
3760                                     /*FIXME: explicit args */ 0,
3761                                     Args, NumArgs, CandidateSet,
3762                                     SuppressUserConversions);
3763    }
3764  }
3765}
3766
3767/// AddMethodCandidate - Adds a named decl (which is some kind of
3768/// method) as a method candidate to the given overload set.
3769void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
3770                              QualType ObjectType,
3771                              Expr::Classification ObjectClassification,
3772                              Expr **Args, unsigned NumArgs,
3773                              OverloadCandidateSet& CandidateSet,
3774                              bool SuppressUserConversions) {
3775  NamedDecl *Decl = FoundDecl.getDecl();
3776  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
3777
3778  if (isa<UsingShadowDecl>(Decl))
3779    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3780
3781  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3782    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3783           "Expected a member function template");
3784    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3785                               /*ExplicitArgs*/ 0,
3786                               ObjectType, ObjectClassification, Args, NumArgs,
3787                               CandidateSet,
3788                               SuppressUserConversions);
3789  } else {
3790    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
3791                       ObjectType, ObjectClassification, Args, NumArgs,
3792                       CandidateSet, SuppressUserConversions);
3793  }
3794}
3795
3796/// AddMethodCandidate - Adds the given C++ member function to the set
3797/// of candidate functions, using the given function call arguments
3798/// and the object argument (@c Object). For example, in a call
3799/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3800/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3801/// allow user-defined conversions via constructors or conversion
3802/// operators.
3803void
3804Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
3805                         CXXRecordDecl *ActingContext, QualType ObjectType,
3806                         Expr::Classification ObjectClassification,
3807                         Expr **Args, unsigned NumArgs,
3808                         OverloadCandidateSet& CandidateSet,
3809                         bool SuppressUserConversions) {
3810  const FunctionProtoType* Proto
3811    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
3812  assert(Proto && "Methods without a prototype cannot be overloaded");
3813  assert(!isa<CXXConstructorDecl>(Method) &&
3814         "Use AddOverloadCandidate for constructors");
3815
3816  if (!CandidateSet.isNewCandidate(Method))
3817    return;
3818
3819  // Overload resolution is always an unevaluated context.
3820  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
3821
3822  // Add this candidate
3823  CandidateSet.push_back(OverloadCandidate());
3824  OverloadCandidate& Candidate = CandidateSet.back();
3825  Candidate.FoundDecl = FoundDecl;
3826  Candidate.Function = Method;
3827  Candidate.IsSurrogate = false;
3828  Candidate.IgnoreObjectArgument = false;
3829  Candidate.ExplicitCallArguments = NumArgs;
3830
3831  unsigned NumArgsInProto = Proto->getNumArgs();
3832
3833  // (C++ 13.3.2p2): A candidate function having fewer than m
3834  // parameters is viable only if it has an ellipsis in its parameter
3835  // list (8.3.5).
3836  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3837    Candidate.Viable = false;
3838    Candidate.FailureKind = ovl_fail_too_many_arguments;
3839    return;
3840  }
3841
3842  // (C++ 13.3.2p2): A candidate function having more than m parameters
3843  // is viable only if the (m+1)st parameter has a default argument
3844  // (8.3.6). For the purposes of overload resolution, the
3845  // parameter list is truncated on the right, so that there are
3846  // exactly m parameters.
3847  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3848  if (NumArgs < MinRequiredArgs) {
3849    // Not enough arguments.
3850    Candidate.Viable = false;
3851    Candidate.FailureKind = ovl_fail_too_few_arguments;
3852    return;
3853  }
3854
3855  Candidate.Viable = true;
3856  Candidate.Conversions.resize(NumArgs + 1);
3857
3858  if (Method->isStatic() || ObjectType.isNull())
3859    // The implicit object argument is ignored.
3860    Candidate.IgnoreObjectArgument = true;
3861  else {
3862    // Determine the implicit conversion sequence for the object
3863    // parameter.
3864    Candidate.Conversions[0]
3865      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
3866                                        Method, ActingContext);
3867    if (Candidate.Conversions[0].isBad()) {
3868      Candidate.Viable = false;
3869      Candidate.FailureKind = ovl_fail_bad_conversion;
3870      return;
3871    }
3872  }
3873
3874  // Determine the implicit conversion sequences for each of the
3875  // arguments.
3876  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3877    if (ArgIdx < NumArgsInProto) {
3878      // (C++ 13.3.2p3): for F to be a viable function, there shall
3879      // exist for each argument an implicit conversion sequence
3880      // (13.3.3.1) that converts that argument to the corresponding
3881      // parameter of F.
3882      QualType ParamType = Proto->getArgType(ArgIdx);
3883      Candidate.Conversions[ArgIdx + 1]
3884        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
3885                                SuppressUserConversions,
3886                                /*InOverloadResolution=*/true);
3887      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
3888        Candidate.Viable = false;
3889        Candidate.FailureKind = ovl_fail_bad_conversion;
3890        break;
3891      }
3892    } else {
3893      // (C++ 13.3.2p2): For the purposes of overload resolution, any
3894      // argument for which there is no corresponding parameter is
3895      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
3896      Candidate.Conversions[ArgIdx + 1].setEllipsis();
3897    }
3898  }
3899}
3900
3901/// \brief Add a C++ member function template as a candidate to the candidate
3902/// set, using template argument deduction to produce an appropriate member
3903/// function template specialization.
3904void
3905Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3906                                 DeclAccessPair FoundDecl,
3907                                 CXXRecordDecl *ActingContext,
3908                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
3909                                 QualType ObjectType,
3910                                 Expr::Classification ObjectClassification,
3911                                 Expr **Args, unsigned NumArgs,
3912                                 OverloadCandidateSet& CandidateSet,
3913                                 bool SuppressUserConversions) {
3914  if (!CandidateSet.isNewCandidate(MethodTmpl))
3915    return;
3916
3917  // C++ [over.match.funcs]p7:
3918  //   In each case where a candidate is a function template, candidate
3919  //   function template specializations are generated using template argument
3920  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
3921  //   candidate functions in the usual way.113) A given name can refer to one
3922  //   or more function templates and also to a set of overloaded non-template
3923  //   functions. In such a case, the candidate functions generated from each
3924  //   function template are combined with the set of non-template candidate
3925  //   functions.
3926  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
3927  FunctionDecl *Specialization = 0;
3928  if (TemplateDeductionResult Result
3929      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
3930                                Args, NumArgs, Specialization, Info)) {
3931    CandidateSet.push_back(OverloadCandidate());
3932    OverloadCandidate &Candidate = CandidateSet.back();
3933    Candidate.FoundDecl = FoundDecl;
3934    Candidate.Function = MethodTmpl->getTemplatedDecl();
3935    Candidate.Viable = false;
3936    Candidate.FailureKind = ovl_fail_bad_deduction;
3937    Candidate.IsSurrogate = false;
3938    Candidate.IgnoreObjectArgument = false;
3939    Candidate.ExplicitCallArguments = NumArgs;
3940    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3941                                                          Info);
3942    return;
3943  }
3944
3945  // Add the function template specialization produced by template argument
3946  // deduction as a candidate.
3947  assert(Specialization && "Missing member function template specialization?");
3948  assert(isa<CXXMethodDecl>(Specialization) &&
3949         "Specialization is not a member function?");
3950  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
3951                     ActingContext, ObjectType, ObjectClassification,
3952                     Args, NumArgs, CandidateSet, SuppressUserConversions);
3953}
3954
3955/// \brief Add a C++ function template specialization as a candidate
3956/// in the candidate set, using template argument deduction to produce
3957/// an appropriate function template specialization.
3958void
3959Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
3960                                   DeclAccessPair FoundDecl,
3961                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
3962                                   Expr **Args, unsigned NumArgs,
3963                                   OverloadCandidateSet& CandidateSet,
3964                                   bool SuppressUserConversions) {
3965  if (!CandidateSet.isNewCandidate(FunctionTemplate))
3966    return;
3967
3968  // C++ [over.match.funcs]p7:
3969  //   In each case where a candidate is a function template, candidate
3970  //   function template specializations are generated using template argument
3971  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
3972  //   candidate functions in the usual way.113) A given name can refer to one
3973  //   or more function templates and also to a set of overloaded non-template
3974  //   functions. In such a case, the candidate functions generated from each
3975  //   function template are combined with the set of non-template candidate
3976  //   functions.
3977  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
3978  FunctionDecl *Specialization = 0;
3979  if (TemplateDeductionResult Result
3980        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
3981                                  Args, NumArgs, Specialization, Info)) {
3982    CandidateSet.push_back(OverloadCandidate());
3983    OverloadCandidate &Candidate = CandidateSet.back();
3984    Candidate.FoundDecl = FoundDecl;
3985    Candidate.Function = FunctionTemplate->getTemplatedDecl();
3986    Candidate.Viable = false;
3987    Candidate.FailureKind = ovl_fail_bad_deduction;
3988    Candidate.IsSurrogate = false;
3989    Candidate.IgnoreObjectArgument = false;
3990    Candidate.ExplicitCallArguments = NumArgs;
3991    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3992                                                          Info);
3993    return;
3994  }
3995
3996  // Add the function template specialization produced by template argument
3997  // deduction as a candidate.
3998  assert(Specialization && "Missing function template specialization?");
3999  AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
4000                       SuppressUserConversions);
4001}
4002
4003/// AddConversionCandidate - Add a C++ conversion function as a
4004/// candidate in the candidate set (C++ [over.match.conv],
4005/// C++ [over.match.copy]). From is the expression we're converting from,
4006/// and ToType is the type that we're eventually trying to convert to
4007/// (which may or may not be the same type as the type that the
4008/// conversion function produces).
4009void
4010Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
4011                             DeclAccessPair FoundDecl,
4012                             CXXRecordDecl *ActingContext,
4013                             Expr *From, QualType ToType,
4014                             OverloadCandidateSet& CandidateSet) {
4015  assert(!Conversion->getDescribedFunctionTemplate() &&
4016         "Conversion function templates use AddTemplateConversionCandidate");
4017  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
4018  if (!CandidateSet.isNewCandidate(Conversion))
4019    return;
4020
4021  // Overload resolution is always an unevaluated context.
4022  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4023
4024  // Add this candidate
4025  CandidateSet.push_back(OverloadCandidate());
4026  OverloadCandidate& Candidate = CandidateSet.back();
4027  Candidate.FoundDecl = FoundDecl;
4028  Candidate.Function = Conversion;
4029  Candidate.IsSurrogate = false;
4030  Candidate.IgnoreObjectArgument = false;
4031  Candidate.FinalConversion.setAsIdentityConversion();
4032  Candidate.FinalConversion.setFromType(ConvType);
4033  Candidate.FinalConversion.setAllToTypes(ToType);
4034  Candidate.Viable = true;
4035  Candidate.Conversions.resize(1);
4036  Candidate.ExplicitCallArguments = 1;
4037
4038  // C++ [over.match.funcs]p4:
4039  //   For conversion functions, the function is considered to be a member of
4040  //   the class of the implicit implied object argument for the purpose of
4041  //   defining the type of the implicit object parameter.
4042  //
4043  // Determine the implicit conversion sequence for the implicit
4044  // object parameter.
4045  QualType ImplicitParamType = From->getType();
4046  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4047    ImplicitParamType = FromPtrType->getPointeeType();
4048  CXXRecordDecl *ConversionContext
4049    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
4050
4051  Candidate.Conversions[0]
4052    = TryObjectArgumentInitialization(*this, From->getType(),
4053                                      From->Classify(Context),
4054                                      Conversion, ConversionContext);
4055
4056  if (Candidate.Conversions[0].isBad()) {
4057    Candidate.Viable = false;
4058    Candidate.FailureKind = ovl_fail_bad_conversion;
4059    return;
4060  }
4061
4062  // We won't go through a user-define type conversion function to convert a
4063  // derived to base as such conversions are given Conversion Rank. They only
4064  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4065  QualType FromCanon
4066    = Context.getCanonicalType(From->getType().getUnqualifiedType());
4067  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4068  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4069    Candidate.Viable = false;
4070    Candidate.FailureKind = ovl_fail_trivial_conversion;
4071    return;
4072  }
4073
4074  // To determine what the conversion from the result of calling the
4075  // conversion function to the type we're eventually trying to
4076  // convert to (ToType), we need to synthesize a call to the
4077  // conversion function and attempt copy initialization from it. This
4078  // makes sure that we get the right semantics with respect to
4079  // lvalues/rvalues and the type. Fortunately, we can allocate this
4080  // call on the stack and we don't need its arguments to be
4081  // well-formed.
4082  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
4083                            VK_LValue, From->getLocStart());
4084  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4085                                Context.getPointerType(Conversion->getType()),
4086                                CK_FunctionToPointerDecay,
4087                                &ConversionRef, VK_RValue);
4088
4089  QualType CallResultType
4090    = Conversion->getConversionType().getNonLValueExprType(Context);
4091  if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4092    Candidate.Viable = false;
4093    Candidate.FailureKind = ovl_fail_bad_final_conversion;
4094    return;
4095  }
4096
4097  ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4098
4099  // Note that it is safe to allocate CallExpr on the stack here because
4100  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4101  // allocator).
4102  CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
4103                From->getLocStart());
4104  ImplicitConversionSequence ICS =
4105    TryCopyInitialization(*this, &Call, ToType,
4106                          /*SuppressUserConversions=*/true,
4107                          /*InOverloadResolution=*/false);
4108
4109  switch (ICS.getKind()) {
4110  case ImplicitConversionSequence::StandardConversion:
4111    Candidate.FinalConversion = ICS.Standard;
4112
4113    // C++ [over.ics.user]p3:
4114    //   If the user-defined conversion is specified by a specialization of a
4115    //   conversion function template, the second standard conversion sequence
4116    //   shall have exact match rank.
4117    if (Conversion->getPrimaryTemplate() &&
4118        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4119      Candidate.Viable = false;
4120      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4121    }
4122
4123    // C++0x [dcl.init.ref]p5:
4124    //    In the second case, if the reference is an rvalue reference and
4125    //    the second standard conversion sequence of the user-defined
4126    //    conversion sequence includes an lvalue-to-rvalue conversion, the
4127    //    program is ill-formed.
4128    if (ToType->isRValueReferenceType() &&
4129        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4130      Candidate.Viable = false;
4131      Candidate.FailureKind = ovl_fail_bad_final_conversion;
4132    }
4133    break;
4134
4135  case ImplicitConversionSequence::BadConversion:
4136    Candidate.Viable = false;
4137    Candidate.FailureKind = ovl_fail_bad_final_conversion;
4138    break;
4139
4140  default:
4141    assert(false &&
4142           "Can only end up with a standard conversion sequence or failure");
4143  }
4144}
4145
4146/// \brief Adds a conversion function template specialization
4147/// candidate to the overload set, using template argument deduction
4148/// to deduce the template arguments of the conversion function
4149/// template from the type that we are converting to (C++
4150/// [temp.deduct.conv]).
4151void
4152Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
4153                                     DeclAccessPair FoundDecl,
4154                                     CXXRecordDecl *ActingDC,
4155                                     Expr *From, QualType ToType,
4156                                     OverloadCandidateSet &CandidateSet) {
4157  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4158         "Only conversion function templates permitted here");
4159
4160  if (!CandidateSet.isNewCandidate(FunctionTemplate))
4161    return;
4162
4163  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4164  CXXConversionDecl *Specialization = 0;
4165  if (TemplateDeductionResult Result
4166        = DeduceTemplateArguments(FunctionTemplate, ToType,
4167                                  Specialization, Info)) {
4168    CandidateSet.push_back(OverloadCandidate());
4169    OverloadCandidate &Candidate = CandidateSet.back();
4170    Candidate.FoundDecl = FoundDecl;
4171    Candidate.Function = FunctionTemplate->getTemplatedDecl();
4172    Candidate.Viable = false;
4173    Candidate.FailureKind = ovl_fail_bad_deduction;
4174    Candidate.IsSurrogate = false;
4175    Candidate.IgnoreObjectArgument = false;
4176    Candidate.ExplicitCallArguments = 1;
4177    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4178                                                          Info);
4179    return;
4180  }
4181
4182  // Add the conversion function template specialization produced by
4183  // template argument deduction as a candidate.
4184  assert(Specialization && "Missing function template specialization?");
4185  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
4186                         CandidateSet);
4187}
4188
4189/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4190/// converts the given @c Object to a function pointer via the
4191/// conversion function @c Conversion, and then attempts to call it
4192/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4193/// the type of function that we'll eventually be calling.
4194void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
4195                                 DeclAccessPair FoundDecl,
4196                                 CXXRecordDecl *ActingContext,
4197                                 const FunctionProtoType *Proto,
4198                                 Expr *Object,
4199                                 Expr **Args, unsigned NumArgs,
4200                                 OverloadCandidateSet& CandidateSet) {
4201  if (!CandidateSet.isNewCandidate(Conversion))
4202    return;
4203
4204  // Overload resolution is always an unevaluated context.
4205  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4206
4207  CandidateSet.push_back(OverloadCandidate());
4208  OverloadCandidate& Candidate = CandidateSet.back();
4209  Candidate.FoundDecl = FoundDecl;
4210  Candidate.Function = 0;
4211  Candidate.Surrogate = Conversion;
4212  Candidate.Viable = true;
4213  Candidate.IsSurrogate = true;
4214  Candidate.IgnoreObjectArgument = false;
4215  Candidate.Conversions.resize(NumArgs + 1);
4216  Candidate.ExplicitCallArguments = NumArgs;
4217
4218  // Determine the implicit conversion sequence for the implicit
4219  // object parameter.
4220  ImplicitConversionSequence ObjectInit
4221    = TryObjectArgumentInitialization(*this, Object->getType(),
4222                                      Object->Classify(Context),
4223                                      Conversion, ActingContext);
4224  if (ObjectInit.isBad()) {
4225    Candidate.Viable = false;
4226    Candidate.FailureKind = ovl_fail_bad_conversion;
4227    Candidate.Conversions[0] = ObjectInit;
4228    return;
4229  }
4230
4231  // The first conversion is actually a user-defined conversion whose
4232  // first conversion is ObjectInit's standard conversion (which is
4233  // effectively a reference binding). Record it as such.
4234  Candidate.Conversions[0].setUserDefined();
4235  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
4236  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
4237  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
4238  Candidate.Conversions[0].UserDefined.FoundConversionFunction
4239    = FoundDecl.getDecl();
4240  Candidate.Conversions[0].UserDefined.After
4241    = Candidate.Conversions[0].UserDefined.Before;
4242  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4243
4244  // Find the
4245  unsigned NumArgsInProto = Proto->getNumArgs();
4246
4247  // (C++ 13.3.2p2): A candidate function having fewer than m
4248  // parameters is viable only if it has an ellipsis in its parameter
4249  // list (8.3.5).
4250  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4251    Candidate.Viable = false;
4252    Candidate.FailureKind = ovl_fail_too_many_arguments;
4253    return;
4254  }
4255
4256  // Function types don't have any default arguments, so just check if
4257  // we have enough arguments.
4258  if (NumArgs < NumArgsInProto) {
4259    // Not enough arguments.
4260    Candidate.Viable = false;
4261    Candidate.FailureKind = ovl_fail_too_few_arguments;
4262    return;
4263  }
4264
4265  // Determine the implicit conversion sequences for each of the
4266  // arguments.
4267  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4268    if (ArgIdx < NumArgsInProto) {
4269      // (C++ 13.3.2p3): for F to be a viable function, there shall
4270      // exist for each argument an implicit conversion sequence
4271      // (13.3.3.1) that converts that argument to the corresponding
4272      // parameter of F.
4273      QualType ParamType = Proto->getArgType(ArgIdx);
4274      Candidate.Conversions[ArgIdx + 1]
4275        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
4276                                /*SuppressUserConversions=*/false,
4277                                /*InOverloadResolution=*/false);
4278      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
4279        Candidate.Viable = false;
4280        Candidate.FailureKind = ovl_fail_bad_conversion;
4281        break;
4282      }
4283    } else {
4284      // (C++ 13.3.2p2): For the purposes of overload resolution, any
4285      // argument for which there is no corresponding parameter is
4286      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
4287      Candidate.Conversions[ArgIdx + 1].setEllipsis();
4288    }
4289  }
4290}
4291
4292/// \brief Add overload candidates for overloaded operators that are
4293/// member functions.
4294///
4295/// Add the overloaded operator candidates that are member functions
4296/// for the operator Op that was used in an operator expression such
4297/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4298/// CandidateSet will store the added overload candidates. (C++
4299/// [over.match.oper]).
4300void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4301                                       SourceLocation OpLoc,
4302                                       Expr **Args, unsigned NumArgs,
4303                                       OverloadCandidateSet& CandidateSet,
4304                                       SourceRange OpRange) {
4305  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4306
4307  // C++ [over.match.oper]p3:
4308  //   For a unary operator @ with an operand of a type whose
4309  //   cv-unqualified version is T1, and for a binary operator @ with
4310  //   a left operand of a type whose cv-unqualified version is T1 and
4311  //   a right operand of a type whose cv-unqualified version is T2,
4312  //   three sets of candidate functions, designated member
4313  //   candidates, non-member candidates and built-in candidates, are
4314  //   constructed as follows:
4315  QualType T1 = Args[0]->getType();
4316
4317  //     -- If T1 is a class type, the set of member candidates is the
4318  //        result of the qualified lookup of T1::operator@
4319  //        (13.3.1.1.1); otherwise, the set of member candidates is
4320  //        empty.
4321  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
4322    // Complete the type if it can be completed. Otherwise, we're done.
4323    if (RequireCompleteType(OpLoc, T1, PDiag()))
4324      return;
4325
4326    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4327    LookupQualifiedName(Operators, T1Rec->getDecl());
4328    Operators.suppressDiagnostics();
4329
4330    for (LookupResult::iterator Oper = Operators.begin(),
4331                             OperEnd = Operators.end();
4332         Oper != OperEnd;
4333         ++Oper)
4334      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
4335                         Args[0]->Classify(Context), Args + 1, NumArgs - 1,
4336                         CandidateSet,
4337                         /* SuppressUserConversions = */ false);
4338  }
4339}
4340
4341/// AddBuiltinCandidate - Add a candidate for a built-in
4342/// operator. ResultTy and ParamTys are the result and parameter types
4343/// of the built-in candidate, respectively. Args and NumArgs are the
4344/// arguments being passed to the candidate. IsAssignmentOperator
4345/// should be true when this built-in candidate is an assignment
4346/// operator. NumContextualBoolArguments is the number of arguments
4347/// (at the beginning of the argument list) that will be contextually
4348/// converted to bool.
4349void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
4350                               Expr **Args, unsigned NumArgs,
4351                               OverloadCandidateSet& CandidateSet,
4352                               bool IsAssignmentOperator,
4353                               unsigned NumContextualBoolArguments) {
4354  // Overload resolution is always an unevaluated context.
4355  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4356
4357  // Add this candidate
4358  CandidateSet.push_back(OverloadCandidate());
4359  OverloadCandidate& Candidate = CandidateSet.back();
4360  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
4361  Candidate.Function = 0;
4362  Candidate.IsSurrogate = false;
4363  Candidate.IgnoreObjectArgument = false;
4364  Candidate.BuiltinTypes.ResultTy = ResultTy;
4365  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4366    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4367
4368  // Determine the implicit conversion sequences for each of the
4369  // arguments.
4370  Candidate.Viable = true;
4371  Candidate.Conversions.resize(NumArgs);
4372  Candidate.ExplicitCallArguments = NumArgs;
4373  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4374    // C++ [over.match.oper]p4:
4375    //   For the built-in assignment operators, conversions of the
4376    //   left operand are restricted as follows:
4377    //     -- no temporaries are introduced to hold the left operand, and
4378    //     -- no user-defined conversions are applied to the left
4379    //        operand to achieve a type match with the left-most
4380    //        parameter of a built-in candidate.
4381    //
4382    // We block these conversions by turning off user-defined
4383    // conversions, since that is the only way that initialization of
4384    // a reference to a non-class type can occur from something that
4385    // is not of the same type.
4386    if (ArgIdx < NumContextualBoolArguments) {
4387      assert(ParamTys[ArgIdx] == Context.BoolTy &&
4388             "Contextual conversion to bool requires bool type");
4389      Candidate.Conversions[ArgIdx]
4390        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
4391    } else {
4392      Candidate.Conversions[ArgIdx]
4393        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
4394                                ArgIdx == 0 && IsAssignmentOperator,
4395                                /*InOverloadResolution=*/false);
4396    }
4397    if (Candidate.Conversions[ArgIdx].isBad()) {
4398      Candidate.Viable = false;
4399      Candidate.FailureKind = ovl_fail_bad_conversion;
4400      break;
4401    }
4402  }
4403}
4404
4405/// BuiltinCandidateTypeSet - A set of types that will be used for the
4406/// candidate operator functions for built-in operators (C++
4407/// [over.built]). The types are separated into pointer types and
4408/// enumeration types.
4409class BuiltinCandidateTypeSet  {
4410  /// TypeSet - A set of types.
4411  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
4412
4413  /// PointerTypes - The set of pointer types that will be used in the
4414  /// built-in candidates.
4415  TypeSet PointerTypes;
4416
4417  /// MemberPointerTypes - The set of member pointer types that will be
4418  /// used in the built-in candidates.
4419  TypeSet MemberPointerTypes;
4420
4421  /// EnumerationTypes - The set of enumeration types that will be
4422  /// used in the built-in candidates.
4423  TypeSet EnumerationTypes;
4424
4425  /// \brief The set of vector types that will be used in the built-in
4426  /// candidates.
4427  TypeSet VectorTypes;
4428
4429  /// \brief A flag indicating non-record types are viable candidates
4430  bool HasNonRecordTypes;
4431
4432  /// \brief A flag indicating whether either arithmetic or enumeration types
4433  /// were present in the candidate set.
4434  bool HasArithmeticOrEnumeralTypes;
4435
4436  /// Sema - The semantic analysis instance where we are building the
4437  /// candidate type set.
4438  Sema &SemaRef;
4439
4440  /// Context - The AST context in which we will build the type sets.
4441  ASTContext &Context;
4442
4443  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4444                                               const Qualifiers &VisibleQuals);
4445  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
4446
4447public:
4448  /// iterator - Iterates through the types that are part of the set.
4449  typedef TypeSet::iterator iterator;
4450
4451  BuiltinCandidateTypeSet(Sema &SemaRef)
4452    : HasNonRecordTypes(false),
4453      HasArithmeticOrEnumeralTypes(false),
4454      SemaRef(SemaRef),
4455      Context(SemaRef.Context) { }
4456
4457  void AddTypesConvertedFrom(QualType Ty,
4458                             SourceLocation Loc,
4459                             bool AllowUserConversions,
4460                             bool AllowExplicitConversions,
4461                             const Qualifiers &VisibleTypeConversionsQuals);
4462
4463  /// pointer_begin - First pointer type found;
4464  iterator pointer_begin() { return PointerTypes.begin(); }
4465
4466  /// pointer_end - Past the last pointer type found;
4467  iterator pointer_end() { return PointerTypes.end(); }
4468
4469  /// member_pointer_begin - First member pointer type found;
4470  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4471
4472  /// member_pointer_end - Past the last member pointer type found;
4473  iterator member_pointer_end() { return MemberPointerTypes.end(); }
4474
4475  /// enumeration_begin - First enumeration type found;
4476  iterator enumeration_begin() { return EnumerationTypes.begin(); }
4477
4478  /// enumeration_end - Past the last enumeration type found;
4479  iterator enumeration_end() { return EnumerationTypes.end(); }
4480
4481  iterator vector_begin() { return VectorTypes.begin(); }
4482  iterator vector_end() { return VectorTypes.end(); }
4483
4484  bool hasNonRecordTypes() { return HasNonRecordTypes; }
4485  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
4486};
4487
4488/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
4489/// the set of pointer types along with any more-qualified variants of
4490/// that type. For example, if @p Ty is "int const *", this routine
4491/// will add "int const *", "int const volatile *", "int const
4492/// restrict *", and "int const volatile restrict *" to the set of
4493/// pointer types. Returns true if the add of @p Ty itself succeeded,
4494/// false otherwise.
4495///
4496/// FIXME: what to do about extended qualifiers?
4497bool
4498BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4499                                             const Qualifiers &VisibleQuals) {
4500
4501  // Insert this type.
4502  if (!PointerTypes.insert(Ty))
4503    return false;
4504
4505  QualType PointeeTy;
4506  const PointerType *PointerTy = Ty->getAs<PointerType>();
4507  bool buildObjCPtr = false;
4508  if (!PointerTy) {
4509    if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
4510      PointeeTy = PTy->getPointeeType();
4511      buildObjCPtr = true;
4512    }
4513    else
4514      assert(false && "type was not a pointer type!");
4515  }
4516  else
4517    PointeeTy = PointerTy->getPointeeType();
4518
4519  // Don't add qualified variants of arrays. For one, they're not allowed
4520  // (the qualifier would sink to the element type), and for another, the
4521  // only overload situation where it matters is subscript or pointer +- int,
4522  // and those shouldn't have qualifier variants anyway.
4523  if (PointeeTy->isArrayType())
4524    return true;
4525  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4526  if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
4527    BaseCVR = Array->getElementType().getCVRQualifiers();
4528  bool hasVolatile = VisibleQuals.hasVolatile();
4529  bool hasRestrict = VisibleQuals.hasRestrict();
4530
4531  // Iterate through all strict supersets of BaseCVR.
4532  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4533    if ((CVR | BaseCVR) != CVR) continue;
4534    // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4535    // in the types.
4536    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4537    if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
4538    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4539    if (!buildObjCPtr)
4540      PointerTypes.insert(Context.getPointerType(QPointeeTy));
4541    else
4542      PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
4543  }
4544
4545  return true;
4546}
4547
4548/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4549/// to the set of pointer types along with any more-qualified variants of
4550/// that type. For example, if @p Ty is "int const *", this routine
4551/// will add "int const *", "int const volatile *", "int const
4552/// restrict *", and "int const volatile restrict *" to the set of
4553/// pointer types. Returns true if the add of @p Ty itself succeeded,
4554/// false otherwise.
4555///
4556/// FIXME: what to do about extended qualifiers?
4557bool
4558BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4559    QualType Ty) {
4560  // Insert this type.
4561  if (!MemberPointerTypes.insert(Ty))
4562    return false;
4563
4564  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4565  assert(PointerTy && "type was not a member pointer type!");
4566
4567  QualType PointeeTy = PointerTy->getPointeeType();
4568  // Don't add qualified variants of arrays. For one, they're not allowed
4569  // (the qualifier would sink to the element type), and for another, the
4570  // only overload situation where it matters is subscript or pointer +- int,
4571  // and those shouldn't have qualifier variants anyway.
4572  if (PointeeTy->isArrayType())
4573    return true;
4574  const Type *ClassTy = PointerTy->getClass();
4575
4576  // Iterate through all strict supersets of the pointee type's CVR
4577  // qualifiers.
4578  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4579  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4580    if ((CVR | BaseCVR) != CVR) continue;
4581
4582    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4583    MemberPointerTypes.insert(
4584      Context.getMemberPointerType(QPointeeTy, ClassTy));
4585  }
4586
4587  return true;
4588}
4589
4590/// AddTypesConvertedFrom - Add each of the types to which the type @p
4591/// Ty can be implicit converted to the given set of @p Types. We're
4592/// primarily interested in pointer types and enumeration types. We also
4593/// take member pointer types, for the conditional operator.
4594/// AllowUserConversions is true if we should look at the conversion
4595/// functions of a class type, and AllowExplicitConversions if we
4596/// should also include the explicit conversion functions of a class
4597/// type.
4598void
4599BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
4600                                               SourceLocation Loc,
4601                                               bool AllowUserConversions,
4602                                               bool AllowExplicitConversions,
4603                                               const Qualifiers &VisibleQuals) {
4604  // Only deal with canonical types.
4605  Ty = Context.getCanonicalType(Ty);
4606
4607  // Look through reference types; they aren't part of the type of an
4608  // expression for the purposes of conversions.
4609  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
4610    Ty = RefTy->getPointeeType();
4611
4612  // If we're dealing with an array type, decay to the pointer.
4613  if (Ty->isArrayType())
4614    Ty = SemaRef.Context.getArrayDecayedType(Ty);
4615
4616  // Otherwise, we don't care about qualifiers on the type.
4617  Ty = Ty.getLocalUnqualifiedType();
4618
4619  // Flag if we ever add a non-record type.
4620  const RecordType *TyRec = Ty->getAs<RecordType>();
4621  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4622
4623  // Flag if we encounter an arithmetic type.
4624  HasArithmeticOrEnumeralTypes =
4625    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4626
4627  if (Ty->isObjCIdType() || Ty->isObjCClassType())
4628    PointerTypes.insert(Ty);
4629  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
4630    // Insert our type, and its more-qualified variants, into the set
4631    // of types.
4632    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
4633      return;
4634  } else if (Ty->isMemberPointerType()) {
4635    // Member pointers are far easier, since the pointee can't be converted.
4636    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4637      return;
4638  } else if (Ty->isEnumeralType()) {
4639    HasArithmeticOrEnumeralTypes = true;
4640    EnumerationTypes.insert(Ty);
4641  } else if (Ty->isVectorType()) {
4642    // We treat vector types as arithmetic types in many contexts as an
4643    // extension.
4644    HasArithmeticOrEnumeralTypes = true;
4645    VectorTypes.insert(Ty);
4646  } else if (AllowUserConversions && TyRec) {
4647    // No conversion functions in incomplete types.
4648    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4649      return;
4650
4651    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4652    const UnresolvedSetImpl *Conversions
4653      = ClassDecl->getVisibleConversionFunctions();
4654    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4655           E = Conversions->end(); I != E; ++I) {
4656      NamedDecl *D = I.getDecl();
4657      if (isa<UsingShadowDecl>(D))
4658        D = cast<UsingShadowDecl>(D)->getTargetDecl();
4659
4660      // Skip conversion function templates; they don't tell us anything
4661      // about which builtin types we can convert to.
4662      if (isa<FunctionTemplateDecl>(D))
4663        continue;
4664
4665      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4666      if (AllowExplicitConversions || !Conv->isExplicit()) {
4667        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4668                              VisibleQuals);
4669      }
4670    }
4671  }
4672}
4673
4674/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4675/// the volatile- and non-volatile-qualified assignment operators for the
4676/// given type to the candidate set.
4677static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4678                                                   QualType T,
4679                                                   Expr **Args,
4680                                                   unsigned NumArgs,
4681                                    OverloadCandidateSet &CandidateSet) {
4682  QualType ParamTypes[2];
4683
4684  // T& operator=(T&, T)
4685  ParamTypes[0] = S.Context.getLValueReferenceType(T);
4686  ParamTypes[1] = T;
4687  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4688                        /*IsAssignmentOperator=*/true);
4689
4690  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4691    // volatile T& operator=(volatile T&, T)
4692    ParamTypes[0]
4693      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
4694    ParamTypes[1] = T;
4695    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4696                          /*IsAssignmentOperator=*/true);
4697  }
4698}
4699
4700/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4701/// if any, found in visible type conversion functions found in ArgExpr's type.
4702static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4703    Qualifiers VRQuals;
4704    const RecordType *TyRec;
4705    if (const MemberPointerType *RHSMPType =
4706        ArgExpr->getType()->getAs<MemberPointerType>())
4707      TyRec = RHSMPType->getClass()->getAs<RecordType>();
4708    else
4709      TyRec = ArgExpr->getType()->getAs<RecordType>();
4710    if (!TyRec) {
4711      // Just to be safe, assume the worst case.
4712      VRQuals.addVolatile();
4713      VRQuals.addRestrict();
4714      return VRQuals;
4715    }
4716
4717    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4718    if (!ClassDecl->hasDefinition())
4719      return VRQuals;
4720
4721    const UnresolvedSetImpl *Conversions =
4722      ClassDecl->getVisibleConversionFunctions();
4723
4724    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4725           E = Conversions->end(); I != E; ++I) {
4726      NamedDecl *D = I.getDecl();
4727      if (isa<UsingShadowDecl>(D))
4728        D = cast<UsingShadowDecl>(D)->getTargetDecl();
4729      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
4730        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4731        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4732          CanTy = ResTypeRef->getPointeeType();
4733        // Need to go down the pointer/mempointer chain and add qualifiers
4734        // as see them.
4735        bool done = false;
4736        while (!done) {
4737          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4738            CanTy = ResTypePtr->getPointeeType();
4739          else if (const MemberPointerType *ResTypeMPtr =
4740                CanTy->getAs<MemberPointerType>())
4741            CanTy = ResTypeMPtr->getPointeeType();
4742          else
4743            done = true;
4744          if (CanTy.isVolatileQualified())
4745            VRQuals.addVolatile();
4746          if (CanTy.isRestrictQualified())
4747            VRQuals.addRestrict();
4748          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4749            return VRQuals;
4750        }
4751      }
4752    }
4753    return VRQuals;
4754}
4755
4756namespace {
4757
4758/// \brief Helper class to manage the addition of builtin operator overload
4759/// candidates. It provides shared state and utility methods used throughout
4760/// the process, as well as a helper method to add each group of builtin
4761/// operator overloads from the standard to a candidate set.
4762class BuiltinOperatorOverloadBuilder {
4763  // Common instance state available to all overload candidate addition methods.
4764  Sema &S;
4765  Expr **Args;
4766  unsigned NumArgs;
4767  Qualifiers VisibleTypeConversionsQuals;
4768  bool HasArithmeticOrEnumeralCandidateType;
4769  llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4770  OverloadCandidateSet &CandidateSet;
4771
4772  // Define some constants used to index and iterate over the arithemetic types
4773  // provided via the getArithmeticType() method below.
4774  // The "promoted arithmetic types" are the arithmetic
4775  // types are that preserved by promotion (C++ [over.built]p2).
4776  static const unsigned FirstIntegralType = 3;
4777  static const unsigned LastIntegralType = 18;
4778  static const unsigned FirstPromotedIntegralType = 3,
4779                        LastPromotedIntegralType = 9;
4780  static const unsigned FirstPromotedArithmeticType = 0,
4781                        LastPromotedArithmeticType = 9;
4782  static const unsigned NumArithmeticTypes = 18;
4783
4784  /// \brief Get the canonical type for a given arithmetic type index.
4785  CanQualType getArithmeticType(unsigned index) {
4786    assert(index < NumArithmeticTypes);
4787    static CanQualType ASTContext::* const
4788      ArithmeticTypes[NumArithmeticTypes] = {
4789      // Start of promoted types.
4790      &ASTContext::FloatTy,
4791      &ASTContext::DoubleTy,
4792      &ASTContext::LongDoubleTy,
4793
4794      // Start of integral types.
4795      &ASTContext::IntTy,
4796      &ASTContext::LongTy,
4797      &ASTContext::LongLongTy,
4798      &ASTContext::UnsignedIntTy,
4799      &ASTContext::UnsignedLongTy,
4800      &ASTContext::UnsignedLongLongTy,
4801      // End of promoted types.
4802
4803      &ASTContext::BoolTy,
4804      &ASTContext::CharTy,
4805      &ASTContext::WCharTy,
4806      &ASTContext::Char16Ty,
4807      &ASTContext::Char32Ty,
4808      &ASTContext::SignedCharTy,
4809      &ASTContext::ShortTy,
4810      &ASTContext::UnsignedCharTy,
4811      &ASTContext::UnsignedShortTy,
4812      // End of integral types.
4813      // FIXME: What about complex?
4814    };
4815    return S.Context.*ArithmeticTypes[index];
4816  }
4817
4818  /// \brief Gets the canonical type resulting from the usual arithemetic
4819  /// converions for the given arithmetic types.
4820  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4821    // Accelerator table for performing the usual arithmetic conversions.
4822    // The rules are basically:
4823    //   - if either is floating-point, use the wider floating-point
4824    //   - if same signedness, use the higher rank
4825    //   - if same size, use unsigned of the higher rank
4826    //   - use the larger type
4827    // These rules, together with the axiom that higher ranks are
4828    // never smaller, are sufficient to precompute all of these results
4829    // *except* when dealing with signed types of higher rank.
4830    // (we could precompute SLL x UI for all known platforms, but it's
4831    // better not to make any assumptions).
4832    enum PromotedType {
4833                  Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL, Dep=-1
4834    };
4835    static PromotedType ConversionsTable[LastPromotedArithmeticType]
4836                                        [LastPromotedArithmeticType] = {
4837      /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
4838      /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
4839      /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4840      /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL },
4841      /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL,  Dep,   UL,  ULL },
4842      /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL,  Dep,  Dep,  ULL },
4843      /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep,   UI,   UL,  ULL },
4844      /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep,   UL,   UL,  ULL },
4845      /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL,  ULL,  ULL,  ULL },
4846    };
4847
4848    assert(L < LastPromotedArithmeticType);
4849    assert(R < LastPromotedArithmeticType);
4850    int Idx = ConversionsTable[L][R];
4851
4852    // Fast path: the table gives us a concrete answer.
4853    if (Idx != Dep) return getArithmeticType(Idx);
4854
4855    // Slow path: we need to compare widths.
4856    // An invariant is that the signed type has higher rank.
4857    CanQualType LT = getArithmeticType(L),
4858                RT = getArithmeticType(R);
4859    unsigned LW = S.Context.getIntWidth(LT),
4860             RW = S.Context.getIntWidth(RT);
4861
4862    // If they're different widths, use the signed type.
4863    if (LW > RW) return LT;
4864    else if (LW < RW) return RT;
4865
4866    // Otherwise, use the unsigned type of the signed type's rank.
4867    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
4868    assert(L == SLL || R == SLL);
4869    return S.Context.UnsignedLongLongTy;
4870  }
4871
4872  /// \brief Helper method to factor out the common pattern of adding overloads
4873  /// for '++' and '--' builtin operators.
4874  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
4875                                           bool HasVolatile) {
4876    QualType ParamTypes[2] = {
4877      S.Context.getLValueReferenceType(CandidateTy),
4878      S.Context.IntTy
4879    };
4880
4881    // Non-volatile version.
4882    if (NumArgs == 1)
4883      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4884    else
4885      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4886
4887    // Use a heuristic to reduce number of builtin candidates in the set:
4888    // add volatile version only if there are conversions to a volatile type.
4889    if (HasVolatile) {
4890      ParamTypes[0] =
4891        S.Context.getLValueReferenceType(
4892          S.Context.getVolatileType(CandidateTy));
4893      if (NumArgs == 1)
4894        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4895      else
4896        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4897    }
4898  }
4899
4900public:
4901  BuiltinOperatorOverloadBuilder(
4902    Sema &S, Expr **Args, unsigned NumArgs,
4903    Qualifiers VisibleTypeConversionsQuals,
4904    bool HasArithmeticOrEnumeralCandidateType,
4905    llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
4906    OverloadCandidateSet &CandidateSet)
4907    : S(S), Args(Args), NumArgs(NumArgs),
4908      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
4909      HasArithmeticOrEnumeralCandidateType(
4910        HasArithmeticOrEnumeralCandidateType),
4911      CandidateTypes(CandidateTypes),
4912      CandidateSet(CandidateSet) {
4913    // Validate some of our static helper constants in debug builds.
4914    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
4915           "Invalid first promoted integral type");
4916    assert(getArithmeticType(LastPromotedIntegralType - 1)
4917             == S.Context.UnsignedLongLongTy &&
4918           "Invalid last promoted integral type");
4919    assert(getArithmeticType(FirstPromotedArithmeticType)
4920             == S.Context.FloatTy &&
4921           "Invalid first promoted arithmetic type");
4922    assert(getArithmeticType(LastPromotedArithmeticType - 1)
4923             == S.Context.UnsignedLongLongTy &&
4924           "Invalid last promoted arithmetic type");
4925  }
4926
4927  // C++ [over.built]p3:
4928  //
4929  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
4930  //   is either volatile or empty, there exist candidate operator
4931  //   functions of the form
4932  //
4933  //       VQ T&      operator++(VQ T&);
4934  //       T          operator++(VQ T&, int);
4935  //
4936  // C++ [over.built]p4:
4937  //
4938  //   For every pair (T, VQ), where T is an arithmetic type other
4939  //   than bool, and VQ is either volatile or empty, there exist
4940  //   candidate operator functions of the form
4941  //
4942  //       VQ T&      operator--(VQ T&);
4943  //       T          operator--(VQ T&, int);
4944  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
4945    if (!HasArithmeticOrEnumeralCandidateType)
4946      return;
4947
4948    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4949         Arith < NumArithmeticTypes; ++Arith) {
4950      addPlusPlusMinusMinusStyleOverloads(
4951        getArithmeticType(Arith),
4952        VisibleTypeConversionsQuals.hasVolatile());
4953    }
4954  }
4955
4956  // C++ [over.built]p5:
4957  //
4958  //   For every pair (T, VQ), where T is a cv-qualified or
4959  //   cv-unqualified object type, and VQ is either volatile or
4960  //   empty, there exist candidate operator functions of the form
4961  //
4962  //       T*VQ&      operator++(T*VQ&);
4963  //       T*VQ&      operator--(T*VQ&);
4964  //       T*         operator++(T*VQ&, int);
4965  //       T*         operator--(T*VQ&, int);
4966  void addPlusPlusMinusMinusPointerOverloads() {
4967    for (BuiltinCandidateTypeSet::iterator
4968              Ptr = CandidateTypes[0].pointer_begin(),
4969           PtrEnd = CandidateTypes[0].pointer_end();
4970         Ptr != PtrEnd; ++Ptr) {
4971      // Skip pointer types that aren't pointers to object types.
4972      if (!(*Ptr)->getPointeeType()->isObjectType())
4973        continue;
4974
4975      addPlusPlusMinusMinusStyleOverloads(*Ptr,
4976        (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4977         VisibleTypeConversionsQuals.hasVolatile()));
4978    }
4979  }
4980
4981  // C++ [over.built]p6:
4982  //   For every cv-qualified or cv-unqualified object type T, there
4983  //   exist candidate operator functions of the form
4984  //
4985  //       T&         operator*(T*);
4986  //
4987  // C++ [over.built]p7:
4988  //   For every function type T that does not have cv-qualifiers or a
4989  //   ref-qualifier, there exist candidate operator functions of the form
4990  //       T&         operator*(T*);
4991  void addUnaryStarPointerOverloads() {
4992    for (BuiltinCandidateTypeSet::iterator
4993              Ptr = CandidateTypes[0].pointer_begin(),
4994           PtrEnd = CandidateTypes[0].pointer_end();
4995         Ptr != PtrEnd; ++Ptr) {
4996      QualType ParamTy = *Ptr;
4997      QualType PointeeTy = ParamTy->getPointeeType();
4998      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
4999        continue;
5000
5001      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5002        if (Proto->getTypeQuals() || Proto->getRefQualifier())
5003          continue;
5004
5005      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5006                            &ParamTy, Args, 1, CandidateSet);
5007    }
5008  }
5009
5010  // C++ [over.built]p9:
5011  //  For every promoted arithmetic type T, there exist candidate
5012  //  operator functions of the form
5013  //
5014  //       T         operator+(T);
5015  //       T         operator-(T);
5016  void addUnaryPlusOrMinusArithmeticOverloads() {
5017    if (!HasArithmeticOrEnumeralCandidateType)
5018      return;
5019
5020    for (unsigned Arith = FirstPromotedArithmeticType;
5021         Arith < LastPromotedArithmeticType; ++Arith) {
5022      QualType ArithTy = getArithmeticType(Arith);
5023      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5024    }
5025
5026    // Extension: We also add these operators for vector types.
5027    for (BuiltinCandidateTypeSet::iterator
5028              Vec = CandidateTypes[0].vector_begin(),
5029           VecEnd = CandidateTypes[0].vector_end();
5030         Vec != VecEnd; ++Vec) {
5031      QualType VecTy = *Vec;
5032      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5033    }
5034  }
5035
5036  // C++ [over.built]p8:
5037  //   For every type T, there exist candidate operator functions of
5038  //   the form
5039  //
5040  //       T*         operator+(T*);
5041  void addUnaryPlusPointerOverloads() {
5042    for (BuiltinCandidateTypeSet::iterator
5043              Ptr = CandidateTypes[0].pointer_begin(),
5044           PtrEnd = CandidateTypes[0].pointer_end();
5045         Ptr != PtrEnd; ++Ptr) {
5046      QualType ParamTy = *Ptr;
5047      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5048    }
5049  }
5050
5051  // C++ [over.built]p10:
5052  //   For every promoted integral type T, there exist candidate
5053  //   operator functions of the form
5054  //
5055  //        T         operator~(T);
5056  void addUnaryTildePromotedIntegralOverloads() {
5057    if (!HasArithmeticOrEnumeralCandidateType)
5058      return;
5059
5060    for (unsigned Int = FirstPromotedIntegralType;
5061         Int < LastPromotedIntegralType; ++Int) {
5062      QualType IntTy = getArithmeticType(Int);
5063      S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5064    }
5065
5066    // Extension: We also add this operator for vector types.
5067    for (BuiltinCandidateTypeSet::iterator
5068              Vec = CandidateTypes[0].vector_begin(),
5069           VecEnd = CandidateTypes[0].vector_end();
5070         Vec != VecEnd; ++Vec) {
5071      QualType VecTy = *Vec;
5072      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5073    }
5074  }
5075
5076  // C++ [over.match.oper]p16:
5077  //   For every pointer to member type T, there exist candidate operator
5078  //   functions of the form
5079  //
5080  //        bool operator==(T,T);
5081  //        bool operator!=(T,T);
5082  void addEqualEqualOrNotEqualMemberPointerOverloads() {
5083    /// Set of (canonical) types that we've already handled.
5084    llvm::SmallPtrSet<QualType, 8> AddedTypes;
5085
5086    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5087      for (BuiltinCandidateTypeSet::iterator
5088                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5089             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5090           MemPtr != MemPtrEnd;
5091           ++MemPtr) {
5092        // Don't add the same builtin candidate twice.
5093        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5094          continue;
5095
5096        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5097        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5098                              CandidateSet);
5099      }
5100    }
5101  }
5102
5103  // C++ [over.built]p15:
5104  //
5105  //   For every pointer or enumeration type T, there exist
5106  //   candidate operator functions of the form
5107  //
5108  //        bool       operator<(T, T);
5109  //        bool       operator>(T, T);
5110  //        bool       operator<=(T, T);
5111  //        bool       operator>=(T, T);
5112  //        bool       operator==(T, T);
5113  //        bool       operator!=(T, T);
5114  void addRelationalPointerOrEnumeralOverloads() {
5115    // C++ [over.built]p1:
5116    //   If there is a user-written candidate with the same name and parameter
5117    //   types as a built-in candidate operator function, the built-in operator
5118    //   function is hidden and is not included in the set of candidate
5119    //   functions.
5120    //
5121    // The text is actually in a note, but if we don't implement it then we end
5122    // up with ambiguities when the user provides an overloaded operator for
5123    // an enumeration type. Note that only enumeration types have this problem,
5124    // so we track which enumeration types we've seen operators for. Also, the
5125    // only other overloaded operator with enumeration argumenst, operator=,
5126    // cannot be overloaded for enumeration types, so this is the only place
5127    // where we must suppress candidates like this.
5128    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5129      UserDefinedBinaryOperators;
5130
5131    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5132      if (CandidateTypes[ArgIdx].enumeration_begin() !=
5133          CandidateTypes[ArgIdx].enumeration_end()) {
5134        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5135                                         CEnd = CandidateSet.end();
5136             C != CEnd; ++C) {
5137          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5138            continue;
5139
5140          QualType FirstParamType =
5141            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5142          QualType SecondParamType =
5143            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5144
5145          // Skip if either parameter isn't of enumeral type.
5146          if (!FirstParamType->isEnumeralType() ||
5147              !SecondParamType->isEnumeralType())
5148            continue;
5149
5150          // Add this operator to the set of known user-defined operators.
5151          UserDefinedBinaryOperators.insert(
5152            std::make_pair(S.Context.getCanonicalType(FirstParamType),
5153                           S.Context.getCanonicalType(SecondParamType)));
5154        }
5155      }
5156    }
5157
5158    /// Set of (canonical) types that we've already handled.
5159    llvm::SmallPtrSet<QualType, 8> AddedTypes;
5160
5161    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5162      for (BuiltinCandidateTypeSet::iterator
5163                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5164             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5165           Ptr != PtrEnd; ++Ptr) {
5166        // Don't add the same builtin candidate twice.
5167        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5168          continue;
5169
5170        QualType ParamTypes[2] = { *Ptr, *Ptr };
5171        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5172                              CandidateSet);
5173      }
5174      for (BuiltinCandidateTypeSet::iterator
5175                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5176             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5177           Enum != EnumEnd; ++Enum) {
5178        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5179
5180        // Don't add the same builtin candidate twice, or if a user defined
5181        // candidate exists.
5182        if (!AddedTypes.insert(CanonType) ||
5183            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5184                                                            CanonType)))
5185          continue;
5186
5187        QualType ParamTypes[2] = { *Enum, *Enum };
5188        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5189                              CandidateSet);
5190      }
5191    }
5192  }
5193
5194  // C++ [over.built]p13:
5195  //
5196  //   For every cv-qualified or cv-unqualified object type T
5197  //   there exist candidate operator functions of the form
5198  //
5199  //      T*         operator+(T*, ptrdiff_t);
5200  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
5201  //      T*         operator-(T*, ptrdiff_t);
5202  //      T*         operator+(ptrdiff_t, T*);
5203  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
5204  //
5205  // C++ [over.built]p14:
5206  //
5207  //   For every T, where T is a pointer to object type, there
5208  //   exist candidate operator functions of the form
5209  //
5210  //      ptrdiff_t  operator-(T, T);
5211  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5212    /// Set of (canonical) types that we've already handled.
5213    llvm::SmallPtrSet<QualType, 8> AddedTypes;
5214
5215    for (int Arg = 0; Arg < 2; ++Arg) {
5216      QualType AsymetricParamTypes[2] = {
5217        S.Context.getPointerDiffType(),
5218        S.Context.getPointerDiffType(),
5219      };
5220      for (BuiltinCandidateTypeSet::iterator
5221                Ptr = CandidateTypes[Arg].pointer_begin(),
5222             PtrEnd = CandidateTypes[Arg].pointer_end();
5223           Ptr != PtrEnd; ++Ptr) {
5224        QualType PointeeTy = (*Ptr)->getPointeeType();
5225        if (!PointeeTy->isObjectType())
5226          continue;
5227
5228        AsymetricParamTypes[Arg] = *Ptr;
5229        if (Arg == 0 || Op == OO_Plus) {
5230          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5231          // T* operator+(ptrdiff_t, T*);
5232          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5233                                CandidateSet);
5234        }
5235        if (Op == OO_Minus) {
5236          // ptrdiff_t operator-(T, T);
5237          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5238            continue;
5239
5240          QualType ParamTypes[2] = { *Ptr, *Ptr };
5241          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5242                                Args, 2, CandidateSet);
5243        }
5244      }
5245    }
5246  }
5247
5248  // C++ [over.built]p12:
5249  //
5250  //   For every pair of promoted arithmetic types L and R, there
5251  //   exist candidate operator functions of the form
5252  //
5253  //        LR         operator*(L, R);
5254  //        LR         operator/(L, R);
5255  //        LR         operator+(L, R);
5256  //        LR         operator-(L, R);
5257  //        bool       operator<(L, R);
5258  //        bool       operator>(L, R);
5259  //        bool       operator<=(L, R);
5260  //        bool       operator>=(L, R);
5261  //        bool       operator==(L, R);
5262  //        bool       operator!=(L, R);
5263  //
5264  //   where LR is the result of the usual arithmetic conversions
5265  //   between types L and R.
5266  //
5267  // C++ [over.built]p24:
5268  //
5269  //   For every pair of promoted arithmetic types L and R, there exist
5270  //   candidate operator functions of the form
5271  //
5272  //        LR       operator?(bool, L, R);
5273  //
5274  //   where LR is the result of the usual arithmetic conversions
5275  //   between types L and R.
5276  // Our candidates ignore the first parameter.
5277  void addGenericBinaryArithmeticOverloads(bool isComparison) {
5278    if (!HasArithmeticOrEnumeralCandidateType)
5279      return;
5280
5281    for (unsigned Left = FirstPromotedArithmeticType;
5282         Left < LastPromotedArithmeticType; ++Left) {
5283      for (unsigned Right = FirstPromotedArithmeticType;
5284           Right < LastPromotedArithmeticType; ++Right) {
5285        QualType LandR[2] = { getArithmeticType(Left),
5286                              getArithmeticType(Right) };
5287        QualType Result =
5288          isComparison ? S.Context.BoolTy
5289                       : getUsualArithmeticConversions(Left, Right);
5290        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5291      }
5292    }
5293
5294    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5295    // conditional operator for vector types.
5296    for (BuiltinCandidateTypeSet::iterator
5297              Vec1 = CandidateTypes[0].vector_begin(),
5298           Vec1End = CandidateTypes[0].vector_end();
5299         Vec1 != Vec1End; ++Vec1) {
5300      for (BuiltinCandidateTypeSet::iterator
5301                Vec2 = CandidateTypes[1].vector_begin(),
5302             Vec2End = CandidateTypes[1].vector_end();
5303           Vec2 != Vec2End; ++Vec2) {
5304        QualType LandR[2] = { *Vec1, *Vec2 };
5305        QualType Result = S.Context.BoolTy;
5306        if (!isComparison) {
5307          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5308            Result = *Vec1;
5309          else
5310            Result = *Vec2;
5311        }
5312
5313        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5314      }
5315    }
5316  }
5317
5318  // C++ [over.built]p17:
5319  //
5320  //   For every pair of promoted integral types L and R, there
5321  //   exist candidate operator functions of the form
5322  //
5323  //      LR         operator%(L, R);
5324  //      LR         operator&(L, R);
5325  //      LR         operator^(L, R);
5326  //      LR         operator|(L, R);
5327  //      L          operator<<(L, R);
5328  //      L          operator>>(L, R);
5329  //
5330  //   where LR is the result of the usual arithmetic conversions
5331  //   between types L and R.
5332  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
5333    if (!HasArithmeticOrEnumeralCandidateType)
5334      return;
5335
5336    for (unsigned Left = FirstPromotedIntegralType;
5337         Left < LastPromotedIntegralType; ++Left) {
5338      for (unsigned Right = FirstPromotedIntegralType;
5339           Right < LastPromotedIntegralType; ++Right) {
5340        QualType LandR[2] = { getArithmeticType(Left),
5341                              getArithmeticType(Right) };
5342        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5343            ? LandR[0]
5344            : getUsualArithmeticConversions(Left, Right);
5345        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5346      }
5347    }
5348  }
5349
5350  // C++ [over.built]p20:
5351  //
5352  //   For every pair (T, VQ), where T is an enumeration or
5353  //   pointer to member type and VQ is either volatile or
5354  //   empty, there exist candidate operator functions of the form
5355  //
5356  //        VQ T&      operator=(VQ T&, T);
5357  void addAssignmentMemberPointerOrEnumeralOverloads() {
5358    /// Set of (canonical) types that we've already handled.
5359    llvm::SmallPtrSet<QualType, 8> AddedTypes;
5360
5361    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5362      for (BuiltinCandidateTypeSet::iterator
5363                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5364             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5365           Enum != EnumEnd; ++Enum) {
5366        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5367          continue;
5368
5369        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5370                                               CandidateSet);
5371      }
5372
5373      for (BuiltinCandidateTypeSet::iterator
5374                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5375             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5376           MemPtr != MemPtrEnd; ++MemPtr) {
5377        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5378          continue;
5379
5380        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5381                                               CandidateSet);
5382      }
5383    }
5384  }
5385
5386  // C++ [over.built]p19:
5387  //
5388  //   For every pair (T, VQ), where T is any type and VQ is either
5389  //   volatile or empty, there exist candidate operator functions
5390  //   of the form
5391  //
5392  //        T*VQ&      operator=(T*VQ&, T*);
5393  //
5394  // C++ [over.built]p21:
5395  //
5396  //   For every pair (T, VQ), where T is a cv-qualified or
5397  //   cv-unqualified object type and VQ is either volatile or
5398  //   empty, there exist candidate operator functions of the form
5399  //
5400  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
5401  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
5402  void addAssignmentPointerOverloads(bool isEqualOp) {
5403    /// Set of (canonical) types that we've already handled.
5404    llvm::SmallPtrSet<QualType, 8> AddedTypes;
5405
5406    for (BuiltinCandidateTypeSet::iterator
5407              Ptr = CandidateTypes[0].pointer_begin(),
5408           PtrEnd = CandidateTypes[0].pointer_end();
5409         Ptr != PtrEnd; ++Ptr) {
5410      // If this is operator=, keep track of the builtin candidates we added.
5411      if (isEqualOp)
5412        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
5413      else if (!(*Ptr)->getPointeeType()->isObjectType())
5414        continue;
5415
5416      // non-volatile version
5417      QualType ParamTypes[2] = {
5418        S.Context.getLValueReferenceType(*Ptr),
5419        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5420      };
5421      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5422                            /*IsAssigmentOperator=*/ isEqualOp);
5423
5424      if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5425          VisibleTypeConversionsQuals.hasVolatile()) {
5426        // volatile version
5427        ParamTypes[0] =
5428          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5429        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5430                              /*IsAssigmentOperator=*/isEqualOp);
5431      }
5432    }
5433
5434    if (isEqualOp) {
5435      for (BuiltinCandidateTypeSet::iterator
5436                Ptr = CandidateTypes[1].pointer_begin(),
5437             PtrEnd = CandidateTypes[1].pointer_end();
5438           Ptr != PtrEnd; ++Ptr) {
5439        // Make sure we don't add the same candidate twice.
5440        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5441          continue;
5442
5443        QualType ParamTypes[2] = {
5444          S.Context.getLValueReferenceType(*Ptr),
5445          *Ptr,
5446        };
5447
5448        // non-volatile version
5449        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5450                              /*IsAssigmentOperator=*/true);
5451
5452        if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5453            VisibleTypeConversionsQuals.hasVolatile()) {
5454          // volatile version
5455          ParamTypes[0] =
5456            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5457          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5458                                CandidateSet, /*IsAssigmentOperator=*/true);
5459        }
5460      }
5461    }
5462  }
5463
5464  // C++ [over.built]p18:
5465  //
5466  //   For every triple (L, VQ, R), where L is an arithmetic type,
5467  //   VQ is either volatile or empty, and R is a promoted
5468  //   arithmetic type, there exist candidate operator functions of
5469  //   the form
5470  //
5471  //        VQ L&      operator=(VQ L&, R);
5472  //        VQ L&      operator*=(VQ L&, R);
5473  //        VQ L&      operator/=(VQ L&, R);
5474  //        VQ L&      operator+=(VQ L&, R);
5475  //        VQ L&      operator-=(VQ L&, R);
5476  void addAssignmentArithmeticOverloads(bool isEqualOp) {
5477    if (!HasArithmeticOrEnumeralCandidateType)
5478      return;
5479
5480    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5481      for (unsigned Right = FirstPromotedArithmeticType;
5482           Right < LastPromotedArithmeticType; ++Right) {
5483        QualType ParamTypes[2];
5484        ParamTypes[1] = getArithmeticType(Right);
5485
5486        // Add this built-in operator as a candidate (VQ is empty).
5487        ParamTypes[0] =
5488          S.Context.getLValueReferenceType(getArithmeticType(Left));
5489        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5490                              /*IsAssigmentOperator=*/isEqualOp);
5491
5492        // Add this built-in operator as a candidate (VQ is 'volatile').
5493        if (VisibleTypeConversionsQuals.hasVolatile()) {
5494          ParamTypes[0] =
5495            S.Context.getVolatileType(getArithmeticType(Left));
5496          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5497          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5498                                CandidateSet,
5499                                /*IsAssigmentOperator=*/isEqualOp);
5500        }
5501      }
5502    }
5503
5504    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5505    for (BuiltinCandidateTypeSet::iterator
5506              Vec1 = CandidateTypes[0].vector_begin(),
5507           Vec1End = CandidateTypes[0].vector_end();
5508         Vec1 != Vec1End; ++Vec1) {
5509      for (BuiltinCandidateTypeSet::iterator
5510                Vec2 = CandidateTypes[1].vector_begin(),
5511             Vec2End = CandidateTypes[1].vector_end();
5512           Vec2 != Vec2End; ++Vec2) {
5513        QualType ParamTypes[2];
5514        ParamTypes[1] = *Vec2;
5515        // Add this built-in operator as a candidate (VQ is empty).
5516        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5517        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5518                              /*IsAssigmentOperator=*/isEqualOp);
5519
5520        // Add this built-in operator as a candidate (VQ is 'volatile').
5521        if (VisibleTypeConversionsQuals.hasVolatile()) {
5522          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5523          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5524          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5525                                CandidateSet,
5526                                /*IsAssigmentOperator=*/isEqualOp);
5527        }
5528      }
5529    }
5530  }
5531
5532  // C++ [over.built]p22:
5533  //
5534  //   For every triple (L, VQ, R), where L is an integral type, VQ
5535  //   is either volatile or empty, and R is a promoted integral
5536  //   type, there exist candidate operator functions of the form
5537  //
5538  //        VQ L&       operator%=(VQ L&, R);
5539  //        VQ L&       operator<<=(VQ L&, R);
5540  //        VQ L&       operator>>=(VQ L&, R);
5541  //        VQ L&       operator&=(VQ L&, R);
5542  //        VQ L&       operator^=(VQ L&, R);
5543  //        VQ L&       operator|=(VQ L&, R);
5544  void addAssignmentIntegralOverloads() {
5545    if (!HasArithmeticOrEnumeralCandidateType)
5546      return;
5547
5548    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5549      for (unsigned Right = FirstPromotedIntegralType;
5550           Right < LastPromotedIntegralType; ++Right) {
5551        QualType ParamTypes[2];
5552        ParamTypes[1] = getArithmeticType(Right);
5553
5554        // Add this built-in operator as a candidate (VQ is empty).
5555        ParamTypes[0] =
5556          S.Context.getLValueReferenceType(getArithmeticType(Left));
5557        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5558        if (VisibleTypeConversionsQuals.hasVolatile()) {
5559          // Add this built-in operator as a candidate (VQ is 'volatile').
5560          ParamTypes[0] = getArithmeticType(Left);
5561          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5562          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5563          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5564                                CandidateSet);
5565        }
5566      }
5567    }
5568  }
5569
5570  // C++ [over.operator]p23:
5571  //
5572  //   There also exist candidate operator functions of the form
5573  //
5574  //        bool        operator!(bool);
5575  //        bool        operator&&(bool, bool);
5576  //        bool        operator||(bool, bool);
5577  void addExclaimOverload() {
5578    QualType ParamTy = S.Context.BoolTy;
5579    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5580                          /*IsAssignmentOperator=*/false,
5581                          /*NumContextualBoolArguments=*/1);
5582  }
5583  void addAmpAmpOrPipePipeOverload() {
5584    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5585    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5586                          /*IsAssignmentOperator=*/false,
5587                          /*NumContextualBoolArguments=*/2);
5588  }
5589
5590  // C++ [over.built]p13:
5591  //
5592  //   For every cv-qualified or cv-unqualified object type T there
5593  //   exist candidate operator functions of the form
5594  //
5595  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
5596  //        T&         operator[](T*, ptrdiff_t);
5597  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
5598  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
5599  //        T&         operator[](ptrdiff_t, T*);
5600  void addSubscriptOverloads() {
5601    for (BuiltinCandidateTypeSet::iterator
5602              Ptr = CandidateTypes[0].pointer_begin(),
5603           PtrEnd = CandidateTypes[0].pointer_end();
5604         Ptr != PtrEnd; ++Ptr) {
5605      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5606      QualType PointeeType = (*Ptr)->getPointeeType();
5607      if (!PointeeType->isObjectType())
5608        continue;
5609
5610      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5611
5612      // T& operator[](T*, ptrdiff_t)
5613      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5614    }
5615
5616    for (BuiltinCandidateTypeSet::iterator
5617              Ptr = CandidateTypes[1].pointer_begin(),
5618           PtrEnd = CandidateTypes[1].pointer_end();
5619         Ptr != PtrEnd; ++Ptr) {
5620      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5621      QualType PointeeType = (*Ptr)->getPointeeType();
5622      if (!PointeeType->isObjectType())
5623        continue;
5624
5625      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5626
5627      // T& operator[](ptrdiff_t, T*)
5628      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5629    }
5630  }
5631
5632  // C++ [over.built]p11:
5633  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5634  //    C1 is the same type as C2 or is a derived class of C2, T is an object
5635  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5636  //    there exist candidate operator functions of the form
5637  //
5638  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5639  //
5640  //    where CV12 is the union of CV1 and CV2.
5641  void addArrowStarOverloads() {
5642    for (BuiltinCandidateTypeSet::iterator
5643             Ptr = CandidateTypes[0].pointer_begin(),
5644           PtrEnd = CandidateTypes[0].pointer_end();
5645         Ptr != PtrEnd; ++Ptr) {
5646      QualType C1Ty = (*Ptr);
5647      QualType C1;
5648      QualifierCollector Q1;
5649      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5650      if (!isa<RecordType>(C1))
5651        continue;
5652      // heuristic to reduce number of builtin candidates in the set.
5653      // Add volatile/restrict version only if there are conversions to a
5654      // volatile/restrict type.
5655      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5656        continue;
5657      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5658        continue;
5659      for (BuiltinCandidateTypeSet::iterator
5660                MemPtr = CandidateTypes[1].member_pointer_begin(),
5661             MemPtrEnd = CandidateTypes[1].member_pointer_end();
5662           MemPtr != MemPtrEnd; ++MemPtr) {
5663        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5664        QualType C2 = QualType(mptr->getClass(), 0);
5665        C2 = C2.getUnqualifiedType();
5666        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5667          break;
5668        QualType ParamTypes[2] = { *Ptr, *MemPtr };
5669        // build CV12 T&
5670        QualType T = mptr->getPointeeType();
5671        if (!VisibleTypeConversionsQuals.hasVolatile() &&
5672            T.isVolatileQualified())
5673          continue;
5674        if (!VisibleTypeConversionsQuals.hasRestrict() &&
5675            T.isRestrictQualified())
5676          continue;
5677        T = Q1.apply(S.Context, T);
5678        QualType ResultTy = S.Context.getLValueReferenceType(T);
5679        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5680      }
5681    }
5682  }
5683
5684  // Note that we don't consider the first argument, since it has been
5685  // contextually converted to bool long ago. The candidates below are
5686  // therefore added as binary.
5687  //
5688  // C++ [over.built]p25:
5689  //   For every type T, where T is a pointer, pointer-to-member, or scoped
5690  //   enumeration type, there exist candidate operator functions of the form
5691  //
5692  //        T        operator?(bool, T, T);
5693  //
5694  void addConditionalOperatorOverloads() {
5695    /// Set of (canonical) types that we've already handled.
5696    llvm::SmallPtrSet<QualType, 8> AddedTypes;
5697
5698    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5699      for (BuiltinCandidateTypeSet::iterator
5700                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5701             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5702           Ptr != PtrEnd; ++Ptr) {
5703        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5704          continue;
5705
5706        QualType ParamTypes[2] = { *Ptr, *Ptr };
5707        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5708      }
5709
5710      for (BuiltinCandidateTypeSet::iterator
5711                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5712             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5713           MemPtr != MemPtrEnd; ++MemPtr) {
5714        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5715          continue;
5716
5717        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5718        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5719      }
5720
5721      if (S.getLangOptions().CPlusPlus0x) {
5722        for (BuiltinCandidateTypeSet::iterator
5723                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5724               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5725             Enum != EnumEnd; ++Enum) {
5726          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5727            continue;
5728
5729          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5730            continue;
5731
5732          QualType ParamTypes[2] = { *Enum, *Enum };
5733          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5734        }
5735      }
5736    }
5737  }
5738};
5739
5740} // end anonymous namespace
5741
5742/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5743/// operator overloads to the candidate set (C++ [over.built]), based
5744/// on the operator @p Op and the arguments given. For example, if the
5745/// operator is a binary '+', this routine might add "int
5746/// operator+(int, int)" to cover integer addition.
5747void
5748Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5749                                   SourceLocation OpLoc,
5750                                   Expr **Args, unsigned NumArgs,
5751                                   OverloadCandidateSet& CandidateSet) {
5752  // Find all of the types that the arguments can convert to, but only
5753  // if the operator we're looking at has built-in operator candidates
5754  // that make use of these types. Also record whether we encounter non-record
5755  // candidate types or either arithmetic or enumeral candidate types.
5756  Qualifiers VisibleTypeConversionsQuals;
5757  VisibleTypeConversionsQuals.addConst();
5758  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5759    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
5760
5761  bool HasNonRecordCandidateType = false;
5762  bool HasArithmeticOrEnumeralCandidateType = false;
5763  llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5764  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5765    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5766    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5767                                                 OpLoc,
5768                                                 true,
5769                                                 (Op == OO_Exclaim ||
5770                                                  Op == OO_AmpAmp ||
5771                                                  Op == OO_PipePipe),
5772                                                 VisibleTypeConversionsQuals);
5773    HasNonRecordCandidateType = HasNonRecordCandidateType ||
5774        CandidateTypes[ArgIdx].hasNonRecordTypes();
5775    HasArithmeticOrEnumeralCandidateType =
5776        HasArithmeticOrEnumeralCandidateType ||
5777        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
5778  }
5779
5780  // Exit early when no non-record types have been added to the candidate set
5781  // for any of the arguments to the operator.
5782  if (!HasNonRecordCandidateType)
5783    return;
5784
5785  // Setup an object to manage the common state for building overloads.
5786  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5787                                           VisibleTypeConversionsQuals,
5788                                           HasArithmeticOrEnumeralCandidateType,
5789                                           CandidateTypes, CandidateSet);
5790
5791  // Dispatch over the operation to add in only those overloads which apply.
5792  switch (Op) {
5793  case OO_None:
5794  case NUM_OVERLOADED_OPERATORS:
5795    assert(false && "Expected an overloaded operator");
5796    break;
5797
5798  case OO_New:
5799  case OO_Delete:
5800  case OO_Array_New:
5801  case OO_Array_Delete:
5802  case OO_Call:
5803    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5804    break;
5805
5806  case OO_Comma:
5807  case OO_Arrow:
5808    // C++ [over.match.oper]p3:
5809    //   -- For the operator ',', the unary operator '&', or the
5810    //      operator '->', the built-in candidates set is empty.
5811    break;
5812
5813  case OO_Plus: // '+' is either unary or binary
5814    if (NumArgs == 1)
5815      OpBuilder.addUnaryPlusPointerOverloads();
5816    // Fall through.
5817
5818  case OO_Minus: // '-' is either unary or binary
5819    if (NumArgs == 1) {
5820      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
5821    } else {
5822      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5823      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5824    }
5825    break;
5826
5827  case OO_Star: // '*' is either unary or binary
5828    if (NumArgs == 1)
5829      OpBuilder.addUnaryStarPointerOverloads();
5830    else
5831      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5832    break;
5833
5834  case OO_Slash:
5835    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5836    break;
5837
5838  case OO_PlusPlus:
5839  case OO_MinusMinus:
5840    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5841    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
5842    break;
5843
5844  case OO_EqualEqual:
5845  case OO_ExclaimEqual:
5846    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
5847    // Fall through.
5848
5849  case OO_Less:
5850  case OO_Greater:
5851  case OO_LessEqual:
5852  case OO_GreaterEqual:
5853    OpBuilder.addRelationalPointerOrEnumeralOverloads();
5854    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
5855    break;
5856
5857  case OO_Percent:
5858  case OO_Caret:
5859  case OO_Pipe:
5860  case OO_LessLess:
5861  case OO_GreaterGreater:
5862    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5863    break;
5864
5865  case OO_Amp: // '&' is either unary or binary
5866    if (NumArgs == 1)
5867      // C++ [over.match.oper]p3:
5868      //   -- For the operator ',', the unary operator '&', or the
5869      //      operator '->', the built-in candidates set is empty.
5870      break;
5871
5872    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5873    break;
5874
5875  case OO_Tilde:
5876    OpBuilder.addUnaryTildePromotedIntegralOverloads();
5877    break;
5878
5879  case OO_Equal:
5880    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
5881    // Fall through.
5882
5883  case OO_PlusEqual:
5884  case OO_MinusEqual:
5885    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
5886    // Fall through.
5887
5888  case OO_StarEqual:
5889  case OO_SlashEqual:
5890    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
5891    break;
5892
5893  case OO_PercentEqual:
5894  case OO_LessLessEqual:
5895  case OO_GreaterGreaterEqual:
5896  case OO_AmpEqual:
5897  case OO_CaretEqual:
5898  case OO_PipeEqual:
5899    OpBuilder.addAssignmentIntegralOverloads();
5900    break;
5901
5902  case OO_Exclaim:
5903    OpBuilder.addExclaimOverload();
5904    break;
5905
5906  case OO_AmpAmp:
5907  case OO_PipePipe:
5908    OpBuilder.addAmpAmpOrPipePipeOverload();
5909    break;
5910
5911  case OO_Subscript:
5912    OpBuilder.addSubscriptOverloads();
5913    break;
5914
5915  case OO_ArrowStar:
5916    OpBuilder.addArrowStarOverloads();
5917    break;
5918
5919  case OO_Conditional:
5920    OpBuilder.addConditionalOperatorOverloads();
5921    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5922    break;
5923  }
5924}
5925
5926/// \brief Add function candidates found via argument-dependent lookup
5927/// to the set of overloading candidates.
5928///
5929/// This routine performs argument-dependent name lookup based on the
5930/// given function name (which may also be an operator name) and adds
5931/// all of the overload candidates found by ADL to the overload
5932/// candidate set (C++ [basic.lookup.argdep]).
5933void
5934Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
5935                                           bool Operator,
5936                                           Expr **Args, unsigned NumArgs,
5937                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
5938                                           OverloadCandidateSet& CandidateSet,
5939                                           bool PartialOverloading) {
5940  ADLResult Fns;
5941
5942  // FIXME: This approach for uniquing ADL results (and removing
5943  // redundant candidates from the set) relies on pointer-equality,
5944  // which means we need to key off the canonical decl.  However,
5945  // always going back to the canonical decl might not get us the
5946  // right set of default arguments.  What default arguments are
5947  // we supposed to consider on ADL candidates, anyway?
5948
5949  // FIXME: Pass in the explicit template arguments?
5950  ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
5951
5952  // Erase all of the candidates we already knew about.
5953  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5954                                   CandEnd = CandidateSet.end();
5955       Cand != CandEnd; ++Cand)
5956    if (Cand->Function) {
5957      Fns.erase(Cand->Function);
5958      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
5959        Fns.erase(FunTmpl);
5960    }
5961
5962  // For each of the ADL candidates we found, add it to the overload
5963  // set.
5964  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
5965    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
5966    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
5967      if (ExplicitTemplateArgs)
5968        continue;
5969
5970      AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
5971                           false, PartialOverloading);
5972    } else
5973      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
5974                                   FoundDecl, ExplicitTemplateArgs,
5975                                   Args, NumArgs, CandidateSet);
5976  }
5977}
5978
5979/// isBetterOverloadCandidate - Determines whether the first overload
5980/// candidate is a better candidate than the second (C++ 13.3.3p1).
5981bool
5982isBetterOverloadCandidate(Sema &S,
5983                          const OverloadCandidate &Cand1,
5984                          const OverloadCandidate &Cand2,
5985                          SourceLocation Loc,
5986                          bool UserDefinedConversion) {
5987  // Define viable functions to be better candidates than non-viable
5988  // functions.
5989  if (!Cand2.Viable)
5990    return Cand1.Viable;
5991  else if (!Cand1.Viable)
5992    return false;
5993
5994  // C++ [over.match.best]p1:
5995  //
5996  //   -- if F is a static member function, ICS1(F) is defined such
5997  //      that ICS1(F) is neither better nor worse than ICS1(G) for
5998  //      any function G, and, symmetrically, ICS1(G) is neither
5999  //      better nor worse than ICS1(F).
6000  unsigned StartArg = 0;
6001  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6002    StartArg = 1;
6003
6004  // C++ [over.match.best]p1:
6005  //   A viable function F1 is defined to be a better function than another
6006  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
6007  //   conversion sequence than ICSi(F2), and then...
6008  unsigned NumArgs = Cand1.Conversions.size();
6009  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6010  bool HasBetterConversion = false;
6011  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
6012    switch (CompareImplicitConversionSequences(S,
6013                                               Cand1.Conversions[ArgIdx],
6014                                               Cand2.Conversions[ArgIdx])) {
6015    case ImplicitConversionSequence::Better:
6016      // Cand1 has a better conversion sequence.
6017      HasBetterConversion = true;
6018      break;
6019
6020    case ImplicitConversionSequence::Worse:
6021      // Cand1 can't be better than Cand2.
6022      return false;
6023
6024    case ImplicitConversionSequence::Indistinguishable:
6025      // Do nothing.
6026      break;
6027    }
6028  }
6029
6030  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
6031  //       ICSj(F2), or, if not that,
6032  if (HasBetterConversion)
6033    return true;
6034
6035  //     - F1 is a non-template function and F2 is a function template
6036  //       specialization, or, if not that,
6037  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
6038      Cand2.Function && Cand2.Function->getPrimaryTemplate())
6039    return true;
6040
6041  //   -- F1 and F2 are function template specializations, and the function
6042  //      template for F1 is more specialized than the template for F2
6043  //      according to the partial ordering rules described in 14.5.5.2, or,
6044  //      if not that,
6045  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
6046      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
6047    if (FunctionTemplateDecl *BetterTemplate
6048          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6049                                         Cand2.Function->getPrimaryTemplate(),
6050                                         Loc,
6051                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
6052                                                             : TPOC_Call,
6053                                         Cand1.ExplicitCallArguments))
6054      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
6055  }
6056
6057  //   -- the context is an initialization by user-defined conversion
6058  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
6059  //      from the return type of F1 to the destination type (i.e.,
6060  //      the type of the entity being initialized) is a better
6061  //      conversion sequence than the standard conversion sequence
6062  //      from the return type of F2 to the destination type.
6063  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
6064      isa<CXXConversionDecl>(Cand1.Function) &&
6065      isa<CXXConversionDecl>(Cand2.Function)) {
6066    switch (CompareStandardConversionSequences(S,
6067                                               Cand1.FinalConversion,
6068                                               Cand2.FinalConversion)) {
6069    case ImplicitConversionSequence::Better:
6070      // Cand1 has a better conversion sequence.
6071      return true;
6072
6073    case ImplicitConversionSequence::Worse:
6074      // Cand1 can't be better than Cand2.
6075      return false;
6076
6077    case ImplicitConversionSequence::Indistinguishable:
6078      // Do nothing
6079      break;
6080    }
6081  }
6082
6083  return false;
6084}
6085
6086/// \brief Computes the best viable function (C++ 13.3.3)
6087/// within an overload candidate set.
6088///
6089/// \param CandidateSet the set of candidate functions.
6090///
6091/// \param Loc the location of the function name (or operator symbol) for
6092/// which overload resolution occurs.
6093///
6094/// \param Best f overload resolution was successful or found a deleted
6095/// function, Best points to the candidate function found.
6096///
6097/// \returns The result of overload resolution.
6098OverloadingResult
6099OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
6100                                         iterator &Best,
6101                                         bool UserDefinedConversion) {
6102  // Find the best viable function.
6103  Best = end();
6104  for (iterator Cand = begin(); Cand != end(); ++Cand) {
6105    if (Cand->Viable)
6106      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
6107                                                     UserDefinedConversion))
6108        Best = Cand;
6109  }
6110
6111  // If we didn't find any viable functions, abort.
6112  if (Best == end())
6113    return OR_No_Viable_Function;
6114
6115  // Make sure that this function is better than every other viable
6116  // function. If not, we have an ambiguity.
6117  for (iterator Cand = begin(); Cand != end(); ++Cand) {
6118    if (Cand->Viable &&
6119        Cand != Best &&
6120        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
6121                                   UserDefinedConversion)) {
6122      Best = end();
6123      return OR_Ambiguous;
6124    }
6125  }
6126
6127  // Best is the best viable function.
6128  if (Best->Function &&
6129      (Best->Function->isDeleted() ||
6130       Best->Function->getAttr<UnavailableAttr>()))
6131    return OR_Deleted;
6132
6133  // C++ [basic.def.odr]p2:
6134  //   An overloaded function is used if it is selected by overload resolution
6135  //   when referred to from a potentially-evaluated expression. [Note: this
6136  //   covers calls to named functions (5.2.2), operator overloading
6137  //   (clause 13), user-defined conversions (12.3.2), allocation function for
6138  //   placement new (5.3.4), as well as non-default initialization (8.5).
6139  if (Best->Function)
6140    S.MarkDeclarationReferenced(Loc, Best->Function);
6141
6142  return OR_Success;
6143}
6144
6145namespace {
6146
6147enum OverloadCandidateKind {
6148  oc_function,
6149  oc_method,
6150  oc_constructor,
6151  oc_function_template,
6152  oc_method_template,
6153  oc_constructor_template,
6154  oc_implicit_default_constructor,
6155  oc_implicit_copy_constructor,
6156  oc_implicit_copy_assignment
6157};
6158
6159OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6160                                                FunctionDecl *Fn,
6161                                                std::string &Description) {
6162  bool isTemplate = false;
6163
6164  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6165    isTemplate = true;
6166    Description = S.getTemplateArgumentBindingsText(
6167      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6168  }
6169
6170  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
6171    if (!Ctor->isImplicit())
6172      return isTemplate ? oc_constructor_template : oc_constructor;
6173
6174    return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6175                                     : oc_implicit_default_constructor;
6176  }
6177
6178  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6179    // This actually gets spelled 'candidate function' for now, but
6180    // it doesn't hurt to split it out.
6181    if (!Meth->isImplicit())
6182      return isTemplate ? oc_method_template : oc_method;
6183
6184    assert(Meth->isCopyAssignmentOperator()
6185           && "implicit method is not copy assignment operator?");
6186    return oc_implicit_copy_assignment;
6187  }
6188
6189  return isTemplate ? oc_function_template : oc_function;
6190}
6191
6192} // end anonymous namespace
6193
6194// Notes the location of an overload candidate.
6195void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
6196  std::string FnDesc;
6197  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6198  Diag(Fn->getLocation(), diag::note_ovl_candidate)
6199    << (unsigned) K << FnDesc;
6200}
6201
6202/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
6203/// "lead" diagnostic; it will be given two arguments, the source and
6204/// target types of the conversion.
6205void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6206                                 Sema &S,
6207                                 SourceLocation CaretLoc,
6208                                 const PartialDiagnostic &PDiag) const {
6209  S.Diag(CaretLoc, PDiag)
6210    << Ambiguous.getFromType() << Ambiguous.getToType();
6211  for (AmbiguousConversionSequence::const_iterator
6212         I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6213    S.NoteOverloadCandidate(*I);
6214  }
6215}
6216
6217namespace {
6218
6219void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6220  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6221  assert(Conv.isBad());
6222  assert(Cand->Function && "for now, candidate must be a function");
6223  FunctionDecl *Fn = Cand->Function;
6224
6225  // There's a conversion slot for the object argument if this is a
6226  // non-constructor method.  Note that 'I' corresponds the
6227  // conversion-slot index.
6228  bool isObjectArgument = false;
6229  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
6230    if (I == 0)
6231      isObjectArgument = true;
6232    else
6233      I--;
6234  }
6235
6236  std::string FnDesc;
6237  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6238
6239  Expr *FromExpr = Conv.Bad.FromExpr;
6240  QualType FromTy = Conv.Bad.getFromType();
6241  QualType ToTy = Conv.Bad.getToType();
6242
6243  if (FromTy == S.Context.OverloadTy) {
6244    assert(FromExpr && "overload set argument came from implicit argument?");
6245    Expr *E = FromExpr->IgnoreParens();
6246    if (isa<UnaryOperator>(E))
6247      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
6248    DeclarationName Name = cast<OverloadExpr>(E)->getName();
6249
6250    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6251      << (unsigned) FnKind << FnDesc
6252      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6253      << ToTy << Name << I+1;
6254    return;
6255  }
6256
6257  // Do some hand-waving analysis to see if the non-viability is due
6258  // to a qualifier mismatch.
6259  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6260  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6261  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6262    CToTy = RT->getPointeeType();
6263  else {
6264    // TODO: detect and diagnose the full richness of const mismatches.
6265    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6266      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6267        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6268  }
6269
6270  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6271      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6272    // It is dumb that we have to do this here.
6273    while (isa<ArrayType>(CFromTy))
6274      CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6275    while (isa<ArrayType>(CToTy))
6276      CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6277
6278    Qualifiers FromQs = CFromTy.getQualifiers();
6279    Qualifiers ToQs = CToTy.getQualifiers();
6280
6281    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6282      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6283        << (unsigned) FnKind << FnDesc
6284        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6285        << FromTy
6286        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6287        << (unsigned) isObjectArgument << I+1;
6288      return;
6289    }
6290
6291    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6292    assert(CVR && "unexpected qualifiers mismatch");
6293
6294    if (isObjectArgument) {
6295      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6296        << (unsigned) FnKind << FnDesc
6297        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6298        << FromTy << (CVR - 1);
6299    } else {
6300      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6301        << (unsigned) FnKind << FnDesc
6302        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6303        << FromTy << (CVR - 1) << I+1;
6304    }
6305    return;
6306  }
6307
6308  // Diagnose references or pointers to incomplete types differently,
6309  // since it's far from impossible that the incompleteness triggered
6310  // the failure.
6311  QualType TempFromTy = FromTy.getNonReferenceType();
6312  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6313    TempFromTy = PTy->getPointeeType();
6314  if (TempFromTy->isIncompleteType()) {
6315    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6316      << (unsigned) FnKind << FnDesc
6317      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6318      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6319    return;
6320  }
6321
6322  // Diagnose base -> derived pointer conversions.
6323  unsigned BaseToDerivedConversion = 0;
6324  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6325    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6326      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6327                                               FromPtrTy->getPointeeType()) &&
6328          !FromPtrTy->getPointeeType()->isIncompleteType() &&
6329          !ToPtrTy->getPointeeType()->isIncompleteType() &&
6330          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6331                          FromPtrTy->getPointeeType()))
6332        BaseToDerivedConversion = 1;
6333    }
6334  } else if (const ObjCObjectPointerType *FromPtrTy
6335                                    = FromTy->getAs<ObjCObjectPointerType>()) {
6336    if (const ObjCObjectPointerType *ToPtrTy
6337                                        = ToTy->getAs<ObjCObjectPointerType>())
6338      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6339        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6340          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6341                                                FromPtrTy->getPointeeType()) &&
6342              FromIface->isSuperClassOf(ToIface))
6343            BaseToDerivedConversion = 2;
6344  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6345      if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6346          !FromTy->isIncompleteType() &&
6347          !ToRefTy->getPointeeType()->isIncompleteType() &&
6348          S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6349        BaseToDerivedConversion = 3;
6350    }
6351
6352  if (BaseToDerivedConversion) {
6353    S.Diag(Fn->getLocation(),
6354           diag::note_ovl_candidate_bad_base_to_derived_conv)
6355      << (unsigned) FnKind << FnDesc
6356      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6357      << (BaseToDerivedConversion - 1)
6358      << FromTy << ToTy << I+1;
6359    return;
6360  }
6361
6362  // TODO: specialize more based on the kind of mismatch
6363  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6364    << (unsigned) FnKind << FnDesc
6365    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6366    << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6367}
6368
6369void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6370                           unsigned NumFormalArgs) {
6371  // TODO: treat calls to a missing default constructor as a special case
6372
6373  FunctionDecl *Fn = Cand->Function;
6374  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6375
6376  unsigned MinParams = Fn->getMinRequiredArguments();
6377
6378  // at least / at most / exactly
6379  unsigned mode, modeCount;
6380  if (NumFormalArgs < MinParams) {
6381    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6382           (Cand->FailureKind == ovl_fail_bad_deduction &&
6383            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
6384    if (MinParams != FnTy->getNumArgs() ||
6385        FnTy->isVariadic() || FnTy->isTemplateVariadic())
6386      mode = 0; // "at least"
6387    else
6388      mode = 2; // "exactly"
6389    modeCount = MinParams;
6390  } else {
6391    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6392           (Cand->FailureKind == ovl_fail_bad_deduction &&
6393            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
6394    if (MinParams != FnTy->getNumArgs())
6395      mode = 1; // "at most"
6396    else
6397      mode = 2; // "exactly"
6398    modeCount = FnTy->getNumArgs();
6399  }
6400
6401  std::string Description;
6402  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6403
6404  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
6405    << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6406    << modeCount << NumFormalArgs;
6407}
6408
6409/// Diagnose a failed template-argument deduction.
6410void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6411                          Expr **Args, unsigned NumArgs) {
6412  FunctionDecl *Fn = Cand->Function; // pattern
6413
6414  TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
6415  NamedDecl *ParamD;
6416  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6417  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6418  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
6419  switch (Cand->DeductionFailure.Result) {
6420  case Sema::TDK_Success:
6421    llvm_unreachable("TDK_success while diagnosing bad deduction");
6422
6423  case Sema::TDK_Incomplete: {
6424    assert(ParamD && "no parameter found for incomplete deduction result");
6425    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6426      << ParamD->getDeclName();
6427    return;
6428  }
6429
6430  case Sema::TDK_Underqualified: {
6431    assert(ParamD && "no parameter found for bad qualifiers deduction result");
6432    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6433
6434    QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6435
6436    // Param will have been canonicalized, but it should just be a
6437    // qualified version of ParamD, so move the qualifiers to that.
6438    QualifierCollector Qs;
6439    Qs.strip(Param);
6440    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
6441    assert(S.Context.hasSameType(Param, NonCanonParam));
6442
6443    // Arg has also been canonicalized, but there's nothing we can do
6444    // about that.  It also doesn't matter as much, because it won't
6445    // have any template parameters in it (because deduction isn't
6446    // done on dependent types).
6447    QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6448
6449    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6450      << ParamD->getDeclName() << Arg << NonCanonParam;
6451    return;
6452  }
6453
6454  case Sema::TDK_Inconsistent: {
6455    assert(ParamD && "no parameter found for inconsistent deduction result");
6456    int which = 0;
6457    if (isa<TemplateTypeParmDecl>(ParamD))
6458      which = 0;
6459    else if (isa<NonTypeTemplateParmDecl>(ParamD))
6460      which = 1;
6461    else {
6462      which = 2;
6463    }
6464
6465    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6466      << which << ParamD->getDeclName()
6467      << *Cand->DeductionFailure.getFirstArg()
6468      << *Cand->DeductionFailure.getSecondArg();
6469    return;
6470  }
6471
6472  case Sema::TDK_InvalidExplicitArguments:
6473    assert(ParamD && "no parameter found for invalid explicit arguments");
6474    if (ParamD->getDeclName())
6475      S.Diag(Fn->getLocation(),
6476             diag::note_ovl_candidate_explicit_arg_mismatch_named)
6477        << ParamD->getDeclName();
6478    else {
6479      int index = 0;
6480      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6481        index = TTP->getIndex();
6482      else if (NonTypeTemplateParmDecl *NTTP
6483                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6484        index = NTTP->getIndex();
6485      else
6486        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6487      S.Diag(Fn->getLocation(),
6488             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6489        << (index + 1);
6490    }
6491    return;
6492
6493  case Sema::TDK_TooManyArguments:
6494  case Sema::TDK_TooFewArguments:
6495    DiagnoseArityMismatch(S, Cand, NumArgs);
6496    return;
6497
6498  case Sema::TDK_InstantiationDepth:
6499    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6500    return;
6501
6502  case Sema::TDK_SubstitutionFailure: {
6503    std::string ArgString;
6504    if (TemplateArgumentList *Args
6505                            = Cand->DeductionFailure.getTemplateArgumentList())
6506      ArgString = S.getTemplateArgumentBindingsText(
6507                    Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6508                                                    *Args);
6509    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6510      << ArgString;
6511    return;
6512  }
6513
6514  // TODO: diagnose these individually, then kill off
6515  // note_ovl_candidate_bad_deduction, which is uselessly vague.
6516  case Sema::TDK_NonDeducedMismatch:
6517  case Sema::TDK_FailedOverloadResolution:
6518    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6519    return;
6520  }
6521}
6522
6523/// Generates a 'note' diagnostic for an overload candidate.  We've
6524/// already generated a primary error at the call site.
6525///
6526/// It really does need to be a single diagnostic with its caret
6527/// pointed at the candidate declaration.  Yes, this creates some
6528/// major challenges of technical writing.  Yes, this makes pointing
6529/// out problems with specific arguments quite awkward.  It's still
6530/// better than generating twenty screens of text for every failed
6531/// overload.
6532///
6533/// It would be great to be able to express per-candidate problems
6534/// more richly for those diagnostic clients that cared, but we'd
6535/// still have to be just as careful with the default diagnostics.
6536void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6537                           Expr **Args, unsigned NumArgs) {
6538  FunctionDecl *Fn = Cand->Function;
6539
6540  // Note deleted candidates, but only if they're viable.
6541  if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
6542    std::string FnDesc;
6543    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6544
6545    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
6546      << FnKind << FnDesc << Fn->isDeleted();
6547    return;
6548  }
6549
6550  // We don't really have anything else to say about viable candidates.
6551  if (Cand->Viable) {
6552    S.NoteOverloadCandidate(Fn);
6553    return;
6554  }
6555
6556  switch (Cand->FailureKind) {
6557  case ovl_fail_too_many_arguments:
6558  case ovl_fail_too_few_arguments:
6559    return DiagnoseArityMismatch(S, Cand, NumArgs);
6560
6561  case ovl_fail_bad_deduction:
6562    return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6563
6564  case ovl_fail_trivial_conversion:
6565  case ovl_fail_bad_final_conversion:
6566  case ovl_fail_final_conversion_not_exact:
6567    return S.NoteOverloadCandidate(Fn);
6568
6569  case ovl_fail_bad_conversion: {
6570    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6571    for (unsigned N = Cand->Conversions.size(); I != N; ++I)
6572      if (Cand->Conversions[I].isBad())
6573        return DiagnoseBadConversion(S, Cand, I);
6574
6575    // FIXME: this currently happens when we're called from SemaInit
6576    // when user-conversion overload fails.  Figure out how to handle
6577    // those conditions and diagnose them well.
6578    return S.NoteOverloadCandidate(Fn);
6579  }
6580  }
6581}
6582
6583void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6584  // Desugar the type of the surrogate down to a function type,
6585  // retaining as many typedefs as possible while still showing
6586  // the function type (and, therefore, its parameter types).
6587  QualType FnType = Cand->Surrogate->getConversionType();
6588  bool isLValueReference = false;
6589  bool isRValueReference = false;
6590  bool isPointer = false;
6591  if (const LValueReferenceType *FnTypeRef =
6592        FnType->getAs<LValueReferenceType>()) {
6593    FnType = FnTypeRef->getPointeeType();
6594    isLValueReference = true;
6595  } else if (const RValueReferenceType *FnTypeRef =
6596               FnType->getAs<RValueReferenceType>()) {
6597    FnType = FnTypeRef->getPointeeType();
6598    isRValueReference = true;
6599  }
6600  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6601    FnType = FnTypePtr->getPointeeType();
6602    isPointer = true;
6603  }
6604  // Desugar down to a function type.
6605  FnType = QualType(FnType->getAs<FunctionType>(), 0);
6606  // Reconstruct the pointer/reference as appropriate.
6607  if (isPointer) FnType = S.Context.getPointerType(FnType);
6608  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6609  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6610
6611  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6612    << FnType;
6613}
6614
6615void NoteBuiltinOperatorCandidate(Sema &S,
6616                                  const char *Opc,
6617                                  SourceLocation OpLoc,
6618                                  OverloadCandidate *Cand) {
6619  assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6620  std::string TypeStr("operator");
6621  TypeStr += Opc;
6622  TypeStr += "(";
6623  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6624  if (Cand->Conversions.size() == 1) {
6625    TypeStr += ")";
6626    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6627  } else {
6628    TypeStr += ", ";
6629    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6630    TypeStr += ")";
6631    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6632  }
6633}
6634
6635void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6636                                  OverloadCandidate *Cand) {
6637  unsigned NoOperands = Cand->Conversions.size();
6638  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6639    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
6640    if (ICS.isBad()) break; // all meaningless after first invalid
6641    if (!ICS.isAmbiguous()) continue;
6642
6643    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
6644                              S.PDiag(diag::note_ambiguous_type_conversion));
6645  }
6646}
6647
6648SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6649  if (Cand->Function)
6650    return Cand->Function->getLocation();
6651  if (Cand->IsSurrogate)
6652    return Cand->Surrogate->getLocation();
6653  return SourceLocation();
6654}
6655
6656struct CompareOverloadCandidatesForDisplay {
6657  Sema &S;
6658  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
6659
6660  bool operator()(const OverloadCandidate *L,
6661                  const OverloadCandidate *R) {
6662    // Fast-path this check.
6663    if (L == R) return false;
6664
6665    // Order first by viability.
6666    if (L->Viable) {
6667      if (!R->Viable) return true;
6668
6669      // TODO: introduce a tri-valued comparison for overload
6670      // candidates.  Would be more worthwhile if we had a sort
6671      // that could exploit it.
6672      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6673      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
6674    } else if (R->Viable)
6675      return false;
6676
6677    assert(L->Viable == R->Viable);
6678
6679    // Criteria by which we can sort non-viable candidates:
6680    if (!L->Viable) {
6681      // 1. Arity mismatches come after other candidates.
6682      if (L->FailureKind == ovl_fail_too_many_arguments ||
6683          L->FailureKind == ovl_fail_too_few_arguments)
6684        return false;
6685      if (R->FailureKind == ovl_fail_too_many_arguments ||
6686          R->FailureKind == ovl_fail_too_few_arguments)
6687        return true;
6688
6689      // 2. Bad conversions come first and are ordered by the number
6690      // of bad conversions and quality of good conversions.
6691      if (L->FailureKind == ovl_fail_bad_conversion) {
6692        if (R->FailureKind != ovl_fail_bad_conversion)
6693          return true;
6694
6695        // If there's any ordering between the defined conversions...
6696        // FIXME: this might not be transitive.
6697        assert(L->Conversions.size() == R->Conversions.size());
6698
6699        int leftBetter = 0;
6700        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6701        for (unsigned E = L->Conversions.size(); I != E; ++I) {
6702          switch (CompareImplicitConversionSequences(S,
6703                                                     L->Conversions[I],
6704                                                     R->Conversions[I])) {
6705          case ImplicitConversionSequence::Better:
6706            leftBetter++;
6707            break;
6708
6709          case ImplicitConversionSequence::Worse:
6710            leftBetter--;
6711            break;
6712
6713          case ImplicitConversionSequence::Indistinguishable:
6714            break;
6715          }
6716        }
6717        if (leftBetter > 0) return true;
6718        if (leftBetter < 0) return false;
6719
6720      } else if (R->FailureKind == ovl_fail_bad_conversion)
6721        return false;
6722
6723      // TODO: others?
6724    }
6725
6726    // Sort everything else by location.
6727    SourceLocation LLoc = GetLocationForCandidate(L);
6728    SourceLocation RLoc = GetLocationForCandidate(R);
6729
6730    // Put candidates without locations (e.g. builtins) at the end.
6731    if (LLoc.isInvalid()) return false;
6732    if (RLoc.isInvalid()) return true;
6733
6734    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
6735  }
6736};
6737
6738/// CompleteNonViableCandidate - Normally, overload resolution only
6739/// computes up to the first
6740void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6741                                Expr **Args, unsigned NumArgs) {
6742  assert(!Cand->Viable);
6743
6744  // Don't do anything on failures other than bad conversion.
6745  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6746
6747  // Skip forward to the first bad conversion.
6748  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
6749  unsigned ConvCount = Cand->Conversions.size();
6750  while (true) {
6751    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6752    ConvIdx++;
6753    if (Cand->Conversions[ConvIdx - 1].isBad())
6754      break;
6755  }
6756
6757  if (ConvIdx == ConvCount)
6758    return;
6759
6760  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6761         "remaining conversion is initialized?");
6762
6763  // FIXME: this should probably be preserved from the overload
6764  // operation somehow.
6765  bool SuppressUserConversions = false;
6766
6767  const FunctionProtoType* Proto;
6768  unsigned ArgIdx = ConvIdx;
6769
6770  if (Cand->IsSurrogate) {
6771    QualType ConvType
6772      = Cand->Surrogate->getConversionType().getNonReferenceType();
6773    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6774      ConvType = ConvPtrType->getPointeeType();
6775    Proto = ConvType->getAs<FunctionProtoType>();
6776    ArgIdx--;
6777  } else if (Cand->Function) {
6778    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6779    if (isa<CXXMethodDecl>(Cand->Function) &&
6780        !isa<CXXConstructorDecl>(Cand->Function))
6781      ArgIdx--;
6782  } else {
6783    // Builtin binary operator with a bad first conversion.
6784    assert(ConvCount <= 3);
6785    for (; ConvIdx != ConvCount; ++ConvIdx)
6786      Cand->Conversions[ConvIdx]
6787        = TryCopyInitialization(S, Args[ConvIdx],
6788                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
6789                                SuppressUserConversions,
6790                                /*InOverloadResolution*/ true);
6791    return;
6792  }
6793
6794  // Fill in the rest of the conversions.
6795  unsigned NumArgsInProto = Proto->getNumArgs();
6796  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6797    if (ArgIdx < NumArgsInProto)
6798      Cand->Conversions[ConvIdx]
6799        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6800                                SuppressUserConversions,
6801                                /*InOverloadResolution=*/true);
6802    else
6803      Cand->Conversions[ConvIdx].setEllipsis();
6804  }
6805}
6806
6807} // end anonymous namespace
6808
6809/// PrintOverloadCandidates - When overload resolution fails, prints
6810/// diagnostic messages containing the candidates in the candidate
6811/// set.
6812void OverloadCandidateSet::NoteCandidates(Sema &S,
6813                                          OverloadCandidateDisplayKind OCD,
6814                                          Expr **Args, unsigned NumArgs,
6815                                          const char *Opc,
6816                                          SourceLocation OpLoc) {
6817  // Sort the candidates by viability and position.  Sorting directly would
6818  // be prohibitive, so we make a set of pointers and sort those.
6819  llvm::SmallVector<OverloadCandidate*, 32> Cands;
6820  if (OCD == OCD_AllCandidates) Cands.reserve(size());
6821  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
6822    if (Cand->Viable)
6823      Cands.push_back(Cand);
6824    else if (OCD == OCD_AllCandidates) {
6825      CompleteNonViableCandidate(S, Cand, Args, NumArgs);
6826      if (Cand->Function || Cand->IsSurrogate)
6827        Cands.push_back(Cand);
6828      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
6829      // want to list every possible builtin candidate.
6830    }
6831  }
6832
6833  std::sort(Cands.begin(), Cands.end(),
6834            CompareOverloadCandidatesForDisplay(S));
6835
6836  bool ReportedAmbiguousConversions = false;
6837
6838  llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
6839  const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
6840  unsigned CandsShown = 0;
6841  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6842    OverloadCandidate *Cand = *I;
6843
6844    // Set an arbitrary limit on the number of candidate functions we'll spam
6845    // the user with.  FIXME: This limit should depend on details of the
6846    // candidate list.
6847    if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6848      break;
6849    }
6850    ++CandsShown;
6851
6852    if (Cand->Function)
6853      NoteFunctionCandidate(S, Cand, Args, NumArgs);
6854    else if (Cand->IsSurrogate)
6855      NoteSurrogateCandidate(S, Cand);
6856    else {
6857      assert(Cand->Viable &&
6858             "Non-viable built-in candidates are not added to Cands.");
6859      // Generally we only see ambiguities including viable builtin
6860      // operators if overload resolution got screwed up by an
6861      // ambiguous user-defined conversion.
6862      //
6863      // FIXME: It's quite possible for different conversions to see
6864      // different ambiguities, though.
6865      if (!ReportedAmbiguousConversions) {
6866        NoteAmbiguousUserConversions(S, OpLoc, Cand);
6867        ReportedAmbiguousConversions = true;
6868      }
6869
6870      // If this is a viable builtin, print it.
6871      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
6872    }
6873  }
6874
6875  if (I != E)
6876    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
6877}
6878
6879static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
6880  if (isa<UnresolvedLookupExpr>(E))
6881    return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
6882
6883  return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
6884}
6885
6886/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6887/// an overloaded function (C++ [over.over]), where @p From is an
6888/// expression with overloaded function type and @p ToType is the type
6889/// we're trying to resolve to. For example:
6890///
6891/// @code
6892/// int f(double);
6893/// int f(int);
6894///
6895/// int (*pfd)(double) = f; // selects f(double)
6896/// @endcode
6897///
6898/// This routine returns the resulting FunctionDecl if it could be
6899/// resolved, and NULL otherwise. When @p Complain is true, this
6900/// routine will emit diagnostics if there is an error.
6901FunctionDecl *
6902Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
6903                                         bool Complain,
6904                                         DeclAccessPair &FoundResult) {
6905  QualType FunctionType = ToType;
6906  bool IsMember = false;
6907  if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
6908    FunctionType = ToTypePtr->getPointeeType();
6909  else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
6910    FunctionType = ToTypeRef->getPointeeType();
6911  else if (const MemberPointerType *MemTypePtr =
6912                    ToType->getAs<MemberPointerType>()) {
6913    FunctionType = MemTypePtr->getPointeeType();
6914    IsMember = true;
6915  }
6916
6917  // C++ [over.over]p1:
6918  //   [...] [Note: any redundant set of parentheses surrounding the
6919  //   overloaded function name is ignored (5.1). ]
6920  // C++ [over.over]p1:
6921  //   [...] The overloaded function name can be preceded by the &
6922  //   operator.
6923  // However, remember whether the expression has member-pointer form:
6924  // C++ [expr.unary.op]p4:
6925  //     A pointer to member is only formed when an explicit & is used
6926  //     and its operand is a qualified-id not enclosed in
6927  //     parentheses.
6928  OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6929  OverloadExpr *OvlExpr = Ovl.Expression;
6930
6931  // We expect a pointer or reference to function, or a function pointer.
6932  FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6933  if (!FunctionType->isFunctionType()) {
6934    if (Complain)
6935      Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6936        << OvlExpr->getName() << ToType;
6937
6938    return 0;
6939  }
6940
6941  // If the overload expression doesn't have the form of a pointer to
6942  // member, don't try to convert it to a pointer-to-member type.
6943  if (IsMember && !Ovl.HasFormOfMemberPointer) {
6944    if (!Complain) return 0;
6945
6946    // TODO: Should we condition this on whether any functions might
6947    // have matched, or is it more appropriate to do that in callers?
6948    // TODO: a fixit wouldn't hurt.
6949    Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6950      << ToType << OvlExpr->getSourceRange();
6951    return 0;
6952  }
6953
6954  TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6955  if (OvlExpr->hasExplicitTemplateArgs()) {
6956    OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6957    ExplicitTemplateArgs = &ETABuffer;
6958  }
6959
6960  assert(From->getType() == Context.OverloadTy);
6961
6962  // Look through all of the overloaded functions, searching for one
6963  // whose type matches exactly.
6964  llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
6965  llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6966
6967  bool FoundNonTemplateFunction = false;
6968  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6969         E = OvlExpr->decls_end(); I != E; ++I) {
6970    // Look through any using declarations to find the underlying function.
6971    NamedDecl *Fn = (*I)->getUnderlyingDecl();
6972
6973    // C++ [over.over]p3:
6974    //   Non-member functions and static member functions match
6975    //   targets of type "pointer-to-function" or "reference-to-function."
6976    //   Nonstatic member functions match targets of
6977    //   type "pointer-to-member-function."
6978    // Note that according to DR 247, the containing class does not matter.
6979
6980    if (FunctionTemplateDecl *FunctionTemplate
6981          = dyn_cast<FunctionTemplateDecl>(Fn)) {
6982      if (CXXMethodDecl *Method
6983            = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
6984        // Skip non-static function templates when converting to pointer, and
6985        // static when converting to member pointer.
6986        if (Method->isStatic() == IsMember)
6987          continue;
6988      } else if (IsMember)
6989        continue;
6990
6991      // C++ [over.over]p2:
6992      //   If the name is a function template, template argument deduction is
6993      //   done (14.8.2.2), and if the argument deduction succeeds, the
6994      //   resulting template argument list is used to generate a single
6995      //   function template specialization, which is added to the set of
6996      //   overloaded functions considered.
6997      FunctionDecl *Specialization = 0;
6998      TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
6999      if (TemplateDeductionResult Result
7000            = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
7001                                      FunctionType, Specialization, Info)) {
7002        // FIXME: make a note of the failed deduction for diagnostics.
7003        (void)Result;
7004      } else {
7005        // Template argument deduction ensures that we have an exact match.
7006        // This function template specicalization works.
7007        Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7008        assert(FunctionType
7009                 == Context.getCanonicalType(Specialization->getType()));
7010        Matches.push_back(std::make_pair(I.getPair(), Specialization));
7011      }
7012
7013      continue;
7014    }
7015
7016    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7017      // Skip non-static functions when converting to pointer, and static
7018      // when converting to member pointer.
7019      if (Method->isStatic() == IsMember)
7020        continue;
7021
7022      // If we have explicit template arguments, skip non-templates.
7023      if (OvlExpr->hasExplicitTemplateArgs())
7024        continue;
7025    } else if (IsMember)
7026      continue;
7027
7028    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
7029      QualType ResultTy;
7030      if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
7031          IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
7032                               ResultTy)) {
7033        Matches.push_back(std::make_pair(I.getPair(),
7034                           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
7035        FoundNonTemplateFunction = true;
7036      }
7037    }
7038  }
7039
7040  // If there were 0 or 1 matches, we're done.
7041  if (Matches.empty()) {
7042    if (Complain) {
7043      Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
7044        << OvlExpr->getName() << FunctionType;
7045      for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7046                                 E = OvlExpr->decls_end();
7047           I != E; ++I)
7048        if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
7049          NoteOverloadCandidate(F);
7050    }
7051
7052    return 0;
7053  } else if (Matches.size() == 1) {
7054    FunctionDecl *Result = Matches[0].second;
7055    FoundResult = Matches[0].first;
7056    MarkDeclarationReferenced(From->getLocStart(), Result);
7057    if (Complain) {
7058      CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
7059    }
7060    return Result;
7061  }
7062
7063  // C++ [over.over]p4:
7064  //   If more than one function is selected, [...]
7065  if (!FoundNonTemplateFunction) {
7066    //   [...] and any given function template specialization F1 is
7067    //   eliminated if the set contains a second function template
7068    //   specialization whose function template is more specialized
7069    //   than the function template of F1 according to the partial
7070    //   ordering rules of 14.5.5.2.
7071
7072    // The algorithm specified above is quadratic. We instead use a
7073    // two-pass algorithm (similar to the one used to identify the
7074    // best viable function in an overload set) that identifies the
7075    // best function template (if it exists).
7076
7077    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7078    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7079      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
7080
7081    UnresolvedSetIterator Result =
7082        getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7083                           TPOC_Other, 0, From->getLocStart(),
7084                           PDiag(),
7085                           PDiag(diag::err_addr_ovl_ambiguous)
7086                               << Matches[0].second->getDeclName(),
7087                           PDiag(diag::note_ovl_candidate)
7088                               << (unsigned) oc_function_template);
7089    if (Result == MatchesCopy.end())
7090      return 0;
7091
7092    MarkDeclarationReferenced(From->getLocStart(), *Result);
7093    FoundResult = Matches[Result - MatchesCopy.begin()].first;
7094    if (Complain)
7095      CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
7096    return cast<FunctionDecl>(*Result);
7097  }
7098
7099  //   [...] any function template specializations in the set are
7100  //   eliminated if the set also contains a non-template function, [...]
7101  for (unsigned I = 0, N = Matches.size(); I != N; ) {
7102    if (Matches[I].second->getPrimaryTemplate() == 0)
7103      ++I;
7104    else {
7105      Matches[I] = Matches[--N];
7106      Matches.set_size(N);
7107    }
7108  }
7109
7110  // [...] After such eliminations, if any, there shall remain exactly one
7111  // selected function.
7112  if (Matches.size() == 1) {
7113    MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
7114    FoundResult = Matches[0].first;
7115    if (Complain)
7116      CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
7117    return cast<FunctionDecl>(Matches[0].second);
7118  }
7119
7120  // FIXME: We should probably return the same thing that BestViableFunction
7121  // returns (even if we issue the diagnostics here).
7122  if (Complain) {
7123    Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7124      << Matches[0].second->getDeclName();
7125    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7126      NoteOverloadCandidate(Matches[I].second);
7127  }
7128
7129  return 0;
7130}
7131
7132/// \brief Given an expression that refers to an overloaded function, try to
7133/// resolve that overloaded function expression down to a single function.
7134///
7135/// This routine can only resolve template-ids that refer to a single function
7136/// template, where that template-id refers to a single template whose template
7137/// arguments are either provided by the template-id or have defaults,
7138/// as described in C++0x [temp.arg.explicit]p3.
7139FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
7140  // C++ [over.over]p1:
7141  //   [...] [Note: any redundant set of parentheses surrounding the
7142  //   overloaded function name is ignored (5.1). ]
7143  // C++ [over.over]p1:
7144  //   [...] The overloaded function name can be preceded by the &
7145  //   operator.
7146
7147  if (From->getType() != Context.OverloadTy)
7148    return 0;
7149
7150  OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
7151
7152  // If we didn't actually find any template-ids, we're done.
7153  if (!OvlExpr->hasExplicitTemplateArgs())
7154    return 0;
7155
7156  TemplateArgumentListInfo ExplicitTemplateArgs;
7157  OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
7158
7159  // Look through all of the overloaded functions, searching for one
7160  // whose type matches exactly.
7161  FunctionDecl *Matched = 0;
7162  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7163         E = OvlExpr->decls_end(); I != E; ++I) {
7164    // C++0x [temp.arg.explicit]p3:
7165    //   [...] In contexts where deduction is done and fails, or in contexts
7166    //   where deduction is not done, if a template argument list is
7167    //   specified and it, along with any default template arguments,
7168    //   identifies a single function template specialization, then the
7169    //   template-id is an lvalue for the function template specialization.
7170    FunctionTemplateDecl *FunctionTemplate
7171      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
7172
7173    // C++ [over.over]p2:
7174    //   If the name is a function template, template argument deduction is
7175    //   done (14.8.2.2), and if the argument deduction succeeds, the
7176    //   resulting template argument list is used to generate a single
7177    //   function template specialization, which is added to the set of
7178    //   overloaded functions considered.
7179    FunctionDecl *Specialization = 0;
7180    TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7181    if (TemplateDeductionResult Result
7182          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7183                                    Specialization, Info)) {
7184      // FIXME: make a note of the failed deduction for diagnostics.
7185      (void)Result;
7186      continue;
7187    }
7188
7189    // Multiple matches; we can't resolve to a single declaration.
7190    if (Matched)
7191      return 0;
7192
7193    Matched = Specialization;
7194  }
7195
7196  return Matched;
7197}
7198
7199/// \brief Add a single candidate to the overload set.
7200static void AddOverloadedCallCandidate(Sema &S,
7201                                       DeclAccessPair FoundDecl,
7202                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
7203                                       Expr **Args, unsigned NumArgs,
7204                                       OverloadCandidateSet &CandidateSet,
7205                                       bool PartialOverloading) {
7206  NamedDecl *Callee = FoundDecl.getDecl();
7207  if (isa<UsingShadowDecl>(Callee))
7208    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7209
7210  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
7211    assert(!ExplicitTemplateArgs && "Explicit template arguments?");
7212    S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
7213                           false, PartialOverloading);
7214    return;
7215  }
7216
7217  if (FunctionTemplateDecl *FuncTemplate
7218      = dyn_cast<FunctionTemplateDecl>(Callee)) {
7219    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7220                                   ExplicitTemplateArgs,
7221                                   Args, NumArgs, CandidateSet);
7222    return;
7223  }
7224
7225  assert(false && "unhandled case in overloaded call candidate");
7226
7227  // do nothing?
7228}
7229
7230/// \brief Add the overload candidates named by callee and/or found by argument
7231/// dependent lookup to the given overload set.
7232void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
7233                                       Expr **Args, unsigned NumArgs,
7234                                       OverloadCandidateSet &CandidateSet,
7235                                       bool PartialOverloading) {
7236
7237#ifndef NDEBUG
7238  // Verify that ArgumentDependentLookup is consistent with the rules
7239  // in C++0x [basic.lookup.argdep]p3:
7240  //
7241  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
7242  //   and let Y be the lookup set produced by argument dependent
7243  //   lookup (defined as follows). If X contains
7244  //
7245  //     -- a declaration of a class member, or
7246  //
7247  //     -- a block-scope function declaration that is not a
7248  //        using-declaration, or
7249  //
7250  //     -- a declaration that is neither a function or a function
7251  //        template
7252  //
7253  //   then Y is empty.
7254
7255  if (ULE->requiresADL()) {
7256    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7257           E = ULE->decls_end(); I != E; ++I) {
7258      assert(!(*I)->getDeclContext()->isRecord());
7259      assert(isa<UsingShadowDecl>(*I) ||
7260             !(*I)->getDeclContext()->isFunctionOrMethod());
7261      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
7262    }
7263  }
7264#endif
7265
7266  // It would be nice to avoid this copy.
7267  TemplateArgumentListInfo TABuffer;
7268  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7269  if (ULE->hasExplicitTemplateArgs()) {
7270    ULE->copyTemplateArgumentsInto(TABuffer);
7271    ExplicitTemplateArgs = &TABuffer;
7272  }
7273
7274  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7275         E = ULE->decls_end(); I != E; ++I)
7276    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
7277                               Args, NumArgs, CandidateSet,
7278                               PartialOverloading);
7279
7280  if (ULE->requiresADL())
7281    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7282                                         Args, NumArgs,
7283                                         ExplicitTemplateArgs,
7284                                         CandidateSet,
7285                                         PartialOverloading);
7286}
7287
7288/// Attempts to recover from a call where no functions were found.
7289///
7290/// Returns true if new candidates were found.
7291static ExprResult
7292BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
7293                      UnresolvedLookupExpr *ULE,
7294                      SourceLocation LParenLoc,
7295                      Expr **Args, unsigned NumArgs,
7296                      SourceLocation RParenLoc) {
7297
7298  CXXScopeSpec SS;
7299  if (ULE->getQualifier()) {
7300    SS.setScopeRep(ULE->getQualifier());
7301    SS.setRange(ULE->getQualifierRange());
7302  }
7303
7304  TemplateArgumentListInfo TABuffer;
7305  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7306  if (ULE->hasExplicitTemplateArgs()) {
7307    ULE->copyTemplateArgumentsInto(TABuffer);
7308    ExplicitTemplateArgs = &TABuffer;
7309  }
7310
7311  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7312                 Sema::LookupOrdinaryName);
7313  if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
7314    return ExprError();
7315
7316  assert(!R.empty() && "lookup results empty despite recovery");
7317
7318  // Build an implicit member call if appropriate.  Just drop the
7319  // casts and such from the call, we don't really care.
7320  ExprResult NewFn = ExprError();
7321  if ((*R.begin())->isCXXClassMember())
7322    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7323                                                    ExplicitTemplateArgs);
7324  else if (ExplicitTemplateArgs)
7325    NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7326  else
7327    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7328
7329  if (NewFn.isInvalid())
7330    return ExprError();
7331
7332  // This shouldn't cause an infinite loop because we're giving it
7333  // an expression with non-empty lookup results, which should never
7334  // end up here.
7335  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
7336                               MultiExprArg(Args, NumArgs), RParenLoc);
7337}
7338
7339/// ResolveOverloadedCallFn - Given the call expression that calls Fn
7340/// (which eventually refers to the declaration Func) and the call
7341/// arguments Args/NumArgs, attempt to resolve the function call down
7342/// to a specific function. If overload resolution succeeds, returns
7343/// the function declaration produced by overload
7344/// resolution. Otherwise, emits diagnostics, deletes all of the
7345/// arguments and Fn, and returns NULL.
7346ExprResult
7347Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
7348                              SourceLocation LParenLoc,
7349                              Expr **Args, unsigned NumArgs,
7350                              SourceLocation RParenLoc) {
7351#ifndef NDEBUG
7352  if (ULE->requiresADL()) {
7353    // To do ADL, we must have found an unqualified name.
7354    assert(!ULE->getQualifier() && "qualified name with ADL");
7355
7356    // We don't perform ADL for implicit declarations of builtins.
7357    // Verify that this was correctly set up.
7358    FunctionDecl *F;
7359    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7360        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7361        F->getBuiltinID() && F->isImplicit())
7362      assert(0 && "performing ADL for builtin");
7363
7364    // We don't perform ADL in C.
7365    assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7366  }
7367#endif
7368
7369  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
7370
7371  // Add the functions denoted by the callee to the set of candidate
7372  // functions, including those from argument-dependent lookup.
7373  AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
7374
7375  // If we found nothing, try to recover.
7376  // AddRecoveryCallCandidates diagnoses the error itself, so we just
7377  // bailout out if it fails.
7378  if (CandidateSet.empty())
7379    return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
7380                                 RParenLoc);
7381
7382  OverloadCandidateSet::iterator Best;
7383  switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
7384  case OR_Success: {
7385    FunctionDecl *FDecl = Best->Function;
7386    CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
7387    DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7388                      ULE->getNameLoc());
7389    Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
7390    return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
7391                                 RParenLoc);
7392  }
7393
7394  case OR_No_Viable_Function:
7395    Diag(Fn->getSourceRange().getBegin(),
7396         diag::err_ovl_no_viable_function_in_call)
7397      << ULE->getName() << Fn->getSourceRange();
7398    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7399    break;
7400
7401  case OR_Ambiguous:
7402    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
7403      << ULE->getName() << Fn->getSourceRange();
7404    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
7405    break;
7406
7407  case OR_Deleted:
7408    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7409      << Best->Function->isDeleted()
7410      << ULE->getName()
7411      << Fn->getSourceRange();
7412    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7413    break;
7414  }
7415
7416  // Overload resolution failed.
7417  return ExprError();
7418}
7419
7420static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
7421  return Functions.size() > 1 ||
7422    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7423}
7424
7425/// \brief Create a unary operation that may resolve to an overloaded
7426/// operator.
7427///
7428/// \param OpLoc The location of the operator itself (e.g., '*').
7429///
7430/// \param OpcIn The UnaryOperator::Opcode that describes this
7431/// operator.
7432///
7433/// \param Functions The set of non-member functions that will be
7434/// considered by overload resolution. The caller needs to build this
7435/// set based on the context using, e.g.,
7436/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7437/// set should not contain any member functions; those will be added
7438/// by CreateOverloadedUnaryOp().
7439///
7440/// \param input The input argument.
7441ExprResult
7442Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7443                              const UnresolvedSetImpl &Fns,
7444                              Expr *Input) {
7445  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
7446
7447  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7448  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7449  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7450  // TODO: provide better source location info.
7451  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
7452
7453  if (Input->getObjectKind() == OK_ObjCProperty)
7454    ConvertPropertyForRValue(Input);
7455
7456  Expr *Args[2] = { Input, 0 };
7457  unsigned NumArgs = 1;
7458
7459  // For post-increment and post-decrement, add the implicit '0' as
7460  // the second argument, so that we know this is a post-increment or
7461  // post-decrement.
7462  if (Opc == UO_PostInc || Opc == UO_PostDec) {
7463    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
7464    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7465                                     SourceLocation());
7466    NumArgs = 2;
7467  }
7468
7469  if (Input->isTypeDependent()) {
7470    if (Fns.empty())
7471      return Owned(new (Context) UnaryOperator(Input,
7472                                               Opc,
7473                                               Context.DependentTy,
7474                                               VK_RValue, OK_Ordinary,
7475                                               OpLoc));
7476
7477    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
7478    UnresolvedLookupExpr *Fn
7479      = UnresolvedLookupExpr::Create(Context, NamingClass,
7480                                     0, SourceRange(), OpNameInfo,
7481                                     /*ADL*/ true, IsOverloaded(Fns),
7482                                     Fns.begin(), Fns.end());
7483    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7484                                                   &Args[0], NumArgs,
7485                                                   Context.DependentTy,
7486                                                   VK_RValue,
7487                                                   OpLoc));
7488  }
7489
7490  // Build an empty overload set.
7491  OverloadCandidateSet CandidateSet(OpLoc);
7492
7493  // Add the candidates from the given function set.
7494  AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
7495
7496  // Add operator candidates that are member functions.
7497  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7498
7499  // Add candidates from ADL.
7500  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7501                                       Args, NumArgs,
7502                                       /*ExplicitTemplateArgs*/ 0,
7503                                       CandidateSet);
7504
7505  // Add builtin operator candidates.
7506  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7507
7508  // Perform overload resolution.
7509  OverloadCandidateSet::iterator Best;
7510  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
7511  case OR_Success: {
7512    // We found a built-in operator or an overloaded operator.
7513    FunctionDecl *FnDecl = Best->Function;
7514
7515    if (FnDecl) {
7516      // We matched an overloaded operator. Build a call to that
7517      // operator.
7518
7519      // Convert the arguments.
7520      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
7521        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
7522
7523        if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7524                                                Best->FoundDecl, Method))
7525          return ExprError();
7526      } else {
7527        // Convert the arguments.
7528        ExprResult InputInit
7529          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7530                                                      Context,
7531                                                      FnDecl->getParamDecl(0)),
7532                                      SourceLocation(),
7533                                      Input);
7534        if (InputInit.isInvalid())
7535          return ExprError();
7536        Input = InputInit.take();
7537      }
7538
7539      DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7540
7541      // Determine the result type.
7542      QualType ResultTy = FnDecl->getResultType();
7543      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7544      ResultTy = ResultTy.getNonLValueExprType(Context);
7545
7546      // Build the actual expression node.
7547      Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
7548
7549      Args[0] = Input;
7550      CallExpr *TheCall =
7551        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7552                                          Args, NumArgs, ResultTy, VK, OpLoc);
7553
7554      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
7555                              FnDecl))
7556        return ExprError();
7557
7558      return MaybeBindToTemporary(TheCall);
7559    } else {
7560      // We matched a built-in operator. Convert the arguments, then
7561      // break out so that we will build the appropriate built-in
7562      // operator node.
7563        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
7564                                      Best->Conversions[0], AA_Passing))
7565          return ExprError();
7566
7567        break;
7568      }
7569    }
7570
7571    case OR_No_Viable_Function:
7572      // No viable function; fall through to handling this as a
7573      // built-in operator, which will produce an error message for us.
7574      break;
7575
7576    case OR_Ambiguous:
7577      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
7578          << UnaryOperator::getOpcodeStr(Opc)
7579          << Input->getType()
7580          << Input->getSourceRange();
7581      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7582                                  Args, NumArgs,
7583                                  UnaryOperator::getOpcodeStr(Opc), OpLoc);
7584      return ExprError();
7585
7586    case OR_Deleted:
7587      Diag(OpLoc, diag::err_ovl_deleted_oper)
7588        << Best->Function->isDeleted()
7589        << UnaryOperator::getOpcodeStr(Opc)
7590        << Input->getSourceRange();
7591      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7592      return ExprError();
7593    }
7594
7595  // Either we found no viable overloaded operator or we matched a
7596  // built-in operator. In either case, fall through to trying to
7597  // build a built-in operation.
7598  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
7599}
7600
7601/// \brief Create a binary operation that may resolve to an overloaded
7602/// operator.
7603///
7604/// \param OpLoc The location of the operator itself (e.g., '+').
7605///
7606/// \param OpcIn The BinaryOperator::Opcode that describes this
7607/// operator.
7608///
7609/// \param Functions The set of non-member functions that will be
7610/// considered by overload resolution. The caller needs to build this
7611/// set based on the context using, e.g.,
7612/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7613/// set should not contain any member functions; those will be added
7614/// by CreateOverloadedBinOp().
7615///
7616/// \param LHS Left-hand argument.
7617/// \param RHS Right-hand argument.
7618ExprResult
7619Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
7620                            unsigned OpcIn,
7621                            const UnresolvedSetImpl &Fns,
7622                            Expr *LHS, Expr *RHS) {
7623  Expr *Args[2] = { LHS, RHS };
7624  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
7625
7626  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7627  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7628  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7629
7630  // If either side is type-dependent, create an appropriate dependent
7631  // expression.
7632  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7633    if (Fns.empty()) {
7634      // If there are no functions to store, just build a dependent
7635      // BinaryOperator or CompoundAssignment.
7636      if (Opc <= BO_Assign || Opc > BO_OrAssign)
7637        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
7638                                                  Context.DependentTy,
7639                                                  VK_RValue, OK_Ordinary,
7640                                                  OpLoc));
7641
7642      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7643                                                        Context.DependentTy,
7644                                                        VK_LValue,
7645                                                        OK_Ordinary,
7646                                                        Context.DependentTy,
7647                                                        Context.DependentTy,
7648                                                        OpLoc));
7649    }
7650
7651    // FIXME: save results of ADL from here?
7652    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
7653    // TODO: provide better source location info in DNLoc component.
7654    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
7655    UnresolvedLookupExpr *Fn
7656      = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
7657                                     OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
7658                                     Fns.begin(), Fns.end());
7659    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7660                                                   Args, 2,
7661                                                   Context.DependentTy,
7662                                                   VK_RValue,
7663                                                   OpLoc));
7664  }
7665
7666  // Always do property rvalue conversions on the RHS.
7667  if (Args[1]->getObjectKind() == OK_ObjCProperty)
7668    ConvertPropertyForRValue(Args[1]);
7669
7670  // The LHS is more complicated.
7671  if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7672
7673    // There's a tension for assignment operators between primitive
7674    // property assignment and the overloaded operators.
7675    if (BinaryOperator::isAssignmentOp(Opc)) {
7676      const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7677
7678      // Is the property "logically" settable?
7679      bool Settable = (PRE->isExplicitProperty() ||
7680                       PRE->getImplicitPropertySetter());
7681
7682      // To avoid gratuitously inventing semantics, use the primitive
7683      // unless it isn't.  Thoughts in case we ever really care:
7684      // - If the property isn't logically settable, we have to
7685      //   load and hope.
7686      // - If the property is settable and this is simple assignment,
7687      //   we really should use the primitive.
7688      // - If the property is settable, then we could try overloading
7689      //   on a generic lvalue of the appropriate type;  if it works
7690      //   out to a builtin candidate, we would do that same operation
7691      //   on the property, and otherwise just error.
7692      if (Settable)
7693        return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7694    }
7695
7696    ConvertPropertyForRValue(Args[0]);
7697  }
7698
7699  // If this is the assignment operator, we only perform overload resolution
7700  // if the left-hand side is a class or enumeration type. This is actually
7701  // a hack. The standard requires that we do overload resolution between the
7702  // various built-in candidates, but as DR507 points out, this can lead to
7703  // problems. So we do it this way, which pretty much follows what GCC does.
7704  // Note that we go the traditional code path for compound assignment forms.
7705  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
7706    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7707
7708  // If this is the .* operator, which is not overloadable, just
7709  // create a built-in binary operator.
7710  if (Opc == BO_PtrMemD)
7711    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7712
7713  // Build an empty overload set.
7714  OverloadCandidateSet CandidateSet(OpLoc);
7715
7716  // Add the candidates from the given function set.
7717  AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
7718
7719  // Add operator candidates that are member functions.
7720  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7721
7722  // Add candidates from ADL.
7723  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7724                                       Args, 2,
7725                                       /*ExplicitTemplateArgs*/ 0,
7726                                       CandidateSet);
7727
7728  // Add builtin operator candidates.
7729  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7730
7731  // Perform overload resolution.
7732  OverloadCandidateSet::iterator Best;
7733  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
7734    case OR_Success: {
7735      // We found a built-in operator or an overloaded operator.
7736      FunctionDecl *FnDecl = Best->Function;
7737
7738      if (FnDecl) {
7739        // We matched an overloaded operator. Build a call to that
7740        // operator.
7741
7742        // Convert the arguments.
7743        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
7744          // Best->Access is only meaningful for class members.
7745          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
7746
7747          ExprResult Arg1 =
7748            PerformCopyInitialization(
7749              InitializedEntity::InitializeParameter(Context,
7750                                                     FnDecl->getParamDecl(0)),
7751              SourceLocation(), Owned(Args[1]));
7752          if (Arg1.isInvalid())
7753            return ExprError();
7754
7755          if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
7756                                                  Best->FoundDecl, Method))
7757            return ExprError();
7758
7759          Args[1] = RHS = Arg1.takeAs<Expr>();
7760        } else {
7761          // Convert the arguments.
7762          ExprResult Arg0 = PerformCopyInitialization(
7763            InitializedEntity::InitializeParameter(Context,
7764                                                   FnDecl->getParamDecl(0)),
7765            SourceLocation(), Owned(Args[0]));
7766          if (Arg0.isInvalid())
7767            return ExprError();
7768
7769          ExprResult Arg1 =
7770            PerformCopyInitialization(
7771              InitializedEntity::InitializeParameter(Context,
7772                                                     FnDecl->getParamDecl(1)),
7773              SourceLocation(), Owned(Args[1]));
7774          if (Arg1.isInvalid())
7775            return ExprError();
7776          Args[0] = LHS = Arg0.takeAs<Expr>();
7777          Args[1] = RHS = Arg1.takeAs<Expr>();
7778        }
7779
7780        DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7781
7782        // Determine the result type.
7783        QualType ResultTy = FnDecl->getResultType();
7784        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7785        ResultTy = ResultTy.getNonLValueExprType(Context);
7786
7787        // Build the actual expression node.
7788        Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
7789
7790        CXXOperatorCallExpr *TheCall =
7791          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7792                                            Args, 2, ResultTy, VK, OpLoc);
7793
7794        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
7795                                FnDecl))
7796          return ExprError();
7797
7798        return MaybeBindToTemporary(TheCall);
7799      } else {
7800        // We matched a built-in operator. Convert the arguments, then
7801        // break out so that we will build the appropriate built-in
7802        // operator node.
7803        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
7804                                      Best->Conversions[0], AA_Passing) ||
7805            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
7806                                      Best->Conversions[1], AA_Passing))
7807          return ExprError();
7808
7809        break;
7810      }
7811    }
7812
7813    case OR_No_Viable_Function: {
7814      // C++ [over.match.oper]p9:
7815      //   If the operator is the operator , [...] and there are no
7816      //   viable functions, then the operator is assumed to be the
7817      //   built-in operator and interpreted according to clause 5.
7818      if (Opc == BO_Comma)
7819        break;
7820
7821      // For class as left operand for assignment or compound assigment
7822      // operator do not fall through to handling in built-in, but report that
7823      // no overloaded assignment operator found
7824      ExprResult Result = ExprError();
7825      if (Args[0]->getType()->isRecordType() &&
7826          Opc >= BO_Assign && Opc <= BO_OrAssign) {
7827        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
7828             << BinaryOperator::getOpcodeStr(Opc)
7829             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7830      } else {
7831        // No viable function; try to create a built-in operation, which will
7832        // produce an error. Then, show the non-viable candidates.
7833        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7834      }
7835      assert(Result.isInvalid() &&
7836             "C++ binary operator overloading is missing candidates!");
7837      if (Result.isInvalid())
7838        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7839                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
7840      return move(Result);
7841    }
7842
7843    case OR_Ambiguous:
7844      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
7845          << BinaryOperator::getOpcodeStr(Opc)
7846          << Args[0]->getType() << Args[1]->getType()
7847          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7848      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7849                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
7850      return ExprError();
7851
7852    case OR_Deleted:
7853      Diag(OpLoc, diag::err_ovl_deleted_oper)
7854        << Best->Function->isDeleted()
7855        << BinaryOperator::getOpcodeStr(Opc)
7856        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7857      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
7858      return ExprError();
7859  }
7860
7861  // We matched a built-in operator; build it.
7862  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7863}
7864
7865ExprResult
7866Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7867                                         SourceLocation RLoc,
7868                                         Expr *Base, Expr *Idx) {
7869  Expr *Args[2] = { Base, Idx };
7870  DeclarationName OpName =
7871      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7872
7873  // If either side is type-dependent, create an appropriate dependent
7874  // expression.
7875  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7876
7877    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
7878    // CHECKME: no 'operator' keyword?
7879    DeclarationNameInfo OpNameInfo(OpName, LLoc);
7880    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
7881    UnresolvedLookupExpr *Fn
7882      = UnresolvedLookupExpr::Create(Context, NamingClass,
7883                                     0, SourceRange(), OpNameInfo,
7884                                     /*ADL*/ true, /*Overloaded*/ false,
7885                                     UnresolvedSetIterator(),
7886                                     UnresolvedSetIterator());
7887    // Can't add any actual overloads yet
7888
7889    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7890                                                   Args, 2,
7891                                                   Context.DependentTy,
7892                                                   VK_RValue,
7893                                                   RLoc));
7894  }
7895
7896  if (Args[0]->getObjectKind() == OK_ObjCProperty)
7897    ConvertPropertyForRValue(Args[0]);
7898  if (Args[1]->getObjectKind() == OK_ObjCProperty)
7899    ConvertPropertyForRValue(Args[1]);
7900
7901  // Build an empty overload set.
7902  OverloadCandidateSet CandidateSet(LLoc);
7903
7904  // Subscript can only be overloaded as a member function.
7905
7906  // Add operator candidates that are member functions.
7907  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7908
7909  // Add builtin operator candidates.
7910  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7911
7912  // Perform overload resolution.
7913  OverloadCandidateSet::iterator Best;
7914  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
7915    case OR_Success: {
7916      // We found a built-in operator or an overloaded operator.
7917      FunctionDecl *FnDecl = Best->Function;
7918
7919      if (FnDecl) {
7920        // We matched an overloaded operator. Build a call to that
7921        // operator.
7922
7923        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
7924        DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
7925
7926        // Convert the arguments.
7927        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
7928        if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
7929                                                Best->FoundDecl, Method))
7930          return ExprError();
7931
7932        // Convert the arguments.
7933        ExprResult InputInit
7934          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7935                                                      Context,
7936                                                      FnDecl->getParamDecl(0)),
7937                                      SourceLocation(),
7938                                      Owned(Args[1]));
7939        if (InputInit.isInvalid())
7940          return ExprError();
7941
7942        Args[1] = InputInit.takeAs<Expr>();
7943
7944        // Determine the result type
7945        QualType ResultTy = FnDecl->getResultType();
7946        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7947        ResultTy = ResultTy.getNonLValueExprType(Context);
7948
7949        // Build the actual expression node.
7950        Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
7951
7952        CXXOperatorCallExpr *TheCall =
7953          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7954                                            FnExpr, Args, 2,
7955                                            ResultTy, VK, RLoc);
7956
7957        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
7958                                FnDecl))
7959          return ExprError();
7960
7961        return MaybeBindToTemporary(TheCall);
7962      } else {
7963        // We matched a built-in operator. Convert the arguments, then
7964        // break out so that we will build the appropriate built-in
7965        // operator node.
7966        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
7967                                      Best->Conversions[0], AA_Passing) ||
7968            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
7969                                      Best->Conversions[1], AA_Passing))
7970          return ExprError();
7971
7972        break;
7973      }
7974    }
7975
7976    case OR_No_Viable_Function: {
7977      if (CandidateSet.empty())
7978        Diag(LLoc, diag::err_ovl_no_oper)
7979          << Args[0]->getType() << /*subscript*/ 0
7980          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7981      else
7982        Diag(LLoc, diag::err_ovl_no_viable_subscript)
7983          << Args[0]->getType()
7984          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7985      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7986                                  "[]", LLoc);
7987      return ExprError();
7988    }
7989
7990    case OR_Ambiguous:
7991      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
7992          << "[]"
7993          << Args[0]->getType() << Args[1]->getType()
7994          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7995      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7996                                  "[]", LLoc);
7997      return ExprError();
7998
7999    case OR_Deleted:
8000      Diag(LLoc, diag::err_ovl_deleted_oper)
8001        << Best->Function->isDeleted() << "[]"
8002        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8003      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8004                                  "[]", LLoc);
8005      return ExprError();
8006    }
8007
8008  // We matched a built-in operator; build it.
8009  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
8010}
8011
8012/// BuildCallToMemberFunction - Build a call to a member
8013/// function. MemExpr is the expression that refers to the member
8014/// function (and includes the object parameter), Args/NumArgs are the
8015/// arguments to the function call (not including the object
8016/// parameter). The caller needs to validate that the member
8017/// expression refers to a member function or an overloaded member
8018/// function.
8019ExprResult
8020Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8021                                SourceLocation LParenLoc, Expr **Args,
8022                                unsigned NumArgs, SourceLocation RParenLoc) {
8023  // Dig out the member expression. This holds both the object
8024  // argument and the member function we're referring to.
8025  Expr *NakedMemExpr = MemExprE->IgnoreParens();
8026
8027  MemberExpr *MemExpr;
8028  CXXMethodDecl *Method = 0;
8029  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
8030  NestedNameSpecifier *Qualifier = 0;
8031  if (isa<MemberExpr>(NakedMemExpr)) {
8032    MemExpr = cast<MemberExpr>(NakedMemExpr);
8033    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
8034    FoundDecl = MemExpr->getFoundDecl();
8035    Qualifier = MemExpr->getQualifier();
8036  } else {
8037    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
8038    Qualifier = UnresExpr->getQualifier();
8039
8040    QualType ObjectType = UnresExpr->getBaseType();
8041    Expr::Classification ObjectClassification
8042      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8043                            : UnresExpr->getBase()->Classify(Context);
8044
8045    // Add overload candidates
8046    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
8047
8048    // FIXME: avoid copy.
8049    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8050    if (UnresExpr->hasExplicitTemplateArgs()) {
8051      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8052      TemplateArgs = &TemplateArgsBuffer;
8053    }
8054
8055    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8056           E = UnresExpr->decls_end(); I != E; ++I) {
8057
8058      NamedDecl *Func = *I;
8059      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8060      if (isa<UsingShadowDecl>(Func))
8061        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8062
8063
8064      // Microsoft supports direct constructor calls.
8065      if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8066        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8067                             CandidateSet);
8068      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
8069        // If explicit template arguments were provided, we can't call a
8070        // non-template member function.
8071        if (TemplateArgs)
8072          continue;
8073
8074        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
8075                           ObjectClassification,
8076                           Args, NumArgs, CandidateSet,
8077                           /*SuppressUserConversions=*/false);
8078      } else {
8079        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
8080                                   I.getPair(), ActingDC, TemplateArgs,
8081                                   ObjectType,  ObjectClassification,
8082                                   Args, NumArgs, CandidateSet,
8083                                   /*SuppressUsedConversions=*/false);
8084      }
8085    }
8086
8087    DeclarationName DeclName = UnresExpr->getMemberName();
8088
8089    OverloadCandidateSet::iterator Best;
8090    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
8091                                            Best)) {
8092    case OR_Success:
8093      Method = cast<CXXMethodDecl>(Best->Function);
8094      FoundDecl = Best->FoundDecl;
8095      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
8096      DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
8097      break;
8098
8099    case OR_No_Viable_Function:
8100      Diag(UnresExpr->getMemberLoc(),
8101           diag::err_ovl_no_viable_member_function_in_call)
8102        << DeclName << MemExprE->getSourceRange();
8103      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8104      // FIXME: Leaking incoming expressions!
8105      return ExprError();
8106
8107    case OR_Ambiguous:
8108      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
8109        << DeclName << MemExprE->getSourceRange();
8110      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8111      // FIXME: Leaking incoming expressions!
8112      return ExprError();
8113
8114    case OR_Deleted:
8115      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
8116        << Best->Function->isDeleted()
8117        << DeclName << MemExprE->getSourceRange();
8118      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8119      // FIXME: Leaking incoming expressions!
8120      return ExprError();
8121    }
8122
8123    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
8124
8125    // If overload resolution picked a static member, build a
8126    // non-member call based on that function.
8127    if (Method->isStatic()) {
8128      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8129                                   Args, NumArgs, RParenLoc);
8130    }
8131
8132    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
8133  }
8134
8135  QualType ResultType = Method->getResultType();
8136  ExprValueKind VK = Expr::getValueKindForType(ResultType);
8137  ResultType = ResultType.getNonLValueExprType(Context);
8138
8139  assert(Method && "Member call to something that isn't a method?");
8140  CXXMemberCallExpr *TheCall =
8141    new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
8142                                    ResultType, VK, RParenLoc);
8143
8144  // Check for a valid return type.
8145  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
8146                          TheCall, Method))
8147    return ExprError();
8148
8149  // Convert the object argument (for a non-static member function call).
8150  // We only need to do this if there was actually an overload; otherwise
8151  // it was done at lookup.
8152  Expr *ObjectArg = MemExpr->getBase();
8153  if (!Method->isStatic() &&
8154      PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8155                                          FoundDecl, Method))
8156    return ExprError();
8157  MemExpr->setBase(ObjectArg);
8158
8159  // Convert the rest of the arguments
8160  const FunctionProtoType *Proto =
8161    Method->getType()->getAs<FunctionProtoType>();
8162  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
8163                              RParenLoc))
8164    return ExprError();
8165
8166  if (CheckFunctionCall(Method, TheCall))
8167    return ExprError();
8168
8169  return MaybeBindToTemporary(TheCall);
8170}
8171
8172/// BuildCallToObjectOfClassType - Build a call to an object of class
8173/// type (C++ [over.call.object]), which can end up invoking an
8174/// overloaded function call operator (@c operator()) or performing a
8175/// user-defined conversion on the object argument.
8176ExprResult
8177Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
8178                                   SourceLocation LParenLoc,
8179                                   Expr **Args, unsigned NumArgs,
8180                                   SourceLocation RParenLoc) {
8181  if (Object->getObjectKind() == OK_ObjCProperty)
8182    ConvertPropertyForRValue(Object);
8183
8184  assert(Object->getType()->isRecordType() && "Requires object type argument");
8185  const RecordType *Record = Object->getType()->getAs<RecordType>();
8186
8187  // C++ [over.call.object]p1:
8188  //  If the primary-expression E in the function call syntax
8189  //  evaluates to a class object of type "cv T", then the set of
8190  //  candidate functions includes at least the function call
8191  //  operators of T. The function call operators of T are obtained by
8192  //  ordinary lookup of the name operator() in the context of
8193  //  (E).operator().
8194  OverloadCandidateSet CandidateSet(LParenLoc);
8195  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
8196
8197  if (RequireCompleteType(LParenLoc, Object->getType(),
8198                          PDiag(diag::err_incomplete_object_call)
8199                          << Object->getSourceRange()))
8200    return true;
8201
8202  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8203  LookupQualifiedName(R, Record->getDecl());
8204  R.suppressDiagnostics();
8205
8206  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
8207       Oper != OperEnd; ++Oper) {
8208    AddMethodCandidate(Oper.getPair(), Object->getType(),
8209                       Object->Classify(Context), Args, NumArgs, CandidateSet,
8210                       /*SuppressUserConversions=*/ false);
8211  }
8212
8213  // C++ [over.call.object]p2:
8214  //   In addition, for each conversion function declared in T of the
8215  //   form
8216  //
8217  //        operator conversion-type-id () cv-qualifier;
8218  //
8219  //   where cv-qualifier is the same cv-qualification as, or a
8220  //   greater cv-qualification than, cv, and where conversion-type-id
8221  //   denotes the type "pointer to function of (P1,...,Pn) returning
8222  //   R", or the type "reference to pointer to function of
8223  //   (P1,...,Pn) returning R", or the type "reference to function
8224  //   of (P1,...,Pn) returning R", a surrogate call function [...]
8225  //   is also considered as a candidate function. Similarly,
8226  //   surrogate call functions are added to the set of candidate
8227  //   functions for each conversion function declared in an
8228  //   accessible base class provided the function is not hidden
8229  //   within T by another intervening declaration.
8230  const UnresolvedSetImpl *Conversions
8231    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
8232  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
8233         E = Conversions->end(); I != E; ++I) {
8234    NamedDecl *D = *I;
8235    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8236    if (isa<UsingShadowDecl>(D))
8237      D = cast<UsingShadowDecl>(D)->getTargetDecl();
8238
8239    // Skip over templated conversion functions; they aren't
8240    // surrogates.
8241    if (isa<FunctionTemplateDecl>(D))
8242      continue;
8243
8244    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8245
8246    // Strip the reference type (if any) and then the pointer type (if
8247    // any) to get down to what might be a function type.
8248    QualType ConvType = Conv->getConversionType().getNonReferenceType();
8249    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8250      ConvType = ConvPtrType->getPointeeType();
8251
8252    if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
8253      AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
8254                            Object, Args, NumArgs, CandidateSet);
8255  }
8256
8257  // Perform overload resolution.
8258  OverloadCandidateSet::iterator Best;
8259  switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8260                             Best)) {
8261  case OR_Success:
8262    // Overload resolution succeeded; we'll build the appropriate call
8263    // below.
8264    break;
8265
8266  case OR_No_Viable_Function:
8267    if (CandidateSet.empty())
8268      Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8269        << Object->getType() << /*call*/ 1
8270        << Object->getSourceRange();
8271    else
8272      Diag(Object->getSourceRange().getBegin(),
8273           diag::err_ovl_no_viable_object_call)
8274        << Object->getType() << Object->getSourceRange();
8275    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8276    break;
8277
8278  case OR_Ambiguous:
8279    Diag(Object->getSourceRange().getBegin(),
8280         diag::err_ovl_ambiguous_object_call)
8281      << Object->getType() << Object->getSourceRange();
8282    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
8283    break;
8284
8285  case OR_Deleted:
8286    Diag(Object->getSourceRange().getBegin(),
8287         diag::err_ovl_deleted_object_call)
8288      << Best->Function->isDeleted()
8289      << Object->getType() << Object->getSourceRange();
8290    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8291    break;
8292  }
8293
8294  if (Best == CandidateSet.end())
8295    return true;
8296
8297  if (Best->Function == 0) {
8298    // Since there is no function declaration, this is one of the
8299    // surrogate candidates. Dig out the conversion function.
8300    CXXConversionDecl *Conv
8301      = cast<CXXConversionDecl>(
8302                         Best->Conversions[0].UserDefined.ConversionFunction);
8303
8304    CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
8305    DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
8306
8307    // We selected one of the surrogate functions that converts the
8308    // object parameter to a function pointer. Perform the conversion
8309    // on the object argument, then let ActOnCallExpr finish the job.
8310
8311    // Create an implicit member expr to refer to the conversion operator.
8312    // and then call it.
8313    ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8314    if (Call.isInvalid())
8315      return ExprError();
8316
8317    return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
8318                         RParenLoc);
8319  }
8320
8321  CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
8322  DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
8323
8324  // We found an overloaded operator(). Build a CXXOperatorCallExpr
8325  // that calls this method, using Object for the implicit object
8326  // parameter and passing along the remaining arguments.
8327  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
8328  const FunctionProtoType *Proto =
8329    Method->getType()->getAs<FunctionProtoType>();
8330
8331  unsigned NumArgsInProto = Proto->getNumArgs();
8332  unsigned NumArgsToCheck = NumArgs;
8333
8334  // Build the full argument list for the method call (the
8335  // implicit object parameter is placed at the beginning of the
8336  // list).
8337  Expr **MethodArgs;
8338  if (NumArgs < NumArgsInProto) {
8339    NumArgsToCheck = NumArgsInProto;
8340    MethodArgs = new Expr*[NumArgsInProto + 1];
8341  } else {
8342    MethodArgs = new Expr*[NumArgs + 1];
8343  }
8344  MethodArgs[0] = Object;
8345  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8346    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
8347
8348  Expr *NewFn = CreateFunctionRefExpr(*this, Method);
8349
8350  // Once we've built TheCall, all of the expressions are properly
8351  // owned.
8352  QualType ResultTy = Method->getResultType();
8353  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8354  ResultTy = ResultTy.getNonLValueExprType(Context);
8355
8356  CXXOperatorCallExpr *TheCall =
8357    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8358                                      MethodArgs, NumArgs + 1,
8359                                      ResultTy, VK, RParenLoc);
8360  delete [] MethodArgs;
8361
8362  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
8363                          Method))
8364    return true;
8365
8366  // We may have default arguments. If so, we need to allocate more
8367  // slots in the call for them.
8368  if (NumArgs < NumArgsInProto)
8369    TheCall->setNumArgs(Context, NumArgsInProto + 1);
8370  else if (NumArgs > NumArgsInProto)
8371    NumArgsToCheck = NumArgsInProto;
8372
8373  bool IsError = false;
8374
8375  // Initialize the implicit object parameter.
8376  IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
8377                                                 Best->FoundDecl, Method);
8378  TheCall->setArg(0, Object);
8379
8380
8381  // Check the argument types.
8382  for (unsigned i = 0; i != NumArgsToCheck; i++) {
8383    Expr *Arg;
8384    if (i < NumArgs) {
8385      Arg = Args[i];
8386
8387      // Pass the argument.
8388
8389      ExprResult InputInit
8390        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
8391                                                    Context,
8392                                                    Method->getParamDecl(i)),
8393                                    SourceLocation(), Arg);
8394
8395      IsError |= InputInit.isInvalid();
8396      Arg = InputInit.takeAs<Expr>();
8397    } else {
8398      ExprResult DefArg
8399        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8400      if (DefArg.isInvalid()) {
8401        IsError = true;
8402        break;
8403      }
8404
8405      Arg = DefArg.takeAs<Expr>();
8406    }
8407
8408    TheCall->setArg(i + 1, Arg);
8409  }
8410
8411  // If this is a variadic call, handle args passed through "...".
8412  if (Proto->isVariadic()) {
8413    // Promote the arguments (C99 6.5.2.2p7).
8414    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8415      Expr *Arg = Args[i];
8416      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
8417      TheCall->setArg(i + 1, Arg);
8418    }
8419  }
8420
8421  if (IsError) return true;
8422
8423  if (CheckFunctionCall(Method, TheCall))
8424    return true;
8425
8426  return MaybeBindToTemporary(TheCall);
8427}
8428
8429/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
8430///  (if one exists), where @c Base is an expression of class type and
8431/// @c Member is the name of the member we're trying to find.
8432ExprResult
8433Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
8434  assert(Base->getType()->isRecordType() &&
8435         "left-hand side must have class type");
8436
8437  if (Base->getObjectKind() == OK_ObjCProperty)
8438    ConvertPropertyForRValue(Base);
8439
8440  SourceLocation Loc = Base->getExprLoc();
8441
8442  // C++ [over.ref]p1:
8443  //
8444  //   [...] An expression x->m is interpreted as (x.operator->())->m
8445  //   for a class object x of type T if T::operator->() exists and if
8446  //   the operator is selected as the best match function by the
8447  //   overload resolution mechanism (13.3).
8448  DeclarationName OpName =
8449    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
8450  OverloadCandidateSet CandidateSet(Loc);
8451  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
8452
8453  if (RequireCompleteType(Loc, Base->getType(),
8454                          PDiag(diag::err_typecheck_incomplete_tag)
8455                            << Base->getSourceRange()))
8456    return ExprError();
8457
8458  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8459  LookupQualifiedName(R, BaseRecord->getDecl());
8460  R.suppressDiagnostics();
8461
8462  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
8463       Oper != OperEnd; ++Oper) {
8464    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8465                       0, 0, CandidateSet, /*SuppressUserConversions=*/false);
8466  }
8467
8468  // Perform overload resolution.
8469  OverloadCandidateSet::iterator Best;
8470  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
8471  case OR_Success:
8472    // Overload resolution succeeded; we'll build the call below.
8473    break;
8474
8475  case OR_No_Viable_Function:
8476    if (CandidateSet.empty())
8477      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
8478        << Base->getType() << Base->getSourceRange();
8479    else
8480      Diag(OpLoc, diag::err_ovl_no_viable_oper)
8481        << "operator->" << Base->getSourceRange();
8482    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
8483    return ExprError();
8484
8485  case OR_Ambiguous:
8486    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
8487      << "->" << Base->getType() << Base->getSourceRange();
8488    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
8489    return ExprError();
8490
8491  case OR_Deleted:
8492    Diag(OpLoc,  diag::err_ovl_deleted_oper)
8493      << Best->Function->isDeleted()
8494      << "->" << Base->getSourceRange();
8495    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
8496    return ExprError();
8497  }
8498
8499  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
8500  DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8501
8502  // Convert the object parameter.
8503  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
8504  if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8505                                          Best->FoundDecl, Method))
8506    return ExprError();
8507
8508  // Build the operator call.
8509  Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
8510
8511  QualType ResultTy = Method->getResultType();
8512  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8513  ResultTy = ResultTy.getNonLValueExprType(Context);
8514  CXXOperatorCallExpr *TheCall =
8515    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
8516                                      &Base, 1, ResultTy, VK, OpLoc);
8517
8518  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
8519                          Method))
8520          return ExprError();
8521  return Owned(TheCall);
8522}
8523
8524/// FixOverloadedFunctionReference - E is an expression that refers to
8525/// a C++ overloaded function (possibly with some parentheses and
8526/// perhaps a '&' around it). We have resolved the overloaded function
8527/// to the function declaration Fn, so patch up the expression E to
8528/// refer (possibly indirectly) to Fn. Returns the new expr.
8529Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
8530                                           FunctionDecl *Fn) {
8531  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
8532    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8533                                                   Found, Fn);
8534    if (SubExpr == PE->getSubExpr())
8535      return PE;
8536
8537    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8538  }
8539
8540  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8541    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8542                                                   Found, Fn);
8543    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
8544                               SubExpr->getType()) &&
8545           "Implicit cast type cannot be determined from overload");
8546    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
8547    if (SubExpr == ICE->getSubExpr())
8548      return ICE;
8549
8550    return ImplicitCastExpr::Create(Context, ICE->getType(),
8551                                    ICE->getCastKind(),
8552                                    SubExpr, 0,
8553                                    ICE->getValueKind());
8554  }
8555
8556  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
8557    assert(UnOp->getOpcode() == UO_AddrOf &&
8558           "Can only take the address of an overloaded function");
8559    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8560      if (Method->isStatic()) {
8561        // Do nothing: static member functions aren't any different
8562        // from non-member functions.
8563      } else {
8564        // Fix the sub expression, which really has to be an
8565        // UnresolvedLookupExpr holding an overloaded member function
8566        // or template.
8567        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8568                                                       Found, Fn);
8569        if (SubExpr == UnOp->getSubExpr())
8570          return UnOp;
8571
8572        assert(isa<DeclRefExpr>(SubExpr)
8573               && "fixed to something other than a decl ref");
8574        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8575               && "fixed to a member ref with no nested name qualifier");
8576
8577        // We have taken the address of a pointer to member
8578        // function. Perform the computation here so that we get the
8579        // appropriate pointer to member type.
8580        QualType ClassType
8581          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8582        QualType MemPtrType
8583          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8584
8585        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8586                                           VK_RValue, OK_Ordinary,
8587                                           UnOp->getOperatorLoc());
8588      }
8589    }
8590    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8591                                                   Found, Fn);
8592    if (SubExpr == UnOp->getSubExpr())
8593      return UnOp;
8594
8595    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
8596                                     Context.getPointerType(SubExpr->getType()),
8597                                       VK_RValue, OK_Ordinary,
8598                                       UnOp->getOperatorLoc());
8599  }
8600
8601  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8602    // FIXME: avoid copy.
8603    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8604    if (ULE->hasExplicitTemplateArgs()) {
8605      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8606      TemplateArgs = &TemplateArgsBuffer;
8607    }
8608
8609    return DeclRefExpr::Create(Context,
8610                               ULE->getQualifier(),
8611                               ULE->getQualifierRange(),
8612                               Fn,
8613                               ULE->getNameLoc(),
8614                               Fn->getType(),
8615                               VK_LValue,
8616                               TemplateArgs);
8617  }
8618
8619  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
8620    // FIXME: avoid copy.
8621    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8622    if (MemExpr->hasExplicitTemplateArgs()) {
8623      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8624      TemplateArgs = &TemplateArgsBuffer;
8625    }
8626
8627    Expr *Base;
8628
8629    // If we're filling in a static method where we used to have an
8630    // implicit member access, rewrite to a simple decl ref.
8631    if (MemExpr->isImplicitAccess()) {
8632      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8633        return DeclRefExpr::Create(Context,
8634                                   MemExpr->getQualifier(),
8635                                   MemExpr->getQualifierRange(),
8636                                   Fn,
8637                                   MemExpr->getMemberLoc(),
8638                                   Fn->getType(),
8639                                   VK_LValue,
8640                                   TemplateArgs);
8641      } else {
8642        SourceLocation Loc = MemExpr->getMemberLoc();
8643        if (MemExpr->getQualifier())
8644          Loc = MemExpr->getQualifierRange().getBegin();
8645        Base = new (Context) CXXThisExpr(Loc,
8646                                         MemExpr->getBaseType(),
8647                                         /*isImplicit=*/true);
8648      }
8649    } else
8650      Base = MemExpr->getBase();
8651
8652    return MemberExpr::Create(Context, Base,
8653                              MemExpr->isArrow(),
8654                              MemExpr->getQualifier(),
8655                              MemExpr->getQualifierRange(),
8656                              Fn,
8657                              Found,
8658                              MemExpr->getMemberNameInfo(),
8659                              TemplateArgs,
8660                              Fn->getType(),
8661                              cast<CXXMethodDecl>(Fn)->isStatic()
8662                                ? VK_LValue : VK_RValue,
8663                              OK_Ordinary);
8664  }
8665
8666  llvm_unreachable("Invalid reference to overloaded function");
8667  return E;
8668}
8669
8670ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8671                                                DeclAccessPair Found,
8672                                                FunctionDecl *Fn) {
8673  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
8674}
8675
8676} // end namespace clang
8677