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