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