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