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