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