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