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