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