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