SemaOverload.cpp revision 6ab3524f72a6e64aa04973fa9433b5559abb3525
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 "Sema.h"
15#include "SemaInherit.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TypeOrdering.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33  static const ImplicitConversionCategory
34    Category[(int)ICK_Num_Conversion_Kinds] = {
35    ICC_Identity,
36    ICC_Lvalue_Transformation,
37    ICC_Lvalue_Transformation,
38    ICC_Lvalue_Transformation,
39    ICC_Qualification_Adjustment,
40    ICC_Promotion,
41    ICC_Promotion,
42    ICC_Promotion,
43    ICC_Conversion,
44    ICC_Conversion,
45    ICC_Conversion,
46    ICC_Conversion,
47    ICC_Conversion,
48    ICC_Conversion,
49    ICC_Conversion,
50    ICC_Conversion,
51    ICC_Conversion,
52    ICC_Conversion
53  };
54  return Category[(int)Kind];
55}
56
57/// GetConversionRank - Retrieve the implicit conversion rank
58/// corresponding to the given implicit conversion kind.
59ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
60  static const ImplicitConversionRank
61    Rank[(int)ICK_Num_Conversion_Kinds] = {
62    ICR_Exact_Match,
63    ICR_Exact_Match,
64    ICR_Exact_Match,
65    ICR_Exact_Match,
66    ICR_Exact_Match,
67    ICR_Promotion,
68    ICR_Promotion,
69    ICR_Promotion,
70    ICR_Conversion,
71    ICR_Conversion,
72    ICR_Conversion,
73    ICR_Conversion,
74    ICR_Conversion,
75    ICR_Conversion,
76    ICR_Conversion,
77    ICR_Conversion,
78    ICR_Conversion,
79    ICR_Conversion
80  };
81  return Rank[(int)Kind];
82}
83
84/// GetImplicitConversionName - Return the name of this kind of
85/// implicit conversion.
86const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
87  static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
88    "No conversion",
89    "Lvalue-to-rvalue",
90    "Array-to-pointer",
91    "Function-to-pointer",
92    "Qualification",
93    "Integral promotion",
94    "Floating point promotion",
95    "Complex promotion",
96    "Integral conversion",
97    "Floating conversion",
98    "Complex conversion",
99    "Floating-integral conversion",
100    "Complex-real conversion",
101    "Pointer conversion",
102    "Pointer-to-member conversion",
103    "Boolean conversion",
104    "Compatible-types conversion",
105    "Derived-to-base conversion"
106  };
107  return Name[Kind];
108}
109
110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113  First = ICK_Identity;
114  Second = ICK_Identity;
115  Third = ICK_Identity;
116  Deprecated = false;
117  ReferenceBinding = false;
118  DirectBinding = false;
119  RRefBinding = false;
120  CopyConstructor = 0;
121}
122
123/// getRank - Retrieve the rank of this standard conversion sequence
124/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
125/// implicit conversions.
126ImplicitConversionRank StandardConversionSequence::getRank() const {
127  ImplicitConversionRank Rank = ICR_Exact_Match;
128  if  (GetConversionRank(First) > Rank)
129    Rank = GetConversionRank(First);
130  if  (GetConversionRank(Second) > Rank)
131    Rank = GetConversionRank(Second);
132  if  (GetConversionRank(Third) > Rank)
133    Rank = GetConversionRank(Third);
134  return Rank;
135}
136
137/// isPointerConversionToBool - Determines whether this conversion is
138/// a conversion of a pointer or pointer-to-member to bool. This is
139/// used as part of the ranking of standard conversion sequences
140/// (C++ 13.3.3.2p4).
141bool StandardConversionSequence::isPointerConversionToBool() const
142{
143  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
144  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
145
146  // Note that FromType has not necessarily been transformed by the
147  // array-to-pointer or function-to-pointer implicit conversions, so
148  // check for their presence as well as checking whether FromType is
149  // a pointer.
150  if (ToType->isBooleanType() &&
151      (FromType->isPointerType() || FromType->isBlockPointerType() ||
152       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
153    return true;
154
155  return false;
156}
157
158/// isPointerConversionToVoidPointer - Determines whether this
159/// conversion is a conversion of a pointer to a void pointer. This is
160/// used as part of the ranking of standard conversion sequences (C++
161/// 13.3.3.2p4).
162bool
163StandardConversionSequence::
164isPointerConversionToVoidPointer(ASTContext& Context) const
165{
166  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169  // Note that FromType has not necessarily been transformed by the
170  // array-to-pointer implicit conversion, so check for its presence
171  // and redo the conversion to get a pointer.
172  if (First == ICK_Array_To_Pointer)
173    FromType = Context.getArrayDecayedType(FromType);
174
175  if (Second == ICK_Pointer_Conversion)
176    if (const PointerType* ToPtrType = ToType->getAsPointerType())
177      return ToPtrType->getPointeeType()->isVoidType();
178
179  return false;
180}
181
182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185  bool PrintedSomething = false;
186  if (First != ICK_Identity) {
187    fprintf(stderr, "%s", GetImplicitConversionName(First));
188    PrintedSomething = true;
189  }
190
191  if (Second != ICK_Identity) {
192    if (PrintedSomething) {
193      fprintf(stderr, " -> ");
194    }
195    fprintf(stderr, "%s", GetImplicitConversionName(Second));
196
197    if (CopyConstructor) {
198      fprintf(stderr, " (by copy constructor)");
199    } else if (DirectBinding) {
200      fprintf(stderr, " (direct reference binding)");
201    } else if (ReferenceBinding) {
202      fprintf(stderr, " (reference binding)");
203    }
204    PrintedSomething = true;
205  }
206
207  if (Third != ICK_Identity) {
208    if (PrintedSomething) {
209      fprintf(stderr, " -> ");
210    }
211    fprintf(stderr, "%s", GetImplicitConversionName(Third));
212    PrintedSomething = true;
213  }
214
215  if (!PrintedSomething) {
216    fprintf(stderr, "No conversions required");
217  }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223  if (Before.First || Before.Second || Before.Third) {
224    Before.DebugPrint();
225    fprintf(stderr, " -> ");
226  }
227  fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
228  if (After.First || After.Second || After.Third) {
229    fprintf(stderr, " -> ");
230    After.DebugPrint();
231  }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237  switch (ConversionKind) {
238  case StandardConversion:
239    fprintf(stderr, "Standard conversion: ");
240    Standard.DebugPrint();
241    break;
242  case UserDefinedConversion:
243    fprintf(stderr, "User-defined conversion: ");
244    UserDefined.DebugPrint();
245    break;
246  case EllipsisConversion:
247    fprintf(stderr, "Ellipsis conversion");
248    break;
249  case BadConversion:
250    fprintf(stderr, "Bad conversion");
251    break;
252  }
253
254  fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
263// FunctionDecl that New cannot be overloaded with.
264//
265// Example: Given the following input:
266//
267//   void f(int, float); // #1
268//   void f(int, int); // #2
269//   int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
272// so IsOverload will not be used.
273//
274// When we process #2, Old is a FunctionDecl for #1.  By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287                 OverloadedFunctionDecl::function_iterator& MatchedDecl)
288{
289  if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
290    // Is this new function an overload of every function in the
291    // overload set?
292    OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
293                                           FuncEnd = Ovl->function_end();
294    for (; Func != FuncEnd; ++Func) {
295      if (!IsOverload(New, *Func, MatchedDecl)) {
296        MatchedDecl = Func;
297        return false;
298      }
299    }
300
301    // This function overloads every function in the overload set.
302    return true;
303  } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
304    // Is the function New an overload of the function Old?
305    QualType OldQType = Context.getCanonicalType(Old->getType());
306    QualType NewQType = Context.getCanonicalType(New->getType());
307
308    // Compare the signatures (C++ 1.3.10) of the two functions to
309    // determine whether they are overloads. If we find any mismatch
310    // in the signature, they are overloads.
311
312    // If either of these functions is a K&R-style function (no
313    // prototype), then we consider them to have matching signatures.
314    if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
315        isa<FunctionNoProtoType>(NewQType.getTypePtr()))
316      return false;
317
318    FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType.getTypePtr());
319    FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType.getTypePtr());
320
321    // The signature of a function includes the types of its
322    // parameters (C++ 1.3.10), which includes the presence or absence
323    // of the ellipsis; see C++ DR 357).
324    if (OldQType != NewQType &&
325        (OldType->getNumArgs() != NewType->getNumArgs() ||
326         OldType->isVariadic() != NewType->isVariadic() ||
327         !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
328                     NewType->arg_type_begin())))
329      return true;
330
331    // If the function is a class member, its signature includes the
332    // cv-qualifiers (if any) on the function itself.
333    //
334    // As part of this, also check whether one of the member functions
335    // is static, in which case they are not overloads (C++
336    // 13.1p2). While not part of the definition of the signature,
337    // this check is important to determine whether these functions
338    // can be overloaded.
339    CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
340    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
341    if (OldMethod && NewMethod &&
342        !OldMethod->isStatic() && !NewMethod->isStatic() &&
343        OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
344      return true;
345
346    // The signatures match; this is not an overload.
347    return false;
348  } else {
349    // (C++ 13p1):
350    //   Only function declarations can be overloaded; object and type
351    //   declarations cannot be overloaded.
352    return false;
353  }
354}
355
356/// TryImplicitConversion - Attempt to perform an implicit conversion
357/// from the given expression (Expr) to the given type (ToType). This
358/// function returns an implicit conversion sequence that can be used
359/// to perform the initialization. Given
360///
361///   void f(float f);
362///   void g(int i) { f(i); }
363///
364/// this routine would produce an implicit conversion sequence to
365/// describe the initialization of f from i, which will be a standard
366/// conversion sequence containing an lvalue-to-rvalue conversion (C++
367/// 4.1) followed by a floating-integral conversion (C++ 4.9).
368//
369/// Note that this routine only determines how the conversion can be
370/// performed; it does not actually perform the conversion. As such,
371/// it will not produce any diagnostics if no conversion is available,
372/// but will instead return an implicit conversion sequence of kind
373/// "BadConversion".
374///
375/// If @p SuppressUserConversions, then user-defined conversions are
376/// not permitted.
377/// If @p AllowExplicit, then explicit user-defined conversions are
378/// permitted.
379ImplicitConversionSequence
380Sema::TryImplicitConversion(Expr* From, QualType ToType,
381                            bool SuppressUserConversions,
382                            bool AllowExplicit)
383{
384  ImplicitConversionSequence ICS;
385  if (IsStandardConversion(From, ToType, ICS.Standard))
386    ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
387  else if (getLangOptions().CPlusPlus &&
388           IsUserDefinedConversion(From, ToType, ICS.UserDefined,
389                                   !SuppressUserConversions, AllowExplicit)) {
390    ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
391    // C++ [over.ics.user]p4:
392    //   A conversion of an expression of class type to the same class
393    //   type is given Exact Match rank, and a conversion of an
394    //   expression of class type to a base class of that type is
395    //   given Conversion rank, in spite of the fact that a copy
396    //   constructor (i.e., a user-defined conversion function) is
397    //   called for those cases.
398    if (CXXConstructorDecl *Constructor
399          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
400      QualType FromCanon
401        = Context.getCanonicalType(From->getType().getUnqualifiedType());
402      QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
403      if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
404        // Turn this into a "standard" conversion sequence, so that it
405        // gets ranked with standard conversion sequences.
406        ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
407        ICS.Standard.setAsIdentityConversion();
408        ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
409        ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
410        ICS.Standard.CopyConstructor = Constructor;
411        if (ToCanon != FromCanon)
412          ICS.Standard.Second = ICK_Derived_To_Base;
413      }
414    }
415
416    // C++ [over.best.ics]p4:
417    //   However, when considering the argument of a user-defined
418    //   conversion function that is a candidate by 13.3.1.3 when
419    //   invoked for the copying of the temporary in the second step
420    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
421    //   13.3.1.6 in all cases, only standard conversion sequences and
422    //   ellipsis conversion sequences are allowed.
423    if (SuppressUserConversions &&
424        ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
425      ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
426  } else
427    ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
428
429  return ICS;
430}
431
432/// IsStandardConversion - Determines whether there is a standard
433/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
434/// expression From to the type ToType. Standard conversion sequences
435/// only consider non-class types; for conversions that involve class
436/// types, use TryImplicitConversion. If a conversion exists, SCS will
437/// contain the standard conversion sequence required to perform this
438/// conversion and this routine will return true. Otherwise, this
439/// routine will return false and the value of SCS is unspecified.
440bool
441Sema::IsStandardConversion(Expr* From, QualType ToType,
442                           StandardConversionSequence &SCS)
443{
444  QualType FromType = From->getType();
445
446  // Standard conversions (C++ [conv])
447  SCS.setAsIdentityConversion();
448  SCS.Deprecated = false;
449  SCS.IncompatibleObjC = false;
450  SCS.FromTypePtr = FromType.getAsOpaquePtr();
451  SCS.CopyConstructor = 0;
452
453  // There are no standard conversions for class types in C++, so
454  // abort early. When overloading in C, however, we do permit
455  if (FromType->isRecordType() || ToType->isRecordType()) {
456    if (getLangOptions().CPlusPlus)
457      return false;
458
459    // When we're overloading in C, we allow, as standard conversions,
460  }
461
462  // The first conversion can be an lvalue-to-rvalue conversion,
463  // array-to-pointer conversion, or function-to-pointer conversion
464  // (C++ 4p1).
465
466  // Lvalue-to-rvalue conversion (C++ 4.1):
467  //   An lvalue (3.10) of a non-function, non-array type T can be
468  //   converted to an rvalue.
469  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
470  if (argIsLvalue == Expr::LV_Valid &&
471      !FromType->isFunctionType() && !FromType->isArrayType() &&
472      Context.getCanonicalType(FromType) != Context.OverloadTy) {
473    SCS.First = ICK_Lvalue_To_Rvalue;
474
475    // If T is a non-class type, the type of the rvalue is the
476    // cv-unqualified version of T. Otherwise, the type of the rvalue
477    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
478    // just strip the qualifiers because they don't matter.
479
480    // FIXME: Doesn't see through to qualifiers behind a typedef!
481    FromType = FromType.getUnqualifiedType();
482  }
483  // Array-to-pointer conversion (C++ 4.2)
484  else if (FromType->isArrayType()) {
485    SCS.First = ICK_Array_To_Pointer;
486
487    // An lvalue or rvalue of type "array of N T" or "array of unknown
488    // bound of T" can be converted to an rvalue of type "pointer to
489    // T" (C++ 4.2p1).
490    FromType = Context.getArrayDecayedType(FromType);
491
492    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
493      // This conversion is deprecated. (C++ D.4).
494      SCS.Deprecated = true;
495
496      // For the purpose of ranking in overload resolution
497      // (13.3.3.1.1), this conversion is considered an
498      // array-to-pointer conversion followed by a qualification
499      // conversion (4.4). (C++ 4.2p2)
500      SCS.Second = ICK_Identity;
501      SCS.Third = ICK_Qualification;
502      SCS.ToTypePtr = ToType.getAsOpaquePtr();
503      return true;
504    }
505  }
506  // Function-to-pointer conversion (C++ 4.3).
507  else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
508    SCS.First = ICK_Function_To_Pointer;
509
510    // An lvalue of function type T can be converted to an rvalue of
511    // type "pointer to T." The result is a pointer to the
512    // function. (C++ 4.3p1).
513    FromType = Context.getPointerType(FromType);
514  }
515  // Address of overloaded function (C++ [over.over]).
516  else if (FunctionDecl *Fn
517             = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
518    SCS.First = ICK_Function_To_Pointer;
519
520    // We were able to resolve the address of the overloaded function,
521    // so we can convert to the type of that function.
522    FromType = Fn->getType();
523    if (ToType->isLValueReferenceType())
524      FromType = Context.getLValueReferenceType(FromType);
525    else if (ToType->isRValueReferenceType())
526      FromType = Context.getRValueReferenceType(FromType);
527    else if (ToType->isMemberPointerType()) {
528      // Resolve address only succeeds if both sides are member pointers,
529      // but it doesn't have to be the same class. See DR 247.
530      // Note that this means that the type of &Derived::fn can be
531      // Ret (Base::*)(Args) if the fn overload actually found is from the
532      // base class, even if it was brought into the derived class via a
533      // using declaration. The standard isn't clear on this issue at all.
534      CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
535      FromType = Context.getMemberPointerType(FromType,
536                    Context.getTypeDeclType(M->getParent()).getTypePtr());
537    } else
538      FromType = Context.getPointerType(FromType);
539  }
540  // We don't require any conversions for the first step.
541  else {
542    SCS.First = ICK_Identity;
543  }
544
545  // The second conversion can be an integral promotion, floating
546  // point promotion, integral conversion, floating point conversion,
547  // floating-integral conversion, pointer conversion,
548  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
549  // For overloading in C, this can also be a "compatible-type"
550  // conversion.
551  bool IncompatibleObjC = false;
552  if (Context.hasSameUnqualifiedType(FromType, ToType)) {
553    // The unqualified versions of the types are the same: there's no
554    // conversion to do.
555    SCS.Second = ICK_Identity;
556  }
557  // Integral promotion (C++ 4.5).
558  else if (IsIntegralPromotion(From, FromType, ToType)) {
559    SCS.Second = ICK_Integral_Promotion;
560    FromType = ToType.getUnqualifiedType();
561  }
562  // Floating point promotion (C++ 4.6).
563  else if (IsFloatingPointPromotion(FromType, ToType)) {
564    SCS.Second = ICK_Floating_Promotion;
565    FromType = ToType.getUnqualifiedType();
566  }
567  // Complex promotion (Clang extension)
568  else if (IsComplexPromotion(FromType, ToType)) {
569    SCS.Second = ICK_Complex_Promotion;
570    FromType = ToType.getUnqualifiedType();
571  }
572  // Integral conversions (C++ 4.7).
573  // FIXME: isIntegralType shouldn't be true for enums in C++.
574  else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
575           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
576    SCS.Second = ICK_Integral_Conversion;
577    FromType = ToType.getUnqualifiedType();
578  }
579  // Floating point conversions (C++ 4.8).
580  else if (FromType->isFloatingType() && ToType->isFloatingType()) {
581    SCS.Second = ICK_Floating_Conversion;
582    FromType = ToType.getUnqualifiedType();
583  }
584  // Complex conversions (C99 6.3.1.6)
585  else if (FromType->isComplexType() && ToType->isComplexType()) {
586    SCS.Second = ICK_Complex_Conversion;
587    FromType = ToType.getUnqualifiedType();
588  }
589  // Floating-integral conversions (C++ 4.9).
590  // FIXME: isIntegralType shouldn't be true for enums in C++.
591  else if ((FromType->isFloatingType() &&
592            ToType->isIntegralType() && !ToType->isBooleanType() &&
593                                        !ToType->isEnumeralType()) ||
594           ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
595            ToType->isFloatingType())) {
596    SCS.Second = ICK_Floating_Integral;
597    FromType = ToType.getUnqualifiedType();
598  }
599  // Complex-real conversions (C99 6.3.1.7)
600  else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
601           (ToType->isComplexType() && FromType->isArithmeticType())) {
602    SCS.Second = ICK_Complex_Real;
603    FromType = ToType.getUnqualifiedType();
604  }
605  // Pointer conversions (C++ 4.10).
606  else if (IsPointerConversion(From, FromType, ToType, FromType,
607                               IncompatibleObjC)) {
608    SCS.Second = ICK_Pointer_Conversion;
609    SCS.IncompatibleObjC = IncompatibleObjC;
610  }
611  // Pointer to member conversions (4.11).
612  else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
613    SCS.Second = ICK_Pointer_Member;
614  }
615  // Boolean conversions (C++ 4.12).
616  else if (ToType->isBooleanType() &&
617           (FromType->isArithmeticType() ||
618            FromType->isEnumeralType() ||
619            FromType->isPointerType() ||
620            FromType->isBlockPointerType() ||
621            FromType->isMemberPointerType())) {
622    SCS.Second = ICK_Boolean_Conversion;
623    FromType = Context.BoolTy;
624  }
625  // Compatible conversions (Clang extension for C function overloading)
626  else if (!getLangOptions().CPlusPlus &&
627           Context.typesAreCompatible(ToType, FromType)) {
628    SCS.Second = ICK_Compatible_Conversion;
629  } else {
630    // No second conversion required.
631    SCS.Second = ICK_Identity;
632  }
633
634  QualType CanonFrom;
635  QualType CanonTo;
636  // The third conversion can be a qualification conversion (C++ 4p1).
637  if (IsQualificationConversion(FromType, ToType)) {
638    SCS.Third = ICK_Qualification;
639    FromType = ToType;
640    CanonFrom = Context.getCanonicalType(FromType);
641    CanonTo = Context.getCanonicalType(ToType);
642  } else {
643    // No conversion required
644    SCS.Third = ICK_Identity;
645
646    // C++ [over.best.ics]p6:
647    //   [...] Any difference in top-level cv-qualification is
648    //   subsumed by the initialization itself and does not constitute
649    //   a conversion. [...]
650    CanonFrom = Context.getCanonicalType(FromType);
651    CanonTo = Context.getCanonicalType(ToType);
652    if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
653        CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
654      FromType = ToType;
655      CanonFrom = CanonTo;
656    }
657  }
658
659  // If we have not converted the argument type to the parameter type,
660  // this is a bad conversion sequence.
661  if (CanonFrom != CanonTo)
662    return false;
663
664  SCS.ToTypePtr = FromType.getAsOpaquePtr();
665  return true;
666}
667
668/// IsIntegralPromotion - Determines whether the conversion from the
669/// expression From (whose potentially-adjusted type is FromType) to
670/// ToType is an integral promotion (C++ 4.5). If so, returns true and
671/// sets PromotedType to the promoted type.
672bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
673{
674  const BuiltinType *To = ToType->getAsBuiltinType();
675  // All integers are built-in.
676  if (!To) {
677    return false;
678  }
679
680  // An rvalue of type char, signed char, unsigned char, short int, or
681  // unsigned short int can be converted to an rvalue of type int if
682  // int can represent all the values of the source type; otherwise,
683  // the source rvalue can be converted to an rvalue of type unsigned
684  // int (C++ 4.5p1).
685  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
686    if (// We can promote any signed, promotable integer type to an int
687        (FromType->isSignedIntegerType() ||
688         // We can promote any unsigned integer type whose size is
689         // less than int to an int.
690         (!FromType->isSignedIntegerType() &&
691          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
692      return To->getKind() == BuiltinType::Int;
693    }
694
695    return To->getKind() == BuiltinType::UInt;
696  }
697
698  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
699  // can be converted to an rvalue of the first of the following types
700  // that can represent all the values of its underlying type: int,
701  // unsigned int, long, or unsigned long (C++ 4.5p2).
702  if ((FromType->isEnumeralType() || FromType->isWideCharType())
703      && ToType->isIntegerType()) {
704    // Determine whether the type we're converting from is signed or
705    // unsigned.
706    bool FromIsSigned;
707    uint64_t FromSize = Context.getTypeSize(FromType);
708    if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
709      QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
710      FromIsSigned = UnderlyingType->isSignedIntegerType();
711    } else {
712      // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
713      FromIsSigned = true;
714    }
715
716    // The types we'll try to promote to, in the appropriate
717    // order. Try each of these types.
718    QualType PromoteTypes[6] = {
719      Context.IntTy, Context.UnsignedIntTy,
720      Context.LongTy, Context.UnsignedLongTy ,
721      Context.LongLongTy, Context.UnsignedLongLongTy
722    };
723    for (int Idx = 0; Idx < 6; ++Idx) {
724      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
725      if (FromSize < ToSize ||
726          (FromSize == ToSize &&
727           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
728        // We found the type that we can promote to. If this is the
729        // type we wanted, we have a promotion. Otherwise, no
730        // promotion.
731        return Context.getCanonicalType(ToType).getUnqualifiedType()
732          == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
733      }
734    }
735  }
736
737  // An rvalue for an integral bit-field (9.6) can be converted to an
738  // rvalue of type int if int can represent all the values of the
739  // bit-field; otherwise, it can be converted to unsigned int if
740  // unsigned int can represent all the values of the bit-field. If
741  // the bit-field is larger yet, no integral promotion applies to
742  // it. If the bit-field has an enumerated type, it is treated as any
743  // other value of that type for promotion purposes (C++ 4.5p3).
744  // FIXME: We should delay checking of bit-fields until we actually
745  // perform the conversion.
746  if (MemberExpr *MemRef = dyn_cast_or_null<MemberExpr>(From)) {
747    using llvm::APSInt;
748    if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
749      APSInt BitWidth;
750      if (MemberDecl->isBitField() &&
751          FromType->isIntegralType() && !FromType->isEnumeralType() &&
752          From->isIntegerConstantExpr(BitWidth, Context)) {
753        APSInt ToSize(Context.getTypeSize(ToType));
754
755        // Are we promoting to an int from a bitfield that fits in an int?
756        if (BitWidth < ToSize ||
757            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
758          return To->getKind() == BuiltinType::Int;
759        }
760
761        // Are we promoting to an unsigned int from an unsigned bitfield
762        // that fits into an unsigned int?
763        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
764          return To->getKind() == BuiltinType::UInt;
765        }
766
767        return false;
768      }
769    }
770  }
771
772  // An rvalue of type bool can be converted to an rvalue of type int,
773  // with false becoming zero and true becoming one (C++ 4.5p4).
774  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
775    return true;
776  }
777
778  return false;
779}
780
781/// IsFloatingPointPromotion - Determines whether the conversion from
782/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
783/// returns true and sets PromotedType to the promoted type.
784bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
785{
786  /// An rvalue of type float can be converted to an rvalue of type
787  /// double. (C++ 4.6p1).
788  if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
789    if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
790      if (FromBuiltin->getKind() == BuiltinType::Float &&
791          ToBuiltin->getKind() == BuiltinType::Double)
792        return true;
793
794      // C99 6.3.1.5p1:
795      //   When a float is promoted to double or long double, or a
796      //   double is promoted to long double [...].
797      if (!getLangOptions().CPlusPlus &&
798          (FromBuiltin->getKind() == BuiltinType::Float ||
799           FromBuiltin->getKind() == BuiltinType::Double) &&
800          (ToBuiltin->getKind() == BuiltinType::LongDouble))
801        return true;
802    }
803
804  return false;
805}
806
807/// \brief Determine if a conversion is a complex promotion.
808///
809/// A complex promotion is defined as a complex -> complex conversion
810/// where the conversion between the underlying real types is a
811/// floating-point or integral promotion.
812bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
813  const ComplexType *FromComplex = FromType->getAsComplexType();
814  if (!FromComplex)
815    return false;
816
817  const ComplexType *ToComplex = ToType->getAsComplexType();
818  if (!ToComplex)
819    return false;
820
821  return IsFloatingPointPromotion(FromComplex->getElementType(),
822                                  ToComplex->getElementType()) ||
823    IsIntegralPromotion(0, FromComplex->getElementType(),
824                        ToComplex->getElementType());
825}
826
827/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
828/// the pointer type FromPtr to a pointer to type ToPointee, with the
829/// same type qualifiers as FromPtr has on its pointee type. ToType,
830/// if non-empty, will be a pointer to ToType that may or may not have
831/// the right set of qualifiers on its pointee.
832static QualType
833BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
834                                   QualType ToPointee, QualType ToType,
835                                   ASTContext &Context) {
836  QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
837  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
838  unsigned Quals = CanonFromPointee.getCVRQualifiers();
839
840  // Exact qualifier match -> return the pointer type we're converting to.
841  if (CanonToPointee.getCVRQualifiers() == Quals) {
842    // ToType is exactly what we need. Return it.
843    if (ToType.getTypePtr())
844      return ToType;
845
846    // Build a pointer to ToPointee. It has the right qualifiers
847    // already.
848    return Context.getPointerType(ToPointee);
849  }
850
851  // Just build a canonical type that has the right qualifiers.
852  return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
853}
854
855/// IsPointerConversion - Determines whether the conversion of the
856/// expression From, which has the (possibly adjusted) type FromType,
857/// can be converted to the type ToType via a pointer conversion (C++
858/// 4.10). If so, returns true and places the converted type (that
859/// might differ from ToType in its cv-qualifiers at some level) into
860/// ConvertedType.
861///
862/// This routine also supports conversions to and from block pointers
863/// and conversions with Objective-C's 'id', 'id<protocols...>', and
864/// pointers to interfaces. FIXME: Once we've determined the
865/// appropriate overloading rules for Objective-C, we may want to
866/// split the Objective-C checks into a different routine; however,
867/// GCC seems to consider all of these conversions to be pointer
868/// conversions, so for now they live here. IncompatibleObjC will be
869/// set if the conversion is an allowed Objective-C conversion that
870/// should result in a warning.
871bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
872                               QualType& ConvertedType,
873                               bool &IncompatibleObjC)
874{
875  IncompatibleObjC = false;
876  if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
877    return true;
878
879  // Conversion from a null pointer constant to any Objective-C pointer type.
880  if (Context.isObjCObjectPointerType(ToType) &&
881      From->isNullPointerConstant(Context)) {
882    ConvertedType = ToType;
883    return true;
884  }
885
886  // Blocks: Block pointers can be converted to void*.
887  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
888      ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
889    ConvertedType = ToType;
890    return true;
891  }
892  // Blocks: A null pointer constant can be converted to a block
893  // pointer type.
894  if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
895    ConvertedType = ToType;
896    return true;
897  }
898
899  const PointerType* ToTypePtr = ToType->getAsPointerType();
900  if (!ToTypePtr)
901    return false;
902
903  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
904  if (From->isNullPointerConstant(Context)) {
905    ConvertedType = ToType;
906    return true;
907  }
908
909  // Beyond this point, both types need to be pointers.
910  const PointerType *FromTypePtr = FromType->getAsPointerType();
911  if (!FromTypePtr)
912    return false;
913
914  QualType FromPointeeType = FromTypePtr->getPointeeType();
915  QualType ToPointeeType = ToTypePtr->getPointeeType();
916
917  // An rvalue of type "pointer to cv T," where T is an object type,
918  // can be converted to an rvalue of type "pointer to cv void" (C++
919  // 4.10p2).
920  if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
921    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
922                                                       ToPointeeType,
923                                                       ToType, Context);
924    return true;
925  }
926
927  // When we're overloading in C, we allow a special kind of pointer
928  // conversion for compatible-but-not-identical pointee types.
929  if (!getLangOptions().CPlusPlus &&
930      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
931    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
932                                                       ToPointeeType,
933                                                       ToType, Context);
934    return true;
935  }
936
937  // C++ [conv.ptr]p3:
938  //
939  //   An rvalue of type "pointer to cv D," where D is a class type,
940  //   can be converted to an rvalue of type "pointer to cv B," where
941  //   B is a base class (clause 10) of D. If B is an inaccessible
942  //   (clause 11) or ambiguous (10.2) base class of D, a program that
943  //   necessitates this conversion is ill-formed. The result of the
944  //   conversion is a pointer to the base class sub-object of the
945  //   derived class object. The null pointer value is converted to
946  //   the null pointer value of the destination type.
947  //
948  // Note that we do not check for ambiguity or inaccessibility
949  // here. That is handled by CheckPointerConversion.
950  if (getLangOptions().CPlusPlus &&
951      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
952      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
953    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
954                                                       ToPointeeType,
955                                                       ToType, Context);
956    return true;
957  }
958
959  return false;
960}
961
962/// isObjCPointerConversion - Determines whether this is an
963/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
964/// with the same arguments and return values.
965bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
966                                   QualType& ConvertedType,
967                                   bool &IncompatibleObjC) {
968  if (!getLangOptions().ObjC1)
969    return false;
970
971  // Conversions with Objective-C's id<...>.
972  if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
973      ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
974    ConvertedType = ToType;
975    return true;
976  }
977
978  // Beyond this point, both types need to be pointers or block pointers.
979  QualType ToPointeeType;
980  const PointerType* ToTypePtr = ToType->getAsPointerType();
981  if (ToTypePtr)
982    ToPointeeType = ToTypePtr->getPointeeType();
983  else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
984    ToPointeeType = ToBlockPtr->getPointeeType();
985  else
986    return false;
987
988  QualType FromPointeeType;
989  const PointerType *FromTypePtr = FromType->getAsPointerType();
990  if (FromTypePtr)
991    FromPointeeType = FromTypePtr->getPointeeType();
992  else if (const BlockPointerType *FromBlockPtr
993             = FromType->getAsBlockPointerType())
994    FromPointeeType = FromBlockPtr->getPointeeType();
995  else
996    return false;
997
998  // Objective C++: We're able to convert from a pointer to an
999  // interface to a pointer to a different interface.
1000  const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
1001  const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1002  if (FromIface && ToIface &&
1003      Context.canAssignObjCInterfaces(ToIface, FromIface)) {
1004    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1005                                                       ToPointeeType,
1006                                                       ToType, Context);
1007    return true;
1008  }
1009
1010  if (FromIface && ToIface &&
1011      Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1012    // Okay: this is some kind of implicit downcast of Objective-C
1013    // interfaces, which is permitted. However, we're going to
1014    // complain about it.
1015    IncompatibleObjC = true;
1016    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1017                                                       ToPointeeType,
1018                                                       ToType, Context);
1019    return true;
1020  }
1021
1022  // Objective C++: We're able to convert between "id" and a pointer
1023  // to any interface (in both directions).
1024  if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1025      || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
1026    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1027                                                       ToPointeeType,
1028                                                       ToType, Context);
1029    return true;
1030  }
1031
1032  // Objective C++: Allow conversions between the Objective-C "id" and
1033  // "Class", in either direction.
1034  if ((Context.isObjCIdStructType(FromPointeeType) &&
1035       Context.isObjCClassStructType(ToPointeeType)) ||
1036      (Context.isObjCClassStructType(FromPointeeType) &&
1037       Context.isObjCIdStructType(ToPointeeType))) {
1038    ConvertedType = ToType;
1039    return true;
1040  }
1041
1042  // If we have pointers to pointers, recursively check whether this
1043  // is an Objective-C conversion.
1044  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1045      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1046                              IncompatibleObjC)) {
1047    // We always complain about this conversion.
1048    IncompatibleObjC = true;
1049    ConvertedType = ToType;
1050    return true;
1051  }
1052
1053  // If we have pointers to functions or blocks, check whether the only
1054  // differences in the argument and result types are in Objective-C
1055  // pointer conversions. If so, we permit the conversion (but
1056  // complain about it).
1057  const FunctionProtoType *FromFunctionType
1058    = FromPointeeType->getAsFunctionProtoType();
1059  const FunctionProtoType *ToFunctionType
1060    = ToPointeeType->getAsFunctionProtoType();
1061  if (FromFunctionType && ToFunctionType) {
1062    // If the function types are exactly the same, this isn't an
1063    // Objective-C pointer conversion.
1064    if (Context.getCanonicalType(FromPointeeType)
1065          == Context.getCanonicalType(ToPointeeType))
1066      return false;
1067
1068    // Perform the quick checks that will tell us whether these
1069    // function types are obviously different.
1070    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1071        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1072        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1073      return false;
1074
1075    bool HasObjCConversion = false;
1076    if (Context.getCanonicalType(FromFunctionType->getResultType())
1077          == Context.getCanonicalType(ToFunctionType->getResultType())) {
1078      // Okay, the types match exactly. Nothing to do.
1079    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1080                                       ToFunctionType->getResultType(),
1081                                       ConvertedType, IncompatibleObjC)) {
1082      // Okay, we have an Objective-C pointer conversion.
1083      HasObjCConversion = true;
1084    } else {
1085      // Function types are too different. Abort.
1086      return false;
1087    }
1088
1089    // Check argument types.
1090    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1091         ArgIdx != NumArgs; ++ArgIdx) {
1092      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1093      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1094      if (Context.getCanonicalType(FromArgType)
1095            == Context.getCanonicalType(ToArgType)) {
1096        // Okay, the types match exactly. Nothing to do.
1097      } else if (isObjCPointerConversion(FromArgType, ToArgType,
1098                                         ConvertedType, IncompatibleObjC)) {
1099        // Okay, we have an Objective-C pointer conversion.
1100        HasObjCConversion = true;
1101      } else {
1102        // Argument types are too different. Abort.
1103        return false;
1104      }
1105    }
1106
1107    if (HasObjCConversion) {
1108      // We had an Objective-C conversion. Allow this pointer
1109      // conversion, but complain about it.
1110      ConvertedType = ToType;
1111      IncompatibleObjC = true;
1112      return true;
1113    }
1114  }
1115
1116  return false;
1117}
1118
1119/// CheckPointerConversion - Check the pointer conversion from the
1120/// expression From to the type ToType. This routine checks for
1121/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1122/// conversions for which IsPointerConversion has already returned
1123/// true. It returns true and produces a diagnostic if there was an
1124/// error, or returns false otherwise.
1125bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1126  QualType FromType = From->getType();
1127
1128  if (const PointerType *FromPtrType = FromType->getAsPointerType())
1129    if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
1130      QualType FromPointeeType = FromPtrType->getPointeeType(),
1131               ToPointeeType   = ToPtrType->getPointeeType();
1132
1133      // Objective-C++ conversions are always okay.
1134      // FIXME: We should have a different class of conversions for
1135      // the Objective-C++ implicit conversions.
1136      if (Context.isObjCIdStructType(FromPointeeType) ||
1137          Context.isObjCIdStructType(ToPointeeType) ||
1138          Context.isObjCClassStructType(FromPointeeType) ||
1139          Context.isObjCClassStructType(ToPointeeType))
1140        return false;
1141
1142      if (FromPointeeType->isRecordType() &&
1143          ToPointeeType->isRecordType()) {
1144        // We must have a derived-to-base conversion. Check an
1145        // ambiguous or inaccessible conversion.
1146        return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1147                                            From->getExprLoc(),
1148                                            From->getSourceRange());
1149      }
1150    }
1151
1152  return false;
1153}
1154
1155/// IsMemberPointerConversion - Determines whether the conversion of the
1156/// expression From, which has the (possibly adjusted) type FromType, can be
1157/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1158/// If so, returns true and places the converted type (that might differ from
1159/// ToType in its cv-qualifiers at some level) into ConvertedType.
1160bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1161                                     QualType ToType, QualType &ConvertedType)
1162{
1163  const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1164  if (!ToTypePtr)
1165    return false;
1166
1167  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1168  if (From->isNullPointerConstant(Context)) {
1169    ConvertedType = ToType;
1170    return true;
1171  }
1172
1173  // Otherwise, both types have to be member pointers.
1174  const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1175  if (!FromTypePtr)
1176    return false;
1177
1178  // A pointer to member of B can be converted to a pointer to member of D,
1179  // where D is derived from B (C++ 4.11p2).
1180  QualType FromClass(FromTypePtr->getClass(), 0);
1181  QualType ToClass(ToTypePtr->getClass(), 0);
1182  // FIXME: What happens when these are dependent? Is this function even called?
1183
1184  if (IsDerivedFrom(ToClass, FromClass)) {
1185    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1186                                                 ToClass.getTypePtr());
1187    return true;
1188  }
1189
1190  return false;
1191}
1192
1193/// CheckMemberPointerConversion - Check the member pointer conversion from the
1194/// expression From to the type ToType. This routine checks for ambiguous or
1195/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1196/// for which IsMemberPointerConversion has already returned true. It returns
1197/// true and produces a diagnostic if there was an error, or returns false
1198/// otherwise.
1199bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1200  QualType FromType = From->getType();
1201  const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1202  if (!FromPtrType)
1203    return false;
1204
1205  const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1206  assert(ToPtrType && "No member pointer cast has a target type "
1207                      "that is not a member pointer.");
1208
1209  QualType FromClass = QualType(FromPtrType->getClass(), 0);
1210  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
1211
1212  // FIXME: What about dependent types?
1213  assert(FromClass->isRecordType() && "Pointer into non-class.");
1214  assert(ToClass->isRecordType() && "Pointer into non-class.");
1215
1216  BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1217                  /*DetectVirtual=*/true);
1218  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1219  assert(DerivationOkay &&
1220         "Should not have been called if derivation isn't OK.");
1221  (void)DerivationOkay;
1222
1223  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1224                                  getUnqualifiedType())) {
1225    // Derivation is ambiguous. Redo the check to find the exact paths.
1226    Paths.clear();
1227    Paths.setRecordingPaths(true);
1228    bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1229    assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1230    (void)StillOkay;
1231
1232    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1233    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1234      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1235    return true;
1236  }
1237
1238  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1239    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1240      << FromClass << ToClass << QualType(VBase, 0)
1241      << From->getSourceRange();
1242    return true;
1243  }
1244
1245  return false;
1246}
1247
1248/// IsQualificationConversion - Determines whether the conversion from
1249/// an rvalue of type FromType to ToType is a qualification conversion
1250/// (C++ 4.4).
1251bool
1252Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1253{
1254  FromType = Context.getCanonicalType(FromType);
1255  ToType = Context.getCanonicalType(ToType);
1256
1257  // If FromType and ToType are the same type, this is not a
1258  // qualification conversion.
1259  if (FromType == ToType)
1260    return false;
1261
1262  // (C++ 4.4p4):
1263  //   A conversion can add cv-qualifiers at levels other than the first
1264  //   in multi-level pointers, subject to the following rules: [...]
1265  bool PreviousToQualsIncludeConst = true;
1266  bool UnwrappedAnyPointer = false;
1267  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1268    // Within each iteration of the loop, we check the qualifiers to
1269    // determine if this still looks like a qualification
1270    // conversion. Then, if all is well, we unwrap one more level of
1271    // pointers or pointers-to-members and do it all again
1272    // until there are no more pointers or pointers-to-members left to
1273    // unwrap.
1274    UnwrappedAnyPointer = true;
1275
1276    //   -- for every j > 0, if const is in cv 1,j then const is in cv
1277    //      2,j, and similarly for volatile.
1278    if (!ToType.isAtLeastAsQualifiedAs(FromType))
1279      return false;
1280
1281    //   -- if the cv 1,j and cv 2,j are different, then const is in
1282    //      every cv for 0 < k < j.
1283    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1284        && !PreviousToQualsIncludeConst)
1285      return false;
1286
1287    // Keep track of whether all prior cv-qualifiers in the "to" type
1288    // include const.
1289    PreviousToQualsIncludeConst
1290      = PreviousToQualsIncludeConst && ToType.isConstQualified();
1291  }
1292
1293  // We are left with FromType and ToType being the pointee types
1294  // after unwrapping the original FromType and ToType the same number
1295  // of types. If we unwrapped any pointers, and if FromType and
1296  // ToType have the same unqualified type (since we checked
1297  // qualifiers above), then this is a qualification conversion.
1298  return UnwrappedAnyPointer &&
1299    FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1300}
1301
1302/// Determines whether there is a user-defined conversion sequence
1303/// (C++ [over.ics.user]) that converts expression From to the type
1304/// ToType. If such a conversion exists, User will contain the
1305/// user-defined conversion sequence that performs such a conversion
1306/// and this routine will return true. Otherwise, this routine returns
1307/// false and User is unspecified.
1308///
1309/// \param AllowConversionFunctions true if the conversion should
1310/// consider conversion functions at all. If false, only constructors
1311/// will be considered.
1312///
1313/// \param AllowExplicit  true if the conversion should consider C++0x
1314/// "explicit" conversion functions as well as non-explicit conversion
1315/// functions (C++0x [class.conv.fct]p2).
1316bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1317                                   UserDefinedConversionSequence& User,
1318                                   bool AllowConversionFunctions,
1319                                   bool AllowExplicit)
1320{
1321  OverloadCandidateSet CandidateSet;
1322  if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1323    if (CXXRecordDecl *ToRecordDecl
1324          = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1325      // C++ [over.match.ctor]p1:
1326      //   When objects of class type are direct-initialized (8.5), or
1327      //   copy-initialized from an expression of the same or a
1328      //   derived class type (8.5), overload resolution selects the
1329      //   constructor. [...] For copy-initialization, the candidate
1330      //   functions are all the converting constructors (12.3.1) of
1331      //   that class. The argument list is the expression-list within
1332      //   the parentheses of the initializer.
1333      DeclarationName ConstructorName
1334        = Context.DeclarationNames.getCXXConstructorName(
1335                          Context.getCanonicalType(ToType).getUnqualifiedType());
1336      DeclContext::lookup_iterator Con, ConEnd;
1337      for (llvm::tie(Con, ConEnd)
1338             = ToRecordDecl->lookup(Context, ConstructorName);
1339           Con != ConEnd; ++Con) {
1340        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1341        if (Constructor->isConvertingConstructor())
1342          AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1343                               /*SuppressUserConversions=*/true);
1344      }
1345    }
1346  }
1347
1348  if (!AllowConversionFunctions) {
1349    // Don't allow any conversion functions to enter the overload set.
1350  } else if (const RecordType *FromRecordType
1351               = From->getType()->getAsRecordType()) {
1352    if (CXXRecordDecl *FromRecordDecl
1353          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1354      // Add all of the conversion functions as candidates.
1355      // FIXME: Look for conversions in base classes!
1356      OverloadedFunctionDecl *Conversions
1357        = FromRecordDecl->getConversionFunctions();
1358      for (OverloadedFunctionDecl::function_iterator Func
1359             = Conversions->function_begin();
1360           Func != Conversions->function_end(); ++Func) {
1361        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1362        if (AllowExplicit || !Conv->isExplicit())
1363          AddConversionCandidate(Conv, From, ToType, CandidateSet);
1364      }
1365    }
1366  }
1367
1368  OverloadCandidateSet::iterator Best;
1369  switch (BestViableFunction(CandidateSet, Best)) {
1370    case OR_Success:
1371      // Record the standard conversion we used and the conversion function.
1372      if (CXXConstructorDecl *Constructor
1373            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1374        // C++ [over.ics.user]p1:
1375        //   If the user-defined conversion is specified by a
1376        //   constructor (12.3.1), the initial standard conversion
1377        //   sequence converts the source type to the type required by
1378        //   the argument of the constructor.
1379        //
1380        // FIXME: What about ellipsis conversions?
1381        QualType ThisType = Constructor->getThisType(Context);
1382        User.Before = Best->Conversions[0].Standard;
1383        User.ConversionFunction = Constructor;
1384        User.After.setAsIdentityConversion();
1385        User.After.FromTypePtr
1386          = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1387        User.After.ToTypePtr = ToType.getAsOpaquePtr();
1388        return true;
1389      } else if (CXXConversionDecl *Conversion
1390                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
1391        // C++ [over.ics.user]p1:
1392        //
1393        //   [...] If the user-defined conversion is specified by a
1394        //   conversion function (12.3.2), the initial standard
1395        //   conversion sequence converts the source type to the
1396        //   implicit object parameter of the conversion function.
1397        User.Before = Best->Conversions[0].Standard;
1398        User.ConversionFunction = Conversion;
1399
1400        // C++ [over.ics.user]p2:
1401        //   The second standard conversion sequence converts the
1402        //   result of the user-defined conversion to the target type
1403        //   for the sequence. Since an implicit conversion sequence
1404        //   is an initialization, the special rules for
1405        //   initialization by user-defined conversion apply when
1406        //   selecting the best user-defined conversion for a
1407        //   user-defined conversion sequence (see 13.3.3 and
1408        //   13.3.3.1).
1409        User.After = Best->FinalConversion;
1410        return true;
1411      } else {
1412        assert(false && "Not a constructor or conversion function?");
1413        return false;
1414      }
1415
1416    case OR_No_Viable_Function:
1417    case OR_Deleted:
1418      // No conversion here! We're done.
1419      return false;
1420
1421    case OR_Ambiguous:
1422      // FIXME: See C++ [over.best.ics]p10 for the handling of
1423      // ambiguous conversion sequences.
1424      return false;
1425    }
1426
1427  return false;
1428}
1429
1430/// CompareImplicitConversionSequences - Compare two implicit
1431/// conversion sequences to determine whether one is better than the
1432/// other or if they are indistinguishable (C++ 13.3.3.2).
1433ImplicitConversionSequence::CompareKind
1434Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1435                                         const ImplicitConversionSequence& ICS2)
1436{
1437  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1438  // conversion sequences (as defined in 13.3.3.1)
1439  //   -- a standard conversion sequence (13.3.3.1.1) is a better
1440  //      conversion sequence than a user-defined conversion sequence or
1441  //      an ellipsis conversion sequence, and
1442  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1443  //      conversion sequence than an ellipsis conversion sequence
1444  //      (13.3.3.1.3).
1445  //
1446  if (ICS1.ConversionKind < ICS2.ConversionKind)
1447    return ImplicitConversionSequence::Better;
1448  else if (ICS2.ConversionKind < ICS1.ConversionKind)
1449    return ImplicitConversionSequence::Worse;
1450
1451  // Two implicit conversion sequences of the same form are
1452  // indistinguishable conversion sequences unless one of the
1453  // following rules apply: (C++ 13.3.3.2p3):
1454  if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1455    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1456  else if (ICS1.ConversionKind ==
1457             ImplicitConversionSequence::UserDefinedConversion) {
1458    // User-defined conversion sequence U1 is a better conversion
1459    // sequence than another user-defined conversion sequence U2 if
1460    // they contain the same user-defined conversion function or
1461    // constructor and if the second standard conversion sequence of
1462    // U1 is better than the second standard conversion sequence of
1463    // U2 (C++ 13.3.3.2p3).
1464    if (ICS1.UserDefined.ConversionFunction ==
1465          ICS2.UserDefined.ConversionFunction)
1466      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1467                                                ICS2.UserDefined.After);
1468  }
1469
1470  return ImplicitConversionSequence::Indistinguishable;
1471}
1472
1473/// CompareStandardConversionSequences - Compare two standard
1474/// conversion sequences to determine whether one is better than the
1475/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1476ImplicitConversionSequence::CompareKind
1477Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1478                                         const StandardConversionSequence& SCS2)
1479{
1480  // Standard conversion sequence S1 is a better conversion sequence
1481  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1482
1483  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1484  //     sequences in the canonical form defined by 13.3.3.1.1,
1485  //     excluding any Lvalue Transformation; the identity conversion
1486  //     sequence is considered to be a subsequence of any
1487  //     non-identity conversion sequence) or, if not that,
1488  if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1489    // Neither is a proper subsequence of the other. Do nothing.
1490    ;
1491  else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1492           (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1493           (SCS1.Second == ICK_Identity &&
1494            SCS1.Third == ICK_Identity))
1495    // SCS1 is a proper subsequence of SCS2.
1496    return ImplicitConversionSequence::Better;
1497  else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1498           (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1499           (SCS2.Second == ICK_Identity &&
1500            SCS2.Third == ICK_Identity))
1501    // SCS2 is a proper subsequence of SCS1.
1502    return ImplicitConversionSequence::Worse;
1503
1504  //  -- the rank of S1 is better than the rank of S2 (by the rules
1505  //     defined below), or, if not that,
1506  ImplicitConversionRank Rank1 = SCS1.getRank();
1507  ImplicitConversionRank Rank2 = SCS2.getRank();
1508  if (Rank1 < Rank2)
1509    return ImplicitConversionSequence::Better;
1510  else if (Rank2 < Rank1)
1511    return ImplicitConversionSequence::Worse;
1512
1513  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1514  // are indistinguishable unless one of the following rules
1515  // applies:
1516
1517  //   A conversion that is not a conversion of a pointer, or
1518  //   pointer to member, to bool is better than another conversion
1519  //   that is such a conversion.
1520  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1521    return SCS2.isPointerConversionToBool()
1522             ? ImplicitConversionSequence::Better
1523             : ImplicitConversionSequence::Worse;
1524
1525  // C++ [over.ics.rank]p4b2:
1526  //
1527  //   If class B is derived directly or indirectly from class A,
1528  //   conversion of B* to A* is better than conversion of B* to
1529  //   void*, and conversion of A* to void* is better than conversion
1530  //   of B* to void*.
1531  bool SCS1ConvertsToVoid
1532    = SCS1.isPointerConversionToVoidPointer(Context);
1533  bool SCS2ConvertsToVoid
1534    = SCS2.isPointerConversionToVoidPointer(Context);
1535  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1536    // Exactly one of the conversion sequences is a conversion to
1537    // a void pointer; it's the worse conversion.
1538    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1539                              : ImplicitConversionSequence::Worse;
1540  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1541    // Neither conversion sequence converts to a void pointer; compare
1542    // their derived-to-base conversions.
1543    if (ImplicitConversionSequence::CompareKind DerivedCK
1544          = CompareDerivedToBaseConversions(SCS1, SCS2))
1545      return DerivedCK;
1546  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1547    // Both conversion sequences are conversions to void
1548    // pointers. Compare the source types to determine if there's an
1549    // inheritance relationship in their sources.
1550    QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1551    QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1552
1553    // Adjust the types we're converting from via the array-to-pointer
1554    // conversion, if we need to.
1555    if (SCS1.First == ICK_Array_To_Pointer)
1556      FromType1 = Context.getArrayDecayedType(FromType1);
1557    if (SCS2.First == ICK_Array_To_Pointer)
1558      FromType2 = Context.getArrayDecayedType(FromType2);
1559
1560    QualType FromPointee1
1561      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1562    QualType FromPointee2
1563      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1564
1565    if (IsDerivedFrom(FromPointee2, FromPointee1))
1566      return ImplicitConversionSequence::Better;
1567    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1568      return ImplicitConversionSequence::Worse;
1569
1570    // Objective-C++: If one interface is more specific than the
1571    // other, it is the better one.
1572    const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1573    const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1574    if (FromIface1 && FromIface1) {
1575      if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1576        return ImplicitConversionSequence::Better;
1577      else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1578        return ImplicitConversionSequence::Worse;
1579    }
1580  }
1581
1582  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1583  // bullet 3).
1584  if (ImplicitConversionSequence::CompareKind QualCK
1585        = CompareQualificationConversions(SCS1, SCS2))
1586    return QualCK;
1587
1588  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1589    // C++0x [over.ics.rank]p3b4:
1590    //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1591    //      implicit object parameter of a non-static member function declared
1592    //      without a ref-qualifier, and S1 binds an rvalue reference to an
1593    //      rvalue and S2 binds an lvalue reference.
1594    // FIXME: We don't know if we're dealing with the implicit object parameter,
1595    // or if the member function in this case has a ref qualifier.
1596    // (Of course, we don't have ref qualifiers yet.)
1597    if (SCS1.RRefBinding != SCS2.RRefBinding)
1598      return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1599                              : ImplicitConversionSequence::Worse;
1600
1601    // C++ [over.ics.rank]p3b4:
1602    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1603    //      which the references refer are the same type except for
1604    //      top-level cv-qualifiers, and the type to which the reference
1605    //      initialized by S2 refers is more cv-qualified than the type
1606    //      to which the reference initialized by S1 refers.
1607    QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1608    QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1609    T1 = Context.getCanonicalType(T1);
1610    T2 = Context.getCanonicalType(T2);
1611    if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1612      if (T2.isMoreQualifiedThan(T1))
1613        return ImplicitConversionSequence::Better;
1614      else if (T1.isMoreQualifiedThan(T2))
1615        return ImplicitConversionSequence::Worse;
1616    }
1617  }
1618
1619  return ImplicitConversionSequence::Indistinguishable;
1620}
1621
1622/// CompareQualificationConversions - Compares two standard conversion
1623/// sequences to determine whether they can be ranked based on their
1624/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1625ImplicitConversionSequence::CompareKind
1626Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1627                                      const StandardConversionSequence& SCS2)
1628{
1629  // C++ 13.3.3.2p3:
1630  //  -- S1 and S2 differ only in their qualification conversion and
1631  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1632  //     cv-qualification signature of type T1 is a proper subset of
1633  //     the cv-qualification signature of type T2, and S1 is not the
1634  //     deprecated string literal array-to-pointer conversion (4.2).
1635  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1636      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1637    return ImplicitConversionSequence::Indistinguishable;
1638
1639  // FIXME: the example in the standard doesn't use a qualification
1640  // conversion (!)
1641  QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1642  QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1643  T1 = Context.getCanonicalType(T1);
1644  T2 = Context.getCanonicalType(T2);
1645
1646  // If the types are the same, we won't learn anything by unwrapped
1647  // them.
1648  if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1649    return ImplicitConversionSequence::Indistinguishable;
1650
1651  ImplicitConversionSequence::CompareKind Result
1652    = ImplicitConversionSequence::Indistinguishable;
1653  while (UnwrapSimilarPointerTypes(T1, T2)) {
1654    // Within each iteration of the loop, we check the qualifiers to
1655    // determine if this still looks like a qualification
1656    // conversion. Then, if all is well, we unwrap one more level of
1657    // pointers or pointers-to-members and do it all again
1658    // until there are no more pointers or pointers-to-members left
1659    // to unwrap. This essentially mimics what
1660    // IsQualificationConversion does, but here we're checking for a
1661    // strict subset of qualifiers.
1662    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1663      // The qualifiers are the same, so this doesn't tell us anything
1664      // about how the sequences rank.
1665      ;
1666    else if (T2.isMoreQualifiedThan(T1)) {
1667      // T1 has fewer qualifiers, so it could be the better sequence.
1668      if (Result == ImplicitConversionSequence::Worse)
1669        // Neither has qualifiers that are a subset of the other's
1670        // qualifiers.
1671        return ImplicitConversionSequence::Indistinguishable;
1672
1673      Result = ImplicitConversionSequence::Better;
1674    } else if (T1.isMoreQualifiedThan(T2)) {
1675      // T2 has fewer qualifiers, so it could be the better sequence.
1676      if (Result == ImplicitConversionSequence::Better)
1677        // Neither has qualifiers that are a subset of the other's
1678        // qualifiers.
1679        return ImplicitConversionSequence::Indistinguishable;
1680
1681      Result = ImplicitConversionSequence::Worse;
1682    } else {
1683      // Qualifiers are disjoint.
1684      return ImplicitConversionSequence::Indistinguishable;
1685    }
1686
1687    // If the types after this point are equivalent, we're done.
1688    if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1689      break;
1690  }
1691
1692  // Check that the winning standard conversion sequence isn't using
1693  // the deprecated string literal array to pointer conversion.
1694  switch (Result) {
1695  case ImplicitConversionSequence::Better:
1696    if (SCS1.Deprecated)
1697      Result = ImplicitConversionSequence::Indistinguishable;
1698    break;
1699
1700  case ImplicitConversionSequence::Indistinguishable:
1701    break;
1702
1703  case ImplicitConversionSequence::Worse:
1704    if (SCS2.Deprecated)
1705      Result = ImplicitConversionSequence::Indistinguishable;
1706    break;
1707  }
1708
1709  return Result;
1710}
1711
1712/// CompareDerivedToBaseConversions - Compares two standard conversion
1713/// sequences to determine whether they can be ranked based on their
1714/// various kinds of derived-to-base conversions (C++
1715/// [over.ics.rank]p4b3).  As part of these checks, we also look at
1716/// conversions between Objective-C interface types.
1717ImplicitConversionSequence::CompareKind
1718Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1719                                      const StandardConversionSequence& SCS2) {
1720  QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1721  QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1722  QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1723  QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1724
1725  // Adjust the types we're converting from via the array-to-pointer
1726  // conversion, if we need to.
1727  if (SCS1.First == ICK_Array_To_Pointer)
1728    FromType1 = Context.getArrayDecayedType(FromType1);
1729  if (SCS2.First == ICK_Array_To_Pointer)
1730    FromType2 = Context.getArrayDecayedType(FromType2);
1731
1732  // Canonicalize all of the types.
1733  FromType1 = Context.getCanonicalType(FromType1);
1734  ToType1 = Context.getCanonicalType(ToType1);
1735  FromType2 = Context.getCanonicalType(FromType2);
1736  ToType2 = Context.getCanonicalType(ToType2);
1737
1738  // C++ [over.ics.rank]p4b3:
1739  //
1740  //   If class B is derived directly or indirectly from class A and
1741  //   class C is derived directly or indirectly from B,
1742  //
1743  // For Objective-C, we let A, B, and C also be Objective-C
1744  // interfaces.
1745
1746  // Compare based on pointer conversions.
1747  if (SCS1.Second == ICK_Pointer_Conversion &&
1748      SCS2.Second == ICK_Pointer_Conversion &&
1749      /*FIXME: Remove if Objective-C id conversions get their own rank*/
1750      FromType1->isPointerType() && FromType2->isPointerType() &&
1751      ToType1->isPointerType() && ToType2->isPointerType()) {
1752    QualType FromPointee1
1753      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1754    QualType ToPointee1
1755      = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1756    QualType FromPointee2
1757      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1758    QualType ToPointee2
1759      = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1760
1761    const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1762    const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1763    const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1764    const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1765
1766    //   -- conversion of C* to B* is better than conversion of C* to A*,
1767    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1768      if (IsDerivedFrom(ToPointee1, ToPointee2))
1769        return ImplicitConversionSequence::Better;
1770      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1771        return ImplicitConversionSequence::Worse;
1772
1773      if (ToIface1 && ToIface2) {
1774        if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1775          return ImplicitConversionSequence::Better;
1776        else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1777          return ImplicitConversionSequence::Worse;
1778      }
1779    }
1780
1781    //   -- conversion of B* to A* is better than conversion of C* to A*,
1782    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1783      if (IsDerivedFrom(FromPointee2, FromPointee1))
1784        return ImplicitConversionSequence::Better;
1785      else if (IsDerivedFrom(FromPointee1, FromPointee2))
1786        return ImplicitConversionSequence::Worse;
1787
1788      if (FromIface1 && FromIface2) {
1789        if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1790          return ImplicitConversionSequence::Better;
1791        else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1792          return ImplicitConversionSequence::Worse;
1793      }
1794    }
1795  }
1796
1797  // Compare based on reference bindings.
1798  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1799      SCS1.Second == ICK_Derived_To_Base) {
1800    //   -- binding of an expression of type C to a reference of type
1801    //      B& is better than binding an expression of type C to a
1802    //      reference of type A&,
1803    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1804        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1805      if (IsDerivedFrom(ToType1, ToType2))
1806        return ImplicitConversionSequence::Better;
1807      else if (IsDerivedFrom(ToType2, ToType1))
1808        return ImplicitConversionSequence::Worse;
1809    }
1810
1811    //   -- binding of an expression of type B to a reference of type
1812    //      A& is better than binding an expression of type C to a
1813    //      reference of type A&,
1814    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1815        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1816      if (IsDerivedFrom(FromType2, FromType1))
1817        return ImplicitConversionSequence::Better;
1818      else if (IsDerivedFrom(FromType1, FromType2))
1819        return ImplicitConversionSequence::Worse;
1820    }
1821  }
1822
1823
1824  // FIXME: conversion of A::* to B::* is better than conversion of
1825  // A::* to C::*,
1826
1827  // FIXME: conversion of B::* to C::* is better than conversion of
1828  // A::* to C::*, and
1829
1830  if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1831      SCS1.Second == ICK_Derived_To_Base) {
1832    //   -- conversion of C to B is better than conversion of C to A,
1833    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1834        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1835      if (IsDerivedFrom(ToType1, ToType2))
1836        return ImplicitConversionSequence::Better;
1837      else if (IsDerivedFrom(ToType2, ToType1))
1838        return ImplicitConversionSequence::Worse;
1839    }
1840
1841    //   -- conversion of B to A is better than conversion of C to A.
1842    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1843        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1844      if (IsDerivedFrom(FromType2, FromType1))
1845        return ImplicitConversionSequence::Better;
1846      else if (IsDerivedFrom(FromType1, FromType2))
1847        return ImplicitConversionSequence::Worse;
1848    }
1849  }
1850
1851  return ImplicitConversionSequence::Indistinguishable;
1852}
1853
1854/// TryCopyInitialization - Try to copy-initialize a value of type
1855/// ToType from the expression From. Return the implicit conversion
1856/// sequence required to pass this argument, which may be a bad
1857/// conversion sequence (meaning that the argument cannot be passed to
1858/// a parameter of this type). If @p SuppressUserConversions, then we
1859/// do not permit any user-defined conversion sequences.
1860ImplicitConversionSequence
1861Sema::TryCopyInitialization(Expr *From, QualType ToType,
1862                            bool SuppressUserConversions) {
1863  if (ToType->isReferenceType()) {
1864    ImplicitConversionSequence ICS;
1865    CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
1866    return ICS;
1867  } else {
1868    return TryImplicitConversion(From, ToType, SuppressUserConversions);
1869  }
1870}
1871
1872/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1873/// type ToType. Returns true (and emits a diagnostic) if there was
1874/// an error, returns false if the initialization succeeded.
1875bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1876                                     const char* Flavor) {
1877  if (!getLangOptions().CPlusPlus) {
1878    // In C, argument passing is the same as performing an assignment.
1879    QualType FromType = From->getType();
1880    AssignConvertType ConvTy =
1881      CheckSingleAssignmentConstraints(ToType, From);
1882
1883    return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1884                                    FromType, From, Flavor);
1885  }
1886
1887  if (ToType->isReferenceType())
1888    return CheckReferenceInit(From, ToType);
1889
1890  if (!PerformImplicitConversion(From, ToType, Flavor))
1891    return false;
1892
1893  return Diag(From->getSourceRange().getBegin(),
1894              diag::err_typecheck_convert_incompatible)
1895    << ToType << From->getType() << Flavor << From->getSourceRange();
1896}
1897
1898/// TryObjectArgumentInitialization - Try to initialize the object
1899/// parameter of the given member function (@c Method) from the
1900/// expression @p From.
1901ImplicitConversionSequence
1902Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1903  QualType ClassType = Context.getTypeDeclType(Method->getParent());
1904  unsigned MethodQuals = Method->getTypeQualifiers();
1905  QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1906
1907  // Set up the conversion sequence as a "bad" conversion, to allow us
1908  // to exit early.
1909  ImplicitConversionSequence ICS;
1910  ICS.Standard.setAsIdentityConversion();
1911  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1912
1913  // We need to have an object of class type.
1914  QualType FromType = From->getType();
1915  if (!FromType->isRecordType())
1916    return ICS;
1917
1918  // The implicit object parmeter is has the type "reference to cv X",
1919  // where X is the class of which the function is a member
1920  // (C++ [over.match.funcs]p4). However, when finding an implicit
1921  // conversion sequence for the argument, we are not allowed to
1922  // create temporaries or perform user-defined conversions
1923  // (C++ [over.match.funcs]p5). We perform a simplified version of
1924  // reference binding here, that allows class rvalues to bind to
1925  // non-constant references.
1926
1927  // First check the qualifiers. We don't care about lvalue-vs-rvalue
1928  // with the implicit object parameter (C++ [over.match.funcs]p5).
1929  QualType FromTypeCanon = Context.getCanonicalType(FromType);
1930  if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1931      !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1932    return ICS;
1933
1934  // Check that we have either the same type or a derived type. It
1935  // affects the conversion rank.
1936  QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1937  if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1938    ICS.Standard.Second = ICK_Identity;
1939  else if (IsDerivedFrom(FromType, ClassType))
1940    ICS.Standard.Second = ICK_Derived_To_Base;
1941  else
1942    return ICS;
1943
1944  // Success. Mark this as a reference binding.
1945  ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1946  ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1947  ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1948  ICS.Standard.ReferenceBinding = true;
1949  ICS.Standard.DirectBinding = true;
1950  ICS.Standard.RRefBinding = false;
1951  return ICS;
1952}
1953
1954/// PerformObjectArgumentInitialization - Perform initialization of
1955/// the implicit object parameter for the given Method with the given
1956/// expression.
1957bool
1958Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1959  QualType ImplicitParamType
1960    = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1961  ImplicitConversionSequence ICS
1962    = TryObjectArgumentInitialization(From, Method);
1963  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1964    return Diag(From->getSourceRange().getBegin(),
1965                diag::err_implicit_object_parameter_init)
1966       << ImplicitParamType << From->getType() << From->getSourceRange();
1967
1968  if (ICS.Standard.Second == ICK_Derived_To_Base &&
1969      CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1970                                   From->getSourceRange().getBegin(),
1971                                   From->getSourceRange()))
1972    return true;
1973
1974  ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1975  return false;
1976}
1977
1978/// TryContextuallyConvertToBool - Attempt to contextually convert the
1979/// expression From to bool (C++0x [conv]p3).
1980ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1981  return TryImplicitConversion(From, Context.BoolTy, false, true);
1982}
1983
1984/// PerformContextuallyConvertToBool - Perform a contextual conversion
1985/// of the expression From to bool (C++0x [conv]p3).
1986bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1987  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1988  if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1989    return false;
1990
1991  return Diag(From->getSourceRange().getBegin(),
1992              diag::err_typecheck_bool_condition)
1993    << From->getType() << From->getSourceRange();
1994}
1995
1996/// AddOverloadCandidate - Adds the given function to the set of
1997/// candidate functions, using the given function call arguments.  If
1998/// @p SuppressUserConversions, then don't allow user-defined
1999/// conversions via constructors or conversion operators.
2000void
2001Sema::AddOverloadCandidate(FunctionDecl *Function,
2002                           Expr **Args, unsigned NumArgs,
2003                           OverloadCandidateSet& CandidateSet,
2004                           bool SuppressUserConversions)
2005{
2006  const FunctionProtoType* Proto
2007    = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
2008  assert(Proto && "Functions without a prototype cannot be overloaded");
2009  assert(!isa<CXXConversionDecl>(Function) &&
2010         "Use AddConversionCandidate for conversion functions");
2011
2012  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2013    // If we get here, it's because we're calling a member function
2014    // that is named without a member access expression (e.g.,
2015    // "this->f") that was either written explicitly or created
2016    // implicitly. This can happen with a qualified call to a member
2017    // function, e.g., X::f(). We use a NULL object as the implied
2018    // object argument (C++ [over.call.func]p3).
2019    AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2020                       SuppressUserConversions);
2021    return;
2022  }
2023
2024
2025  // Add this candidate
2026  CandidateSet.push_back(OverloadCandidate());
2027  OverloadCandidate& Candidate = CandidateSet.back();
2028  Candidate.Function = Function;
2029  Candidate.Viable = true;
2030  Candidate.IsSurrogate = false;
2031  Candidate.IgnoreObjectArgument = false;
2032
2033  unsigned NumArgsInProto = Proto->getNumArgs();
2034
2035  // (C++ 13.3.2p2): A candidate function having fewer than m
2036  // parameters is viable only if it has an ellipsis in its parameter
2037  // list (8.3.5).
2038  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2039    Candidate.Viable = false;
2040    return;
2041  }
2042
2043  // (C++ 13.3.2p2): A candidate function having more than m parameters
2044  // is viable only if the (m+1)st parameter has a default argument
2045  // (8.3.6). For the purposes of overload resolution, the
2046  // parameter list is truncated on the right, so that there are
2047  // exactly m parameters.
2048  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2049  if (NumArgs < MinRequiredArgs) {
2050    // Not enough arguments.
2051    Candidate.Viable = false;
2052    return;
2053  }
2054
2055  // Determine the implicit conversion sequences for each of the
2056  // arguments.
2057  Candidate.Conversions.resize(NumArgs);
2058  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2059    if (ArgIdx < NumArgsInProto) {
2060      // (C++ 13.3.2p3): for F to be a viable function, there shall
2061      // exist for each argument an implicit conversion sequence
2062      // (13.3.3.1) that converts that argument to the corresponding
2063      // parameter of F.
2064      QualType ParamType = Proto->getArgType(ArgIdx);
2065      Candidate.Conversions[ArgIdx]
2066        = TryCopyInitialization(Args[ArgIdx], ParamType,
2067                                SuppressUserConversions);
2068      if (Candidate.Conversions[ArgIdx].ConversionKind
2069            == ImplicitConversionSequence::BadConversion) {
2070        Candidate.Viable = false;
2071        break;
2072      }
2073    } else {
2074      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2075      // argument for which there is no corresponding parameter is
2076      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2077      Candidate.Conversions[ArgIdx].ConversionKind
2078        = ImplicitConversionSequence::EllipsisConversion;
2079    }
2080  }
2081}
2082
2083/// \brief Add all of the function declarations in the given function set to
2084/// the overload canddiate set.
2085void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2086                                 Expr **Args, unsigned NumArgs,
2087                                 OverloadCandidateSet& CandidateSet,
2088                                 bool SuppressUserConversions) {
2089  for (FunctionSet::const_iterator F = Functions.begin(),
2090                                FEnd = Functions.end();
2091       F != FEnd; ++F)
2092    AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2093                         SuppressUserConversions);
2094}
2095
2096/// AddMethodCandidate - Adds the given C++ member function to the set
2097/// of candidate functions, using the given function call arguments
2098/// and the object argument (@c Object). For example, in a call
2099/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2100/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2101/// allow user-defined conversions via constructors or conversion
2102/// operators.
2103void
2104Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2105                         Expr **Args, unsigned NumArgs,
2106                         OverloadCandidateSet& CandidateSet,
2107                         bool SuppressUserConversions)
2108{
2109  const FunctionProtoType* Proto
2110    = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
2111  assert(Proto && "Methods without a prototype cannot be overloaded");
2112  assert(!isa<CXXConversionDecl>(Method) &&
2113         "Use AddConversionCandidate for conversion functions");
2114
2115  // Add this candidate
2116  CandidateSet.push_back(OverloadCandidate());
2117  OverloadCandidate& Candidate = CandidateSet.back();
2118  Candidate.Function = Method;
2119  Candidate.IsSurrogate = false;
2120  Candidate.IgnoreObjectArgument = false;
2121
2122  unsigned NumArgsInProto = Proto->getNumArgs();
2123
2124  // (C++ 13.3.2p2): A candidate function having fewer than m
2125  // parameters is viable only if it has an ellipsis in its parameter
2126  // list (8.3.5).
2127  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2128    Candidate.Viable = false;
2129    return;
2130  }
2131
2132  // (C++ 13.3.2p2): A candidate function having more than m parameters
2133  // is viable only if the (m+1)st parameter has a default argument
2134  // (8.3.6). For the purposes of overload resolution, the
2135  // parameter list is truncated on the right, so that there are
2136  // exactly m parameters.
2137  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2138  if (NumArgs < MinRequiredArgs) {
2139    // Not enough arguments.
2140    Candidate.Viable = false;
2141    return;
2142  }
2143
2144  Candidate.Viable = true;
2145  Candidate.Conversions.resize(NumArgs + 1);
2146
2147  if (Method->isStatic() || !Object)
2148    // The implicit object argument is ignored.
2149    Candidate.IgnoreObjectArgument = true;
2150  else {
2151    // Determine the implicit conversion sequence for the object
2152    // parameter.
2153    Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2154    if (Candidate.Conversions[0].ConversionKind
2155          == ImplicitConversionSequence::BadConversion) {
2156      Candidate.Viable = false;
2157      return;
2158    }
2159  }
2160
2161  // Determine the implicit conversion sequences for each of the
2162  // arguments.
2163  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2164    if (ArgIdx < NumArgsInProto) {
2165      // (C++ 13.3.2p3): for F to be a viable function, there shall
2166      // exist for each argument an implicit conversion sequence
2167      // (13.3.3.1) that converts that argument to the corresponding
2168      // parameter of F.
2169      QualType ParamType = Proto->getArgType(ArgIdx);
2170      Candidate.Conversions[ArgIdx + 1]
2171        = TryCopyInitialization(Args[ArgIdx], ParamType,
2172                                SuppressUserConversions);
2173      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2174            == ImplicitConversionSequence::BadConversion) {
2175        Candidate.Viable = false;
2176        break;
2177      }
2178    } else {
2179      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2180      // argument for which there is no corresponding parameter is
2181      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2182      Candidate.Conversions[ArgIdx + 1].ConversionKind
2183        = ImplicitConversionSequence::EllipsisConversion;
2184    }
2185  }
2186}
2187
2188/// AddConversionCandidate - Add a C++ conversion function as a
2189/// candidate in the candidate set (C++ [over.match.conv],
2190/// C++ [over.match.copy]). From is the expression we're converting from,
2191/// and ToType is the type that we're eventually trying to convert to
2192/// (which may or may not be the same type as the type that the
2193/// conversion function produces).
2194void
2195Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2196                             Expr *From, QualType ToType,
2197                             OverloadCandidateSet& CandidateSet) {
2198  // Add this candidate
2199  CandidateSet.push_back(OverloadCandidate());
2200  OverloadCandidate& Candidate = CandidateSet.back();
2201  Candidate.Function = Conversion;
2202  Candidate.IsSurrogate = false;
2203  Candidate.IgnoreObjectArgument = false;
2204  Candidate.FinalConversion.setAsIdentityConversion();
2205  Candidate.FinalConversion.FromTypePtr
2206    = Conversion->getConversionType().getAsOpaquePtr();
2207  Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2208
2209  // Determine the implicit conversion sequence for the implicit
2210  // object parameter.
2211  Candidate.Viable = true;
2212  Candidate.Conversions.resize(1);
2213  Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
2214
2215  if (Candidate.Conversions[0].ConversionKind
2216      == ImplicitConversionSequence::BadConversion) {
2217    Candidate.Viable = false;
2218    return;
2219  }
2220
2221  // To determine what the conversion from the result of calling the
2222  // conversion function to the type we're eventually trying to
2223  // convert to (ToType), we need to synthesize a call to the
2224  // conversion function and attempt copy initialization from it. This
2225  // makes sure that we get the right semantics with respect to
2226  // lvalues/rvalues and the type. Fortunately, we can allocate this
2227  // call on the stack and we don't need its arguments to be
2228  // well-formed.
2229  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2230                            SourceLocation());
2231  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
2232                                &ConversionRef, false);
2233
2234  // Note that it is safe to allocate CallExpr on the stack here because
2235  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2236  // allocator).
2237  CallExpr Call(Context, &ConversionFn, 0, 0,
2238                Conversion->getConversionType().getNonReferenceType(),
2239                SourceLocation());
2240  ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2241  switch (ICS.ConversionKind) {
2242  case ImplicitConversionSequence::StandardConversion:
2243    Candidate.FinalConversion = ICS.Standard;
2244    break;
2245
2246  case ImplicitConversionSequence::BadConversion:
2247    Candidate.Viable = false;
2248    break;
2249
2250  default:
2251    assert(false &&
2252           "Can only end up with a standard conversion sequence or failure");
2253  }
2254}
2255
2256/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2257/// converts the given @c Object to a function pointer via the
2258/// conversion function @c Conversion, and then attempts to call it
2259/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2260/// the type of function that we'll eventually be calling.
2261void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2262                                 const FunctionProtoType *Proto,
2263                                 Expr *Object, Expr **Args, unsigned NumArgs,
2264                                 OverloadCandidateSet& CandidateSet) {
2265  CandidateSet.push_back(OverloadCandidate());
2266  OverloadCandidate& Candidate = CandidateSet.back();
2267  Candidate.Function = 0;
2268  Candidate.Surrogate = Conversion;
2269  Candidate.Viable = true;
2270  Candidate.IsSurrogate = true;
2271  Candidate.IgnoreObjectArgument = false;
2272  Candidate.Conversions.resize(NumArgs + 1);
2273
2274  // Determine the implicit conversion sequence for the implicit
2275  // object parameter.
2276  ImplicitConversionSequence ObjectInit
2277    = TryObjectArgumentInitialization(Object, Conversion);
2278  if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2279    Candidate.Viable = false;
2280    return;
2281  }
2282
2283  // The first conversion is actually a user-defined conversion whose
2284  // first conversion is ObjectInit's standard conversion (which is
2285  // effectively a reference binding). Record it as such.
2286  Candidate.Conversions[0].ConversionKind
2287    = ImplicitConversionSequence::UserDefinedConversion;
2288  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2289  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2290  Candidate.Conversions[0].UserDefined.After
2291    = Candidate.Conversions[0].UserDefined.Before;
2292  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2293
2294  // Find the
2295  unsigned NumArgsInProto = Proto->getNumArgs();
2296
2297  // (C++ 13.3.2p2): A candidate function having fewer than m
2298  // parameters is viable only if it has an ellipsis in its parameter
2299  // list (8.3.5).
2300  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2301    Candidate.Viable = false;
2302    return;
2303  }
2304
2305  // Function types don't have any default arguments, so just check if
2306  // we have enough arguments.
2307  if (NumArgs < NumArgsInProto) {
2308    // Not enough arguments.
2309    Candidate.Viable = false;
2310    return;
2311  }
2312
2313  // Determine the implicit conversion sequences for each of the
2314  // arguments.
2315  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2316    if (ArgIdx < NumArgsInProto) {
2317      // (C++ 13.3.2p3): for F to be a viable function, there shall
2318      // exist for each argument an implicit conversion sequence
2319      // (13.3.3.1) that converts that argument to the corresponding
2320      // parameter of F.
2321      QualType ParamType = Proto->getArgType(ArgIdx);
2322      Candidate.Conversions[ArgIdx + 1]
2323        = TryCopyInitialization(Args[ArgIdx], ParamType,
2324                                /*SuppressUserConversions=*/false);
2325      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2326            == ImplicitConversionSequence::BadConversion) {
2327        Candidate.Viable = false;
2328        break;
2329      }
2330    } else {
2331      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2332      // argument for which there is no corresponding parameter is
2333      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2334      Candidate.Conversions[ArgIdx + 1].ConversionKind
2335        = ImplicitConversionSequence::EllipsisConversion;
2336    }
2337  }
2338}
2339
2340// FIXME: This will eventually be removed, once we've migrated all of
2341// the operator overloading logic over to the scheme used by binary
2342// operators, which works for template instantiation.
2343void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2344                                 SourceLocation OpLoc,
2345                                 Expr **Args, unsigned NumArgs,
2346                                 OverloadCandidateSet& CandidateSet,
2347                                 SourceRange OpRange) {
2348
2349  FunctionSet Functions;
2350
2351  QualType T1 = Args[0]->getType();
2352  QualType T2;
2353  if (NumArgs > 1)
2354    T2 = Args[1]->getType();
2355
2356  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2357  LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2358  ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2359  AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2360  AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2361  AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2362}
2363
2364/// \brief Add overload candidates for overloaded operators that are
2365/// member functions.
2366///
2367/// Add the overloaded operator candidates that are member functions
2368/// for the operator Op that was used in an operator expression such
2369/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2370/// CandidateSet will store the added overload candidates. (C++
2371/// [over.match.oper]).
2372void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2373                                       SourceLocation OpLoc,
2374                                       Expr **Args, unsigned NumArgs,
2375                                       OverloadCandidateSet& CandidateSet,
2376                                       SourceRange OpRange) {
2377  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2378
2379  // C++ [over.match.oper]p3:
2380  //   For a unary operator @ with an operand of a type whose
2381  //   cv-unqualified version is T1, and for a binary operator @ with
2382  //   a left operand of a type whose cv-unqualified version is T1 and
2383  //   a right operand of a type whose cv-unqualified version is T2,
2384  //   three sets of candidate functions, designated member
2385  //   candidates, non-member candidates and built-in candidates, are
2386  //   constructed as follows:
2387  QualType T1 = Args[0]->getType();
2388  QualType T2;
2389  if (NumArgs > 1)
2390    T2 = Args[1]->getType();
2391
2392  //     -- If T1 is a class type, the set of member candidates is the
2393  //        result of the qualified lookup of T1::operator@
2394  //        (13.3.1.1.1); otherwise, the set of member candidates is
2395  //        empty.
2396  // FIXME: Lookup in base classes, too!
2397  if (const RecordType *T1Rec = T1->getAsRecordType()) {
2398    DeclContext::lookup_const_iterator Oper, OperEnd;
2399    for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(Context, OpName);
2400         Oper != OperEnd; ++Oper)
2401      AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2402                         Args+1, NumArgs - 1, CandidateSet,
2403                         /*SuppressUserConversions=*/false);
2404  }
2405}
2406
2407/// AddBuiltinCandidate - Add a candidate for a built-in
2408/// operator. ResultTy and ParamTys are the result and parameter types
2409/// of the built-in candidate, respectively. Args and NumArgs are the
2410/// arguments being passed to the candidate. IsAssignmentOperator
2411/// should be true when this built-in candidate is an assignment
2412/// operator. NumContextualBoolArguments is the number of arguments
2413/// (at the beginning of the argument list) that will be contextually
2414/// converted to bool.
2415void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2416                               Expr **Args, unsigned NumArgs,
2417                               OverloadCandidateSet& CandidateSet,
2418                               bool IsAssignmentOperator,
2419                               unsigned NumContextualBoolArguments) {
2420  // Add this candidate
2421  CandidateSet.push_back(OverloadCandidate());
2422  OverloadCandidate& Candidate = CandidateSet.back();
2423  Candidate.Function = 0;
2424  Candidate.IsSurrogate = false;
2425  Candidate.IgnoreObjectArgument = false;
2426  Candidate.BuiltinTypes.ResultTy = ResultTy;
2427  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2428    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2429
2430  // Determine the implicit conversion sequences for each of the
2431  // arguments.
2432  Candidate.Viable = true;
2433  Candidate.Conversions.resize(NumArgs);
2434  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2435    // C++ [over.match.oper]p4:
2436    //   For the built-in assignment operators, conversions of the
2437    //   left operand are restricted as follows:
2438    //     -- no temporaries are introduced to hold the left operand, and
2439    //     -- no user-defined conversions are applied to the left
2440    //        operand to achieve a type match with the left-most
2441    //        parameter of a built-in candidate.
2442    //
2443    // We block these conversions by turning off user-defined
2444    // conversions, since that is the only way that initialization of
2445    // a reference to a non-class type can occur from something that
2446    // is not of the same type.
2447    if (ArgIdx < NumContextualBoolArguments) {
2448      assert(ParamTys[ArgIdx] == Context.BoolTy &&
2449             "Contextual conversion to bool requires bool type");
2450      Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2451    } else {
2452      Candidate.Conversions[ArgIdx]
2453        = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2454                                ArgIdx == 0 && IsAssignmentOperator);
2455    }
2456    if (Candidate.Conversions[ArgIdx].ConversionKind
2457        == ImplicitConversionSequence::BadConversion) {
2458      Candidate.Viable = false;
2459      break;
2460    }
2461  }
2462}
2463
2464/// BuiltinCandidateTypeSet - A set of types that will be used for the
2465/// candidate operator functions for built-in operators (C++
2466/// [over.built]). The types are separated into pointer types and
2467/// enumeration types.
2468class BuiltinCandidateTypeSet  {
2469  /// TypeSet - A set of types.
2470  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
2471
2472  /// PointerTypes - The set of pointer types that will be used in the
2473  /// built-in candidates.
2474  TypeSet PointerTypes;
2475
2476  /// EnumerationTypes - The set of enumeration types that will be
2477  /// used in the built-in candidates.
2478  TypeSet EnumerationTypes;
2479
2480  /// Context - The AST context in which we will build the type sets.
2481  ASTContext &Context;
2482
2483  bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2484
2485public:
2486  /// iterator - Iterates through the types that are part of the set.
2487  typedef TypeSet::iterator iterator;
2488
2489  BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2490
2491  void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2492                             bool AllowExplicitConversions);
2493
2494  /// pointer_begin - First pointer type found;
2495  iterator pointer_begin() { return PointerTypes.begin(); }
2496
2497  /// pointer_end - Last pointer type found;
2498  iterator pointer_end() { return PointerTypes.end(); }
2499
2500  /// enumeration_begin - First enumeration type found;
2501  iterator enumeration_begin() { return EnumerationTypes.begin(); }
2502
2503  /// enumeration_end - Last enumeration type found;
2504  iterator enumeration_end() { return EnumerationTypes.end(); }
2505};
2506
2507/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2508/// the set of pointer types along with any more-qualified variants of
2509/// that type. For example, if @p Ty is "int const *", this routine
2510/// will add "int const *", "int const volatile *", "int const
2511/// restrict *", and "int const volatile restrict *" to the set of
2512/// pointer types. Returns true if the add of @p Ty itself succeeded,
2513/// false otherwise.
2514bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2515  // Insert this type.
2516  if (!PointerTypes.insert(Ty))
2517    return false;
2518
2519  if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2520    QualType PointeeTy = PointerTy->getPointeeType();
2521    // FIXME: Optimize this so that we don't keep trying to add the same types.
2522
2523    // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2524    // with all pointer conversions that don't cast away constness?
2525    if (!PointeeTy.isConstQualified())
2526      AddWithMoreQualifiedTypeVariants
2527        (Context.getPointerType(PointeeTy.withConst()));
2528    if (!PointeeTy.isVolatileQualified())
2529      AddWithMoreQualifiedTypeVariants
2530        (Context.getPointerType(PointeeTy.withVolatile()));
2531    if (!PointeeTy.isRestrictQualified())
2532      AddWithMoreQualifiedTypeVariants
2533        (Context.getPointerType(PointeeTy.withRestrict()));
2534  }
2535
2536  return true;
2537}
2538
2539/// AddTypesConvertedFrom - Add each of the types to which the type @p
2540/// Ty can be implicit converted to the given set of @p Types. We're
2541/// primarily interested in pointer types and enumeration types.
2542/// AllowUserConversions is true if we should look at the conversion
2543/// functions of a class type, and AllowExplicitConversions if we
2544/// should also include the explicit conversion functions of a class
2545/// type.
2546void
2547BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2548                                               bool AllowUserConversions,
2549                                               bool AllowExplicitConversions) {
2550  // Only deal with canonical types.
2551  Ty = Context.getCanonicalType(Ty);
2552
2553  // Look through reference types; they aren't part of the type of an
2554  // expression for the purposes of conversions.
2555  if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2556    Ty = RefTy->getPointeeType();
2557
2558  // We don't care about qualifiers on the type.
2559  Ty = Ty.getUnqualifiedType();
2560
2561  if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2562    QualType PointeeTy = PointerTy->getPointeeType();
2563
2564    // Insert our type, and its more-qualified variants, into the set
2565    // of types.
2566    if (!AddWithMoreQualifiedTypeVariants(Ty))
2567      return;
2568
2569    // Add 'cv void*' to our set of types.
2570    if (!Ty->isVoidType()) {
2571      QualType QualVoid
2572        = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2573      AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2574    }
2575
2576    // If this is a pointer to a class type, add pointers to its bases
2577    // (with the same level of cv-qualification as the original
2578    // derived class, of course).
2579    if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2580      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2581      for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2582           Base != ClassDecl->bases_end(); ++Base) {
2583        QualType BaseTy = Context.getCanonicalType(Base->getType());
2584        BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2585
2586        // Add the pointer type, recursively, so that we get all of
2587        // the indirect base classes, too.
2588        AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
2589      }
2590    }
2591  } else if (Ty->isEnumeralType()) {
2592    EnumerationTypes.insert(Ty);
2593  } else if (AllowUserConversions) {
2594    if (const RecordType *TyRec = Ty->getAsRecordType()) {
2595      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2596      // FIXME: Visit conversion functions in the base classes, too.
2597      OverloadedFunctionDecl *Conversions
2598        = ClassDecl->getConversionFunctions();
2599      for (OverloadedFunctionDecl::function_iterator Func
2600             = Conversions->function_begin();
2601           Func != Conversions->function_end(); ++Func) {
2602        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2603        if (AllowExplicitConversions || !Conv->isExplicit())
2604          AddTypesConvertedFrom(Conv->getConversionType(), false, false);
2605      }
2606    }
2607  }
2608}
2609
2610/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2611/// operator overloads to the candidate set (C++ [over.built]), based
2612/// on the operator @p Op and the arguments given. For example, if the
2613/// operator is a binary '+', this routine might add "int
2614/// operator+(int, int)" to cover integer addition.
2615void
2616Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2617                                   Expr **Args, unsigned NumArgs,
2618                                   OverloadCandidateSet& CandidateSet) {
2619  // The set of "promoted arithmetic types", which are the arithmetic
2620  // types are that preserved by promotion (C++ [over.built]p2). Note
2621  // that the first few of these types are the promoted integral
2622  // types; these types need to be first.
2623  // FIXME: What about complex?
2624  const unsigned FirstIntegralType = 0;
2625  const unsigned LastIntegralType = 13;
2626  const unsigned FirstPromotedIntegralType = 7,
2627                 LastPromotedIntegralType = 13;
2628  const unsigned FirstPromotedArithmeticType = 7,
2629                 LastPromotedArithmeticType = 16;
2630  const unsigned NumArithmeticTypes = 16;
2631  QualType ArithmeticTypes[NumArithmeticTypes] = {
2632    Context.BoolTy, Context.CharTy, Context.WCharTy,
2633    Context.SignedCharTy, Context.ShortTy,
2634    Context.UnsignedCharTy, Context.UnsignedShortTy,
2635    Context.IntTy, Context.LongTy, Context.LongLongTy,
2636    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2637    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2638  };
2639
2640  // Find all of the types that the arguments can convert to, but only
2641  // if the operator we're looking at has built-in operator candidates
2642  // that make use of these types.
2643  BuiltinCandidateTypeSet CandidateTypes(Context);
2644  if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2645      Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
2646      Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
2647      Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
2648      Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2649      (Op == OO_Star && NumArgs == 1)) {
2650    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2651      CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2652                                           true,
2653                                           (Op == OO_Exclaim ||
2654                                            Op == OO_AmpAmp ||
2655                                            Op == OO_PipePipe));
2656  }
2657
2658  bool isComparison = false;
2659  switch (Op) {
2660  case OO_None:
2661  case NUM_OVERLOADED_OPERATORS:
2662    assert(false && "Expected an overloaded operator");
2663    break;
2664
2665  case OO_Star: // '*' is either unary or binary
2666    if (NumArgs == 1)
2667      goto UnaryStar;
2668    else
2669      goto BinaryStar;
2670    break;
2671
2672  case OO_Plus: // '+' is either unary or binary
2673    if (NumArgs == 1)
2674      goto UnaryPlus;
2675    else
2676      goto BinaryPlus;
2677    break;
2678
2679  case OO_Minus: // '-' is either unary or binary
2680    if (NumArgs == 1)
2681      goto UnaryMinus;
2682    else
2683      goto BinaryMinus;
2684    break;
2685
2686  case OO_Amp: // '&' is either unary or binary
2687    if (NumArgs == 1)
2688      goto UnaryAmp;
2689    else
2690      goto BinaryAmp;
2691
2692  case OO_PlusPlus:
2693  case OO_MinusMinus:
2694    // C++ [over.built]p3:
2695    //
2696    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
2697    //   is either volatile or empty, there exist candidate operator
2698    //   functions of the form
2699    //
2700    //       VQ T&      operator++(VQ T&);
2701    //       T          operator++(VQ T&, int);
2702    //
2703    // C++ [over.built]p4:
2704    //
2705    //   For every pair (T, VQ), where T is an arithmetic type other
2706    //   than bool, and VQ is either volatile or empty, there exist
2707    //   candidate operator functions of the form
2708    //
2709    //       VQ T&      operator--(VQ T&);
2710    //       T          operator--(VQ T&, int);
2711    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2712         Arith < NumArithmeticTypes; ++Arith) {
2713      QualType ArithTy = ArithmeticTypes[Arith];
2714      QualType ParamTypes[2]
2715        = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
2716
2717      // Non-volatile version.
2718      if (NumArgs == 1)
2719        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2720      else
2721        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2722
2723      // Volatile version
2724      ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
2725      if (NumArgs == 1)
2726        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2727      else
2728        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2729    }
2730
2731    // C++ [over.built]p5:
2732    //
2733    //   For every pair (T, VQ), where T is a cv-qualified or
2734    //   cv-unqualified object type, and VQ is either volatile or
2735    //   empty, there exist candidate operator functions of the form
2736    //
2737    //       T*VQ&      operator++(T*VQ&);
2738    //       T*VQ&      operator--(T*VQ&);
2739    //       T*         operator++(T*VQ&, int);
2740    //       T*         operator--(T*VQ&, int);
2741    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2742         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2743      // Skip pointer types that aren't pointers to object types.
2744      if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
2745        continue;
2746
2747      QualType ParamTypes[2] = {
2748        Context.getLValueReferenceType(*Ptr), Context.IntTy
2749      };
2750
2751      // Without volatile
2752      if (NumArgs == 1)
2753        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2754      else
2755        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2756
2757      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2758        // With volatile
2759        ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
2760        if (NumArgs == 1)
2761          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2762        else
2763          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2764      }
2765    }
2766    break;
2767
2768  UnaryStar:
2769    // C++ [over.built]p6:
2770    //   For every cv-qualified or cv-unqualified object type T, there
2771    //   exist candidate operator functions of the form
2772    //
2773    //       T&         operator*(T*);
2774    //
2775    // C++ [over.built]p7:
2776    //   For every function type T, there exist candidate operator
2777    //   functions of the form
2778    //       T&         operator*(T*);
2779    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2780         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2781      QualType ParamTy = *Ptr;
2782      QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2783      AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
2784                          &ParamTy, Args, 1, CandidateSet);
2785    }
2786    break;
2787
2788  UnaryPlus:
2789    // C++ [over.built]p8:
2790    //   For every type T, there exist candidate operator functions of
2791    //   the form
2792    //
2793    //       T*         operator+(T*);
2794    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2795         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2796      QualType ParamTy = *Ptr;
2797      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2798    }
2799
2800    // Fall through
2801
2802  UnaryMinus:
2803    // C++ [over.built]p9:
2804    //  For every promoted arithmetic type T, there exist candidate
2805    //  operator functions of the form
2806    //
2807    //       T         operator+(T);
2808    //       T         operator-(T);
2809    for (unsigned Arith = FirstPromotedArithmeticType;
2810         Arith < LastPromotedArithmeticType; ++Arith) {
2811      QualType ArithTy = ArithmeticTypes[Arith];
2812      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2813    }
2814    break;
2815
2816  case OO_Tilde:
2817    // C++ [over.built]p10:
2818    //   For every promoted integral type T, there exist candidate
2819    //   operator functions of the form
2820    //
2821    //        T         operator~(T);
2822    for (unsigned Int = FirstPromotedIntegralType;
2823         Int < LastPromotedIntegralType; ++Int) {
2824      QualType IntTy = ArithmeticTypes[Int];
2825      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2826    }
2827    break;
2828
2829  case OO_New:
2830  case OO_Delete:
2831  case OO_Array_New:
2832  case OO_Array_Delete:
2833  case OO_Call:
2834    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
2835    break;
2836
2837  case OO_Comma:
2838  UnaryAmp:
2839  case OO_Arrow:
2840    // C++ [over.match.oper]p3:
2841    //   -- For the operator ',', the unary operator '&', or the
2842    //      operator '->', the built-in candidates set is empty.
2843    break;
2844
2845  case OO_Less:
2846  case OO_Greater:
2847  case OO_LessEqual:
2848  case OO_GreaterEqual:
2849  case OO_EqualEqual:
2850  case OO_ExclaimEqual:
2851    // C++ [over.built]p15:
2852    //
2853    //   For every pointer or enumeration type T, there exist
2854    //   candidate operator functions of the form
2855    //
2856    //        bool       operator<(T, T);
2857    //        bool       operator>(T, T);
2858    //        bool       operator<=(T, T);
2859    //        bool       operator>=(T, T);
2860    //        bool       operator==(T, T);
2861    //        bool       operator!=(T, T);
2862    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2863         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2864      QualType ParamTypes[2] = { *Ptr, *Ptr };
2865      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2866    }
2867    for (BuiltinCandidateTypeSet::iterator Enum
2868           = CandidateTypes.enumeration_begin();
2869         Enum != CandidateTypes.enumeration_end(); ++Enum) {
2870      QualType ParamTypes[2] = { *Enum, *Enum };
2871      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2872    }
2873
2874    // Fall through.
2875    isComparison = true;
2876
2877  BinaryPlus:
2878  BinaryMinus:
2879    if (!isComparison) {
2880      // We didn't fall through, so we must have OO_Plus or OO_Minus.
2881
2882      // C++ [over.built]p13:
2883      //
2884      //   For every cv-qualified or cv-unqualified object type T
2885      //   there exist candidate operator functions of the form
2886      //
2887      //      T*         operator+(T*, ptrdiff_t);
2888      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
2889      //      T*         operator-(T*, ptrdiff_t);
2890      //      T*         operator+(ptrdiff_t, T*);
2891      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
2892      //
2893      // C++ [over.built]p14:
2894      //
2895      //   For every T, where T is a pointer to object type, there
2896      //   exist candidate operator functions of the form
2897      //
2898      //      ptrdiff_t  operator-(T, T);
2899      for (BuiltinCandidateTypeSet::iterator Ptr
2900             = CandidateTypes.pointer_begin();
2901           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2902        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2903
2904        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2905        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2906
2907        if (Op == OO_Plus) {
2908          // T* operator+(ptrdiff_t, T*);
2909          ParamTypes[0] = ParamTypes[1];
2910          ParamTypes[1] = *Ptr;
2911          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2912        } else {
2913          // ptrdiff_t operator-(T, T);
2914          ParamTypes[1] = *Ptr;
2915          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2916                              Args, 2, CandidateSet);
2917        }
2918      }
2919    }
2920    // Fall through
2921
2922  case OO_Slash:
2923  BinaryStar:
2924    // C++ [over.built]p12:
2925    //
2926    //   For every pair of promoted arithmetic types L and R, there
2927    //   exist candidate operator functions of the form
2928    //
2929    //        LR         operator*(L, R);
2930    //        LR         operator/(L, R);
2931    //        LR         operator+(L, R);
2932    //        LR         operator-(L, R);
2933    //        bool       operator<(L, R);
2934    //        bool       operator>(L, R);
2935    //        bool       operator<=(L, R);
2936    //        bool       operator>=(L, R);
2937    //        bool       operator==(L, R);
2938    //        bool       operator!=(L, R);
2939    //
2940    //   where LR is the result of the usual arithmetic conversions
2941    //   between types L and R.
2942    for (unsigned Left = FirstPromotedArithmeticType;
2943         Left < LastPromotedArithmeticType; ++Left) {
2944      for (unsigned Right = FirstPromotedArithmeticType;
2945           Right < LastPromotedArithmeticType; ++Right) {
2946        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2947        QualType Result
2948          = isComparison? Context.BoolTy
2949                        : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2950        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2951      }
2952    }
2953    break;
2954
2955  case OO_Percent:
2956  BinaryAmp:
2957  case OO_Caret:
2958  case OO_Pipe:
2959  case OO_LessLess:
2960  case OO_GreaterGreater:
2961    // C++ [over.built]p17:
2962    //
2963    //   For every pair of promoted integral types L and R, there
2964    //   exist candidate operator functions of the form
2965    //
2966    //      LR         operator%(L, R);
2967    //      LR         operator&(L, R);
2968    //      LR         operator^(L, R);
2969    //      LR         operator|(L, R);
2970    //      L          operator<<(L, R);
2971    //      L          operator>>(L, R);
2972    //
2973    //   where LR is the result of the usual arithmetic conversions
2974    //   between types L and R.
2975    for (unsigned Left = FirstPromotedIntegralType;
2976         Left < LastPromotedIntegralType; ++Left) {
2977      for (unsigned Right = FirstPromotedIntegralType;
2978           Right < LastPromotedIntegralType; ++Right) {
2979        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2980        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2981            ? LandR[0]
2982            : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2983        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2984      }
2985    }
2986    break;
2987
2988  case OO_Equal:
2989    // C++ [over.built]p20:
2990    //
2991    //   For every pair (T, VQ), where T is an enumeration or
2992    //   (FIXME:) pointer to member type and VQ is either volatile or
2993    //   empty, there exist candidate operator functions of the form
2994    //
2995    //        VQ T&      operator=(VQ T&, T);
2996    for (BuiltinCandidateTypeSet::iterator Enum
2997           = CandidateTypes.enumeration_begin();
2998         Enum != CandidateTypes.enumeration_end(); ++Enum) {
2999      QualType ParamTypes[2];
3000
3001      // T& operator=(T&, T)
3002      ParamTypes[0] = Context.getLValueReferenceType(*Enum);
3003      ParamTypes[1] = *Enum;
3004      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3005                          /*IsAssignmentOperator=*/false);
3006
3007      if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3008        // volatile T& operator=(volatile T&, T)
3009        ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
3010        ParamTypes[1] = *Enum;
3011        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3012                            /*IsAssignmentOperator=*/false);
3013      }
3014    }
3015    // Fall through.
3016
3017  case OO_PlusEqual:
3018  case OO_MinusEqual:
3019    // C++ [over.built]p19:
3020    //
3021    //   For every pair (T, VQ), where T is any type and VQ is either
3022    //   volatile or empty, there exist candidate operator functions
3023    //   of the form
3024    //
3025    //        T*VQ&      operator=(T*VQ&, T*);
3026    //
3027    // C++ [over.built]p21:
3028    //
3029    //   For every pair (T, VQ), where T is a cv-qualified or
3030    //   cv-unqualified object type and VQ is either volatile or
3031    //   empty, there exist candidate operator functions of the form
3032    //
3033    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
3034    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
3035    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3036         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3037      QualType ParamTypes[2];
3038      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3039
3040      // non-volatile version
3041      ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
3042      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3043                          /*IsAssigmentOperator=*/Op == OO_Equal);
3044
3045      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3046        // volatile version
3047        ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
3048        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3049                            /*IsAssigmentOperator=*/Op == OO_Equal);
3050      }
3051    }
3052    // Fall through.
3053
3054  case OO_StarEqual:
3055  case OO_SlashEqual:
3056    // C++ [over.built]p18:
3057    //
3058    //   For every triple (L, VQ, R), where L is an arithmetic type,
3059    //   VQ is either volatile or empty, and R is a promoted
3060    //   arithmetic type, there exist candidate operator functions of
3061    //   the form
3062    //
3063    //        VQ L&      operator=(VQ L&, R);
3064    //        VQ L&      operator*=(VQ L&, R);
3065    //        VQ L&      operator/=(VQ L&, R);
3066    //        VQ L&      operator+=(VQ L&, R);
3067    //        VQ L&      operator-=(VQ L&, R);
3068    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3069      for (unsigned Right = FirstPromotedArithmeticType;
3070           Right < LastPromotedArithmeticType; ++Right) {
3071        QualType ParamTypes[2];
3072        ParamTypes[1] = ArithmeticTypes[Right];
3073
3074        // Add this built-in operator as a candidate (VQ is empty).
3075        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3076        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3077                            /*IsAssigmentOperator=*/Op == OO_Equal);
3078
3079        // Add this built-in operator as a candidate (VQ is 'volatile').
3080        ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
3081        ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3082        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3083                            /*IsAssigmentOperator=*/Op == OO_Equal);
3084      }
3085    }
3086    break;
3087
3088  case OO_PercentEqual:
3089  case OO_LessLessEqual:
3090  case OO_GreaterGreaterEqual:
3091  case OO_AmpEqual:
3092  case OO_CaretEqual:
3093  case OO_PipeEqual:
3094    // C++ [over.built]p22:
3095    //
3096    //   For every triple (L, VQ, R), where L is an integral type, VQ
3097    //   is either volatile or empty, and R is a promoted integral
3098    //   type, there exist candidate operator functions of the form
3099    //
3100    //        VQ L&       operator%=(VQ L&, R);
3101    //        VQ L&       operator<<=(VQ L&, R);
3102    //        VQ L&       operator>>=(VQ L&, R);
3103    //        VQ L&       operator&=(VQ L&, R);
3104    //        VQ L&       operator^=(VQ L&, R);
3105    //        VQ L&       operator|=(VQ L&, R);
3106    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3107      for (unsigned Right = FirstPromotedIntegralType;
3108           Right < LastPromotedIntegralType; ++Right) {
3109        QualType ParamTypes[2];
3110        ParamTypes[1] = ArithmeticTypes[Right];
3111
3112        // Add this built-in operator as a candidate (VQ is empty).
3113        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3114        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3115
3116        // Add this built-in operator as a candidate (VQ is 'volatile').
3117        ParamTypes[0] = ArithmeticTypes[Left];
3118        ParamTypes[0].addVolatile();
3119        ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3120        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3121      }
3122    }
3123    break;
3124
3125  case OO_Exclaim: {
3126    // C++ [over.operator]p23:
3127    //
3128    //   There also exist candidate operator functions of the form
3129    //
3130    //        bool        operator!(bool);
3131    //        bool        operator&&(bool, bool);     [BELOW]
3132    //        bool        operator||(bool, bool);     [BELOW]
3133    QualType ParamTy = Context.BoolTy;
3134    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3135                        /*IsAssignmentOperator=*/false,
3136                        /*NumContextualBoolArguments=*/1);
3137    break;
3138  }
3139
3140  case OO_AmpAmp:
3141  case OO_PipePipe: {
3142    // C++ [over.operator]p23:
3143    //
3144    //   There also exist candidate operator functions of the form
3145    //
3146    //        bool        operator!(bool);            [ABOVE]
3147    //        bool        operator&&(bool, bool);
3148    //        bool        operator||(bool, bool);
3149    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
3150    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3151                        /*IsAssignmentOperator=*/false,
3152                        /*NumContextualBoolArguments=*/2);
3153    break;
3154  }
3155
3156  case OO_Subscript:
3157    // C++ [over.built]p13:
3158    //
3159    //   For every cv-qualified or cv-unqualified object type T there
3160    //   exist candidate operator functions of the form
3161    //
3162    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
3163    //        T&         operator[](T*, ptrdiff_t);
3164    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
3165    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
3166    //        T&         operator[](ptrdiff_t, T*);
3167    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3168         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3169      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3170      QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
3171      QualType ResultTy = Context.getLValueReferenceType(PointeeType);
3172
3173      // T& operator[](T*, ptrdiff_t)
3174      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3175
3176      // T& operator[](ptrdiff_t, T*);
3177      ParamTypes[0] = ParamTypes[1];
3178      ParamTypes[1] = *Ptr;
3179      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3180    }
3181    break;
3182
3183  case OO_ArrowStar:
3184    // FIXME: No support for pointer-to-members yet.
3185    break;
3186  }
3187}
3188
3189/// \brief Add function candidates found via argument-dependent lookup
3190/// to the set of overloading candidates.
3191///
3192/// This routine performs argument-dependent name lookup based on the
3193/// given function name (which may also be an operator name) and adds
3194/// all of the overload candidates found by ADL to the overload
3195/// candidate set (C++ [basic.lookup.argdep]).
3196void
3197Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3198                                           Expr **Args, unsigned NumArgs,
3199                                           OverloadCandidateSet& CandidateSet) {
3200  FunctionSet Functions;
3201
3202  // Record all of the function candidates that we've already
3203  // added to the overload set, so that we don't add those same
3204  // candidates a second time.
3205  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3206                                   CandEnd = CandidateSet.end();
3207       Cand != CandEnd; ++Cand)
3208    if (Cand->Function)
3209      Functions.insert(Cand->Function);
3210
3211  ArgumentDependentLookup(Name, Args, NumArgs, Functions);
3212
3213  // Erase all of the candidates we already knew about.
3214  // FIXME: This is suboptimal. Is there a better way?
3215  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3216                                   CandEnd = CandidateSet.end();
3217       Cand != CandEnd; ++Cand)
3218    if (Cand->Function)
3219      Functions.erase(Cand->Function);
3220
3221  // For each of the ADL candidates we found, add it to the overload
3222  // set.
3223  for (FunctionSet::iterator Func = Functions.begin(),
3224                          FuncEnd = Functions.end();
3225       Func != FuncEnd; ++Func)
3226    AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3227}
3228
3229/// isBetterOverloadCandidate - Determines whether the first overload
3230/// candidate is a better candidate than the second (C++ 13.3.3p1).
3231bool
3232Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3233                                const OverloadCandidate& Cand2)
3234{
3235  // Define viable functions to be better candidates than non-viable
3236  // functions.
3237  if (!Cand2.Viable)
3238    return Cand1.Viable;
3239  else if (!Cand1.Viable)
3240    return false;
3241
3242  // C++ [over.match.best]p1:
3243  //
3244  //   -- if F is a static member function, ICS1(F) is defined such
3245  //      that ICS1(F) is neither better nor worse than ICS1(G) for
3246  //      any function G, and, symmetrically, ICS1(G) is neither
3247  //      better nor worse than ICS1(F).
3248  unsigned StartArg = 0;
3249  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3250    StartArg = 1;
3251
3252  // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3253  // function than another viable function F2 if for all arguments i,
3254  // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3255  // then...
3256  unsigned NumArgs = Cand1.Conversions.size();
3257  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3258  bool HasBetterConversion = false;
3259  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
3260    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3261                                               Cand2.Conversions[ArgIdx])) {
3262    case ImplicitConversionSequence::Better:
3263      // Cand1 has a better conversion sequence.
3264      HasBetterConversion = true;
3265      break;
3266
3267    case ImplicitConversionSequence::Worse:
3268      // Cand1 can't be better than Cand2.
3269      return false;
3270
3271    case ImplicitConversionSequence::Indistinguishable:
3272      // Do nothing.
3273      break;
3274    }
3275  }
3276
3277  if (HasBetterConversion)
3278    return true;
3279
3280  // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3281  // implemented, but they require template support.
3282
3283  // C++ [over.match.best]p1b4:
3284  //
3285  //   -- the context is an initialization by user-defined conversion
3286  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
3287  //      from the return type of F1 to the destination type (i.e.,
3288  //      the type of the entity being initialized) is a better
3289  //      conversion sequence than the standard conversion sequence
3290  //      from the return type of F2 to the destination type.
3291  if (Cand1.Function && Cand2.Function &&
3292      isa<CXXConversionDecl>(Cand1.Function) &&
3293      isa<CXXConversionDecl>(Cand2.Function)) {
3294    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3295                                               Cand2.FinalConversion)) {
3296    case ImplicitConversionSequence::Better:
3297      // Cand1 has a better conversion sequence.
3298      return true;
3299
3300    case ImplicitConversionSequence::Worse:
3301      // Cand1 can't be better than Cand2.
3302      return false;
3303
3304    case ImplicitConversionSequence::Indistinguishable:
3305      // Do nothing
3306      break;
3307    }
3308  }
3309
3310  return false;
3311}
3312
3313/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3314/// within an overload candidate set. If overloading is successful,
3315/// the result will be OR_Success and Best will be set to point to the
3316/// best viable function within the candidate set. Otherwise, one of
3317/// several kinds of errors will be returned; see
3318/// Sema::OverloadingResult.
3319Sema::OverloadingResult
3320Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3321                         OverloadCandidateSet::iterator& Best)
3322{
3323  // Find the best viable function.
3324  Best = CandidateSet.end();
3325  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3326       Cand != CandidateSet.end(); ++Cand) {
3327    if (Cand->Viable) {
3328      if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3329        Best = Cand;
3330    }
3331  }
3332
3333  // If we didn't find any viable functions, abort.
3334  if (Best == CandidateSet.end())
3335    return OR_No_Viable_Function;
3336
3337  // Make sure that this function is better than every other viable
3338  // function. If not, we have an ambiguity.
3339  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3340       Cand != CandidateSet.end(); ++Cand) {
3341    if (Cand->Viable &&
3342        Cand != Best &&
3343        !isBetterOverloadCandidate(*Best, *Cand)) {
3344      Best = CandidateSet.end();
3345      return OR_Ambiguous;
3346    }
3347  }
3348
3349  // Best is the best viable function.
3350  if (Best->Function &&
3351      (Best->Function->isDeleted() ||
3352       Best->Function->getAttr<UnavailableAttr>()))
3353    return OR_Deleted;
3354
3355  // If Best refers to a function that is either deleted (C++0x) or
3356  // unavailable (Clang extension) report an error.
3357
3358  return OR_Success;
3359}
3360
3361/// PrintOverloadCandidates - When overload resolution fails, prints
3362/// diagnostic messages containing the candidates in the candidate
3363/// set. If OnlyViable is true, only viable candidates will be printed.
3364void
3365Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3366                              bool OnlyViable)
3367{
3368  OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3369                             LastCand = CandidateSet.end();
3370  for (; Cand != LastCand; ++Cand) {
3371    if (Cand->Viable || !OnlyViable) {
3372      if (Cand->Function) {
3373        if (Cand->Function->isDeleted() ||
3374            Cand->Function->getAttr<UnavailableAttr>()) {
3375          // Deleted or "unavailable" function.
3376          Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3377            << Cand->Function->isDeleted();
3378        } else {
3379          // Normal function
3380          // FIXME: Give a better reason!
3381          Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3382        }
3383      } else if (Cand->IsSurrogate) {
3384        // Desugar the type of the surrogate down to a function type,
3385        // retaining as many typedefs as possible while still showing
3386        // the function type (and, therefore, its parameter types).
3387        QualType FnType = Cand->Surrogate->getConversionType();
3388        bool isLValueReference = false;
3389        bool isRValueReference = false;
3390        bool isPointer = false;
3391        if (const LValueReferenceType *FnTypeRef =
3392              FnType->getAsLValueReferenceType()) {
3393          FnType = FnTypeRef->getPointeeType();
3394          isLValueReference = true;
3395        } else if (const RValueReferenceType *FnTypeRef =
3396                     FnType->getAsRValueReferenceType()) {
3397          FnType = FnTypeRef->getPointeeType();
3398          isRValueReference = true;
3399        }
3400        if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3401          FnType = FnTypePtr->getPointeeType();
3402          isPointer = true;
3403        }
3404        // Desugar down to a function type.
3405        FnType = QualType(FnType->getAsFunctionType(), 0);
3406        // Reconstruct the pointer/reference as appropriate.
3407        if (isPointer) FnType = Context.getPointerType(FnType);
3408        if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3409        if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
3410
3411        Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
3412          << FnType;
3413      } else {
3414        // FIXME: We need to get the identifier in here
3415        // FIXME: Do we want the error message to point at the
3416        // operator? (built-ins won't have a location)
3417        QualType FnType
3418          = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3419                                    Cand->BuiltinTypes.ParamTypes,
3420                                    Cand->Conversions.size(),
3421                                    false, 0);
3422
3423        Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
3424      }
3425    }
3426  }
3427}
3428
3429/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3430/// an overloaded function (C++ [over.over]), where @p From is an
3431/// expression with overloaded function type and @p ToType is the type
3432/// we're trying to resolve to. For example:
3433///
3434/// @code
3435/// int f(double);
3436/// int f(int);
3437///
3438/// int (*pfd)(double) = f; // selects f(double)
3439/// @endcode
3440///
3441/// This routine returns the resulting FunctionDecl if it could be
3442/// resolved, and NULL otherwise. When @p Complain is true, this
3443/// routine will emit diagnostics if there is an error.
3444FunctionDecl *
3445Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3446                                         bool Complain) {
3447  QualType FunctionType = ToType;
3448  bool IsMember = false;
3449  if (const PointerType *ToTypePtr = ToType->getAsPointerType())
3450    FunctionType = ToTypePtr->getPointeeType();
3451  else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3452    FunctionType = ToTypeRef->getPointeeType();
3453  else if (const MemberPointerType *MemTypePtr =
3454                    ToType->getAsMemberPointerType()) {
3455    FunctionType = MemTypePtr->getPointeeType();
3456    IsMember = true;
3457  }
3458
3459  // We only look at pointers or references to functions.
3460  if (!FunctionType->isFunctionType())
3461    return 0;
3462
3463  // Find the actual overloaded function declaration.
3464  OverloadedFunctionDecl *Ovl = 0;
3465
3466  // C++ [over.over]p1:
3467  //   [...] [Note: any redundant set of parentheses surrounding the
3468  //   overloaded function name is ignored (5.1). ]
3469  Expr *OvlExpr = From->IgnoreParens();
3470
3471  // C++ [over.over]p1:
3472  //   [...] The overloaded function name can be preceded by the &
3473  //   operator.
3474  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3475    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3476      OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3477  }
3478
3479  // Try to dig out the overloaded function.
3480  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3481    Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3482
3483  // If there's no overloaded function declaration, we're done.
3484  if (!Ovl)
3485    return 0;
3486
3487  // Look through all of the overloaded functions, searching for one
3488  // whose type matches exactly.
3489  // FIXME: When templates or using declarations come along, we'll actually
3490  // have to deal with duplicates, partial ordering, etc. For now, we
3491  // can just do a simple search.
3492  FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3493  for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3494       Fun != Ovl->function_end(); ++Fun) {
3495    // C++ [over.over]p3:
3496    //   Non-member functions and static member functions match
3497    //   targets of type "pointer-to-function" or "reference-to-function."
3498    //   Nonstatic member functions match targets of
3499    //   type "pointer-to-member-function."
3500    // Note that according to DR 247, the containing class does not matter.
3501    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3502      // Skip non-static functions when converting to pointer, and static
3503      // when converting to member pointer.
3504      if (Method->isStatic() == IsMember)
3505        continue;
3506    } else if (IsMember)
3507      continue;
3508
3509    if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3510      return *Fun;
3511  }
3512
3513  return 0;
3514}
3515
3516/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3517/// (which eventually refers to the declaration Func) and the call
3518/// arguments Args/NumArgs, attempt to resolve the function call down
3519/// to a specific function. If overload resolution succeeds, returns
3520/// the function declaration produced by overload
3521/// resolution. Otherwise, emits diagnostics, deletes all of the
3522/// arguments and Fn, and returns NULL.
3523FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
3524                                            DeclarationName UnqualifiedName,
3525                                            SourceLocation LParenLoc,
3526                                            Expr **Args, unsigned NumArgs,
3527                                            SourceLocation *CommaLocs,
3528                                            SourceLocation RParenLoc,
3529                                            bool &ArgumentDependentLookup) {
3530  OverloadCandidateSet CandidateSet;
3531
3532  // Add the functions denoted by Callee to the set of candidate
3533  // functions. While we're doing so, track whether argument-dependent
3534  // lookup still applies, per:
3535  //
3536  // C++0x [basic.lookup.argdep]p3:
3537  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
3538  //   and let Y be the lookup set produced by argument dependent
3539  //   lookup (defined as follows). If X contains
3540  //
3541  //     -- a declaration of a class member, or
3542  //
3543  //     -- a block-scope function declaration that is not a
3544  //        using-declaration, or
3545  //
3546  //     -- a declaration that is neither a function or a function
3547  //        template
3548  //
3549  //   then Y is empty.
3550  if (OverloadedFunctionDecl *Ovl
3551        = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3552    for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3553                                                FuncEnd = Ovl->function_end();
3554         Func != FuncEnd; ++Func) {
3555      AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3556
3557      if ((*Func)->getDeclContext()->isRecord() ||
3558          (*Func)->getDeclContext()->isFunctionOrMethod())
3559        ArgumentDependentLookup = false;
3560    }
3561  } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3562    AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3563
3564    if (Func->getDeclContext()->isRecord() ||
3565        Func->getDeclContext()->isFunctionOrMethod())
3566      ArgumentDependentLookup = false;
3567  }
3568
3569  if (Callee)
3570    UnqualifiedName = Callee->getDeclName();
3571
3572  if (ArgumentDependentLookup)
3573    AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
3574                                         CandidateSet);
3575
3576  OverloadCandidateSet::iterator Best;
3577  switch (BestViableFunction(CandidateSet, Best)) {
3578  case OR_Success:
3579    return Best->Function;
3580
3581  case OR_No_Viable_Function:
3582    Diag(Fn->getSourceRange().getBegin(),
3583         diag::err_ovl_no_viable_function_in_call)
3584      << UnqualifiedName << Fn->getSourceRange();
3585    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3586    break;
3587
3588  case OR_Ambiguous:
3589    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3590      << UnqualifiedName << Fn->getSourceRange();
3591    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3592    break;
3593
3594  case OR_Deleted:
3595    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3596      << Best->Function->isDeleted()
3597      << UnqualifiedName
3598      << Fn->getSourceRange();
3599    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3600    break;
3601  }
3602
3603  // Overload resolution failed. Destroy all of the subexpressions and
3604  // return NULL.
3605  Fn->Destroy(Context);
3606  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3607    Args[Arg]->Destroy(Context);
3608  return 0;
3609}
3610
3611/// \brief Create a unary operation that may resolve to an overloaded
3612/// operator.
3613///
3614/// \param OpLoc The location of the operator itself (e.g., '*').
3615///
3616/// \param OpcIn The UnaryOperator::Opcode that describes this
3617/// operator.
3618///
3619/// \param Functions The set of non-member functions that will be
3620/// considered by overload resolution. The caller needs to build this
3621/// set based on the context using, e.g.,
3622/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3623/// set should not contain any member functions; those will be added
3624/// by CreateOverloadedUnaryOp().
3625///
3626/// \param input The input argument.
3627Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3628                                                     unsigned OpcIn,
3629                                                     FunctionSet &Functions,
3630                                                     ExprArg input) {
3631  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3632  Expr *Input = (Expr *)input.get();
3633
3634  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3635  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3636  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3637
3638  Expr *Args[2] = { Input, 0 };
3639  unsigned NumArgs = 1;
3640
3641  // For post-increment and post-decrement, add the implicit '0' as
3642  // the second argument, so that we know this is a post-increment or
3643  // post-decrement.
3644  if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3645    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3646    Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3647                                           SourceLocation());
3648    NumArgs = 2;
3649  }
3650
3651  if (Input->isTypeDependent()) {
3652    OverloadedFunctionDecl *Overloads
3653      = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3654    for (FunctionSet::iterator Func = Functions.begin(),
3655                            FuncEnd = Functions.end();
3656         Func != FuncEnd; ++Func)
3657      Overloads->addOverload(*Func);
3658
3659    DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3660                                                OpLoc, false, false);
3661
3662    input.release();
3663    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3664                                                   &Args[0], NumArgs,
3665                                                   Context.DependentTy,
3666                                                   OpLoc));
3667  }
3668
3669  // Build an empty overload set.
3670  OverloadCandidateSet CandidateSet;
3671
3672  // Add the candidates from the given function set.
3673  AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3674
3675  // Add operator candidates that are member functions.
3676  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3677
3678  // Add builtin operator candidates.
3679  AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3680
3681  // Perform overload resolution.
3682  OverloadCandidateSet::iterator Best;
3683  switch (BestViableFunction(CandidateSet, Best)) {
3684  case OR_Success: {
3685    // We found a built-in operator or an overloaded operator.
3686    FunctionDecl *FnDecl = Best->Function;
3687
3688    if (FnDecl) {
3689      // We matched an overloaded operator. Build a call to that
3690      // operator.
3691
3692      // Convert the arguments.
3693      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3694        if (PerformObjectArgumentInitialization(Input, Method))
3695          return ExprError();
3696      } else {
3697        // Convert the arguments.
3698        if (PerformCopyInitialization(Input,
3699                                      FnDecl->getParamDecl(0)->getType(),
3700                                      "passing"))
3701          return ExprError();
3702      }
3703
3704      // Determine the result type
3705      QualType ResultTy
3706        = FnDecl->getType()->getAsFunctionType()->getResultType();
3707      ResultTy = ResultTy.getNonReferenceType();
3708
3709      // Build the actual expression node.
3710      Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3711                                               SourceLocation());
3712      UsualUnaryConversions(FnExpr);
3713
3714      input.release();
3715      return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3716                                                     &Input, 1, ResultTy,
3717                                                     OpLoc));
3718    } else {
3719      // We matched a built-in operator. Convert the arguments, then
3720      // break out so that we will build the appropriate built-in
3721      // operator node.
3722        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3723                                      Best->Conversions[0], "passing"))
3724          return ExprError();
3725
3726        break;
3727      }
3728    }
3729
3730    case OR_No_Viable_Function:
3731      // No viable function; fall through to handling this as a
3732      // built-in operator, which will produce an error message for us.
3733      break;
3734
3735    case OR_Ambiguous:
3736      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
3737          << UnaryOperator::getOpcodeStr(Opc)
3738          << Input->getSourceRange();
3739      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3740      return ExprError();
3741
3742    case OR_Deleted:
3743      Diag(OpLoc, diag::err_ovl_deleted_oper)
3744        << Best->Function->isDeleted()
3745        << UnaryOperator::getOpcodeStr(Opc)
3746        << Input->getSourceRange();
3747      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3748      return ExprError();
3749    }
3750
3751  // Either we found no viable overloaded operator or we matched a
3752  // built-in operator. In either case, fall through to trying to
3753  // build a built-in operation.
3754  input.release();
3755  return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
3756}
3757
3758/// \brief Create a binary operation that may resolve to an overloaded
3759/// operator.
3760///
3761/// \param OpLoc The location of the operator itself (e.g., '+').
3762///
3763/// \param OpcIn The BinaryOperator::Opcode that describes this
3764/// operator.
3765///
3766/// \param Functions The set of non-member functions that will be
3767/// considered by overload resolution. The caller needs to build this
3768/// set based on the context using, e.g.,
3769/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3770/// set should not contain any member functions; those will be added
3771/// by CreateOverloadedBinOp().
3772///
3773/// \param LHS Left-hand argument.
3774/// \param RHS Right-hand argument.
3775Sema::OwningExprResult
3776Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
3777                            unsigned OpcIn,
3778                            FunctionSet &Functions,
3779                            Expr *LHS, Expr *RHS) {
3780  Expr *Args[2] = { LHS, RHS };
3781
3782  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
3783  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
3784  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3785
3786  // If either side is type-dependent, create an appropriate dependent
3787  // expression.
3788  if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
3789    // .* cannot be overloaded.
3790    if (Opc == BinaryOperator::PtrMemD)
3791      return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
3792                                                Context.DependentTy, OpLoc));
3793
3794    OverloadedFunctionDecl *Overloads
3795      = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3796    for (FunctionSet::iterator Func = Functions.begin(),
3797                            FuncEnd = Functions.end();
3798         Func != FuncEnd; ++Func)
3799      Overloads->addOverload(*Func);
3800
3801    DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3802                                                OpLoc, false, false);
3803
3804    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3805                                                   Args, 2,
3806                                                   Context.DependentTy,
3807                                                   OpLoc));
3808  }
3809
3810  // If this is the .* operator, which is not overloadable, just
3811  // create a built-in binary operator.
3812  if (Opc == BinaryOperator::PtrMemD)
3813    return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3814
3815  // If this is one of the assignment operators, we only perform
3816  // overload resolution if the left-hand side is a class or
3817  // enumeration type (C++ [expr.ass]p3).
3818  if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3819      !LHS->getType()->isOverloadableType())
3820    return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3821
3822  // Build an empty overload set.
3823  OverloadCandidateSet CandidateSet;
3824
3825  // Add the candidates from the given function set.
3826  AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
3827
3828  // Add operator candidates that are member functions.
3829  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
3830
3831  // Add builtin operator candidates.
3832  AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
3833
3834  // Perform overload resolution.
3835  OverloadCandidateSet::iterator Best;
3836  switch (BestViableFunction(CandidateSet, Best)) {
3837  case OR_Success: {
3838      // We found a built-in operator or an overloaded operator.
3839      FunctionDecl *FnDecl = Best->Function;
3840
3841      if (FnDecl) {
3842        // We matched an overloaded operator. Build a call to that
3843        // operator.
3844
3845        // Convert the arguments.
3846        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3847          if (PerformObjectArgumentInitialization(LHS, Method) ||
3848              PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
3849                                        "passing"))
3850            return ExprError();
3851        } else {
3852          // Convert the arguments.
3853          if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
3854                                        "passing") ||
3855              PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
3856                                        "passing"))
3857            return ExprError();
3858        }
3859
3860        // Determine the result type
3861        QualType ResultTy
3862          = FnDecl->getType()->getAsFunctionType()->getResultType();
3863        ResultTy = ResultTy.getNonReferenceType();
3864
3865        // Build the actual expression node.
3866        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3867                                                 SourceLocation());
3868        UsualUnaryConversions(FnExpr);
3869
3870        return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3871                                                       Args, 2, ResultTy,
3872                                                       OpLoc));
3873      } else {
3874        // We matched a built-in operator. Convert the arguments, then
3875        // break out so that we will build the appropriate built-in
3876        // operator node.
3877        if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
3878                                      Best->Conversions[0], "passing") ||
3879            PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
3880                                      Best->Conversions[1], "passing"))
3881          return ExprError();
3882
3883        break;
3884      }
3885    }
3886
3887    case OR_No_Viable_Function:
3888      // No viable function; fall through to handling this as a
3889      // built-in operator, which will produce an error message for us.
3890      break;
3891
3892    case OR_Ambiguous:
3893      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
3894          << BinaryOperator::getOpcodeStr(Opc)
3895          << LHS->getSourceRange() << RHS->getSourceRange();
3896      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3897      return ExprError();
3898
3899    case OR_Deleted:
3900      Diag(OpLoc, diag::err_ovl_deleted_oper)
3901        << Best->Function->isDeleted()
3902        << BinaryOperator::getOpcodeStr(Opc)
3903        << LHS->getSourceRange() << RHS->getSourceRange();
3904      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3905      return ExprError();
3906    }
3907
3908  // Either we found no viable overloaded operator or we matched a
3909  // built-in operator. In either case, try to build a built-in
3910  // operation.
3911  return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3912}
3913
3914/// BuildCallToMemberFunction - Build a call to a member
3915/// function. MemExpr is the expression that refers to the member
3916/// function (and includes the object parameter), Args/NumArgs are the
3917/// arguments to the function call (not including the object
3918/// parameter). The caller needs to validate that the member
3919/// expression refers to a member function or an overloaded member
3920/// function.
3921Sema::ExprResult
3922Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3923                                SourceLocation LParenLoc, Expr **Args,
3924                                unsigned NumArgs, SourceLocation *CommaLocs,
3925                                SourceLocation RParenLoc) {
3926  // Dig out the member expression. This holds both the object
3927  // argument and the member function we're referring to.
3928  MemberExpr *MemExpr = 0;
3929  if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3930    MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3931  else
3932    MemExpr = dyn_cast<MemberExpr>(MemExprE);
3933  assert(MemExpr && "Building member call without member expression");
3934
3935  // Extract the object argument.
3936  Expr *ObjectArg = MemExpr->getBase();
3937  if (MemExpr->isArrow())
3938    ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref,
3939                     ObjectArg->getType()->getAsPointerType()->getPointeeType(),
3940                                            ObjectArg->getLocStart());
3941  CXXMethodDecl *Method = 0;
3942  if (OverloadedFunctionDecl *Ovl
3943        = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3944    // Add overload candidates
3945    OverloadCandidateSet CandidateSet;
3946    for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3947                                                FuncEnd = Ovl->function_end();
3948         Func != FuncEnd; ++Func) {
3949      assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3950      Method = cast<CXXMethodDecl>(*Func);
3951      AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3952                         /*SuppressUserConversions=*/false);
3953    }
3954
3955    OverloadCandidateSet::iterator Best;
3956    switch (BestViableFunction(CandidateSet, Best)) {
3957    case OR_Success:
3958      Method = cast<CXXMethodDecl>(Best->Function);
3959      break;
3960
3961    case OR_No_Viable_Function:
3962      Diag(MemExpr->getSourceRange().getBegin(),
3963           diag::err_ovl_no_viable_member_function_in_call)
3964        << Ovl->getDeclName() << MemExprE->getSourceRange();
3965      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3966      // FIXME: Leaking incoming expressions!
3967      return true;
3968
3969    case OR_Ambiguous:
3970      Diag(MemExpr->getSourceRange().getBegin(),
3971           diag::err_ovl_ambiguous_member_call)
3972        << Ovl->getDeclName() << MemExprE->getSourceRange();
3973      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3974      // FIXME: Leaking incoming expressions!
3975      return true;
3976
3977    case OR_Deleted:
3978      Diag(MemExpr->getSourceRange().getBegin(),
3979           diag::err_ovl_deleted_member_call)
3980        << Best->Function->isDeleted()
3981        << Ovl->getDeclName() << MemExprE->getSourceRange();
3982      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3983      // FIXME: Leaking incoming expressions!
3984      return true;
3985    }
3986
3987    FixOverloadedFunctionReference(MemExpr, Method);
3988  } else {
3989    Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3990  }
3991
3992  assert(Method && "Member call to something that isn't a method?");
3993  ExprOwningPtr<CXXMemberCallExpr>
3994    TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
3995                                                  NumArgs,
3996                                  Method->getResultType().getNonReferenceType(),
3997                                  RParenLoc));
3998
3999  // Convert the object argument (for a non-static member function call).
4000  if (!Method->isStatic() &&
4001      PerformObjectArgumentInitialization(ObjectArg, Method))
4002    return true;
4003  MemExpr->setBase(ObjectArg);
4004
4005  // Convert the rest of the arguments
4006  const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
4007  if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4008                              RParenLoc))
4009    return true;
4010
4011  return CheckFunctionCall(Method, TheCall.take()).release();
4012}
4013
4014/// BuildCallToObjectOfClassType - Build a call to an object of class
4015/// type (C++ [over.call.object]), which can end up invoking an
4016/// overloaded function call operator (@c operator()) or performing a
4017/// user-defined conversion on the object argument.
4018Sema::ExprResult
4019Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4020                                   SourceLocation LParenLoc,
4021                                   Expr **Args, unsigned NumArgs,
4022                                   SourceLocation *CommaLocs,
4023                                   SourceLocation RParenLoc) {
4024  assert(Object->getType()->isRecordType() && "Requires object type argument");
4025  const RecordType *Record = Object->getType()->getAsRecordType();
4026
4027  // C++ [over.call.object]p1:
4028  //  If the primary-expression E in the function call syntax
4029  //  evaluates to a class object of type “cv T”, then the set of
4030  //  candidate functions includes at least the function call
4031  //  operators of T. The function call operators of T are obtained by
4032  //  ordinary lookup of the name operator() in the context of
4033  //  (E).operator().
4034  OverloadCandidateSet CandidateSet;
4035  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4036  DeclContext::lookup_const_iterator Oper, OperEnd;
4037  for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(Context, OpName);
4038       Oper != OperEnd; ++Oper)
4039    AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4040                       CandidateSet, /*SuppressUserConversions=*/false);
4041
4042  // C++ [over.call.object]p2:
4043  //   In addition, for each conversion function declared in T of the
4044  //   form
4045  //
4046  //        operator conversion-type-id () cv-qualifier;
4047  //
4048  //   where cv-qualifier is the same cv-qualification as, or a
4049  //   greater cv-qualification than, cv, and where conversion-type-id
4050  //   denotes the type "pointer to function of (P1,...,Pn) returning
4051  //   R", or the type "reference to pointer to function of
4052  //   (P1,...,Pn) returning R", or the type "reference to function
4053  //   of (P1,...,Pn) returning R", a surrogate call function [...]
4054  //   is also considered as a candidate function. Similarly,
4055  //   surrogate call functions are added to the set of candidate
4056  //   functions for each conversion function declared in an
4057  //   accessible base class provided the function is not hidden
4058  //   within T by another intervening declaration.
4059  //
4060  // FIXME: Look in base classes for more conversion operators!
4061  OverloadedFunctionDecl *Conversions
4062    = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
4063  for (OverloadedFunctionDecl::function_iterator
4064         Func = Conversions->function_begin(),
4065         FuncEnd = Conversions->function_end();
4066       Func != FuncEnd; ++Func) {
4067    CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4068
4069    // Strip the reference type (if any) and then the pointer type (if
4070    // any) to get down to what might be a function type.
4071    QualType ConvType = Conv->getConversionType().getNonReferenceType();
4072    if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4073      ConvType = ConvPtrType->getPointeeType();
4074
4075    if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4076      AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4077  }
4078
4079  // Perform overload resolution.
4080  OverloadCandidateSet::iterator Best;
4081  switch (BestViableFunction(CandidateSet, Best)) {
4082  case OR_Success:
4083    // Overload resolution succeeded; we'll build the appropriate call
4084    // below.
4085    break;
4086
4087  case OR_No_Viable_Function:
4088    Diag(Object->getSourceRange().getBegin(),
4089         diag::err_ovl_no_viable_object_call)
4090      << Object->getType() << Object->getSourceRange();
4091    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4092    break;
4093
4094  case OR_Ambiguous:
4095    Diag(Object->getSourceRange().getBegin(),
4096         diag::err_ovl_ambiguous_object_call)
4097      << Object->getType() << Object->getSourceRange();
4098    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4099    break;
4100
4101  case OR_Deleted:
4102    Diag(Object->getSourceRange().getBegin(),
4103         diag::err_ovl_deleted_object_call)
4104      << Best->Function->isDeleted()
4105      << Object->getType() << Object->getSourceRange();
4106    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4107    break;
4108  }
4109
4110  if (Best == CandidateSet.end()) {
4111    // We had an error; delete all of the subexpressions and return
4112    // the error.
4113    Object->Destroy(Context);
4114    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4115      Args[ArgIdx]->Destroy(Context);
4116    return true;
4117  }
4118
4119  if (Best->Function == 0) {
4120    // Since there is no function declaration, this is one of the
4121    // surrogate candidates. Dig out the conversion function.
4122    CXXConversionDecl *Conv
4123      = cast<CXXConversionDecl>(
4124                         Best->Conversions[0].UserDefined.ConversionFunction);
4125
4126    // We selected one of the surrogate functions that converts the
4127    // object parameter to a function pointer. Perform the conversion
4128    // on the object argument, then let ActOnCallExpr finish the job.
4129    // FIXME: Represent the user-defined conversion in the AST!
4130    ImpCastExprToType(Object,
4131                      Conv->getConversionType().getNonReferenceType(),
4132                      Conv->getConversionType()->isLValueReferenceType());
4133    return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4134                         MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4135                         CommaLocs, RParenLoc).release();
4136  }
4137
4138  // We found an overloaded operator(). Build a CXXOperatorCallExpr
4139  // that calls this method, using Object for the implicit object
4140  // parameter and passing along the remaining arguments.
4141  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
4142  const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
4143
4144  unsigned NumArgsInProto = Proto->getNumArgs();
4145  unsigned NumArgsToCheck = NumArgs;
4146
4147  // Build the full argument list for the method call (the
4148  // implicit object parameter is placed at the beginning of the
4149  // list).
4150  Expr **MethodArgs;
4151  if (NumArgs < NumArgsInProto) {
4152    NumArgsToCheck = NumArgsInProto;
4153    MethodArgs = new Expr*[NumArgsInProto + 1];
4154  } else {
4155    MethodArgs = new Expr*[NumArgs + 1];
4156  }
4157  MethodArgs[0] = Object;
4158  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4159    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4160
4161  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4162                                          SourceLocation());
4163  UsualUnaryConversions(NewFn);
4164
4165  // Once we've built TheCall, all of the expressions are properly
4166  // owned.
4167  QualType ResultTy = Method->getResultType().getNonReferenceType();
4168  ExprOwningPtr<CXXOperatorCallExpr>
4169    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4170                                                    MethodArgs, NumArgs + 1,
4171                                                    ResultTy, RParenLoc));
4172  delete [] MethodArgs;
4173
4174  // We may have default arguments. If so, we need to allocate more
4175  // slots in the call for them.
4176  if (NumArgs < NumArgsInProto)
4177    TheCall->setNumArgs(Context, NumArgsInProto + 1);
4178  else if (NumArgs > NumArgsInProto)
4179    NumArgsToCheck = NumArgsInProto;
4180
4181  // Initialize the implicit object parameter.
4182  if (PerformObjectArgumentInitialization(Object, Method))
4183    return true;
4184  TheCall->setArg(0, Object);
4185
4186  // Check the argument types.
4187  for (unsigned i = 0; i != NumArgsToCheck; i++) {
4188    Expr *Arg;
4189    if (i < NumArgs) {
4190      Arg = Args[i];
4191
4192      // Pass the argument.
4193      QualType ProtoArgType = Proto->getArgType(i);
4194      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
4195        return true;
4196    } else {
4197      Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
4198    }
4199
4200    TheCall->setArg(i + 1, Arg);
4201  }
4202
4203  // If this is a variadic call, handle args passed through "...".
4204  if (Proto->isVariadic()) {
4205    // Promote the arguments (C99 6.5.2.2p7).
4206    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4207      Expr *Arg = Args[i];
4208
4209      DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
4210      TheCall->setArg(i + 1, Arg);
4211    }
4212  }
4213
4214  return CheckFunctionCall(Method, TheCall.take()).release();
4215}
4216
4217/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4218///  (if one exists), where @c Base is an expression of class type and
4219/// @c Member is the name of the member we're trying to find.
4220Action::ExprResult
4221Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
4222                               SourceLocation MemberLoc,
4223                               IdentifierInfo &Member) {
4224  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4225
4226  // C++ [over.ref]p1:
4227  //
4228  //   [...] An expression x->m is interpreted as (x.operator->())->m
4229  //   for a class object x of type T if T::operator->() exists and if
4230  //   the operator is selected as the best match function by the
4231  //   overload resolution mechanism (13.3).
4232  // FIXME: look in base classes.
4233  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4234  OverloadCandidateSet CandidateSet;
4235  const RecordType *BaseRecord = Base->getType()->getAsRecordType();
4236
4237  DeclContext::lookup_const_iterator Oper, OperEnd;
4238  for (llvm::tie(Oper, OperEnd)
4239         = BaseRecord->getDecl()->lookup(Context, OpName);
4240       Oper != OperEnd; ++Oper)
4241    AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
4242                       /*SuppressUserConversions=*/false);
4243
4244  ExprOwningPtr<Expr> BasePtr(this, Base);
4245
4246  // Perform overload resolution.
4247  OverloadCandidateSet::iterator Best;
4248  switch (BestViableFunction(CandidateSet, Best)) {
4249  case OR_Success:
4250    // Overload resolution succeeded; we'll build the call below.
4251    break;
4252
4253  case OR_No_Viable_Function:
4254    if (CandidateSet.empty())
4255      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
4256        << BasePtr->getType() << BasePtr->getSourceRange();
4257    else
4258      Diag(OpLoc, diag::err_ovl_no_viable_oper)
4259        << "operator->" << BasePtr->getSourceRange();
4260    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4261    return true;
4262
4263  case OR_Ambiguous:
4264    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4265      << "operator->" << BasePtr->getSourceRange();
4266    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4267    return true;
4268
4269  case OR_Deleted:
4270    Diag(OpLoc,  diag::err_ovl_deleted_oper)
4271      << Best->Function->isDeleted()
4272      << "operator->" << BasePtr->getSourceRange();
4273    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4274    return true;
4275  }
4276
4277  // Convert the object parameter.
4278  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
4279  if (PerformObjectArgumentInitialization(Base, Method))
4280    return true;
4281
4282  // No concerns about early exits now.
4283  BasePtr.take();
4284
4285  // Build the operator call.
4286  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4287                                           SourceLocation());
4288  UsualUnaryConversions(FnExpr);
4289  Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
4290                                 Method->getResultType().getNonReferenceType(),
4291                                 OpLoc);
4292  return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
4293                                  MemberLoc, Member, DeclPtrTy()).release();
4294}
4295
4296/// FixOverloadedFunctionReference - E is an expression that refers to
4297/// a C++ overloaded function (possibly with some parentheses and
4298/// perhaps a '&' around it). We have resolved the overloaded function
4299/// to the function declaration Fn, so patch up the expression E to
4300/// refer (possibly indirectly) to Fn.
4301void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4302  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4303    FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4304    E->setType(PE->getSubExpr()->getType());
4305  } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4306    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4307           "Can only take the address of an overloaded function");
4308    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4309      if (Method->isStatic()) {
4310        // Do nothing: static member functions aren't any different
4311        // from non-member functions.
4312      }
4313      else if (QualifiedDeclRefExpr *DRE
4314                 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4315        // We have taken the address of a pointer to member
4316        // function. Perform the computation here so that we get the
4317        // appropriate pointer to member type.
4318        DRE->setDecl(Fn);
4319        DRE->setType(Fn->getType());
4320        QualType ClassType
4321          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4322        E->setType(Context.getMemberPointerType(Fn->getType(),
4323                                                ClassType.getTypePtr()));
4324        return;
4325      }
4326    }
4327    FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
4328    E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
4329  } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4330    assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4331           "Expected overloaded function");
4332    DR->setDecl(Fn);
4333    E->setType(Fn->getType());
4334  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4335    MemExpr->setMemberDecl(Fn);
4336    E->setType(Fn->getType());
4337  } else {
4338    assert(false && "Invalid reference to overloaded function");
4339  }
4340}
4341
4342} // end namespace clang
4343