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