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