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