SemaOverload.cpp revision 0777972d38a3125efed962b045704c30ae6965cf
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/AST/ASTContext.h"
18#include "clang/AST/Expr.h"
19#include "llvm/Support/Compiler.h"
20#include <algorithm>
21
22namespace clang {
23
24/// GetConversionCategory - Retrieve the implicit conversion
25/// category corresponding to the given implicit conversion kind.
26ImplicitConversionCategory
27GetConversionCategory(ImplicitConversionKind Kind) {
28  static const ImplicitConversionCategory
29    Category[(int)ICK_Num_Conversion_Kinds] = {
30    ICC_Identity,
31    ICC_Lvalue_Transformation,
32    ICC_Lvalue_Transformation,
33    ICC_Lvalue_Transformation,
34    ICC_Qualification_Adjustment,
35    ICC_Promotion,
36    ICC_Promotion,
37    ICC_Conversion,
38    ICC_Conversion,
39    ICC_Conversion,
40    ICC_Conversion,
41    ICC_Conversion,
42    ICC_Conversion,
43    ICC_Conversion
44  };
45  return Category[(int)Kind];
46}
47
48/// GetConversionRank - Retrieve the implicit conversion rank
49/// corresponding to the given implicit conversion kind.
50ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
51  static const ImplicitConversionRank
52    Rank[(int)ICK_Num_Conversion_Kinds] = {
53    ICR_Exact_Match,
54    ICR_Exact_Match,
55    ICR_Exact_Match,
56    ICR_Exact_Match,
57    ICR_Exact_Match,
58    ICR_Promotion,
59    ICR_Promotion,
60    ICR_Conversion,
61    ICR_Conversion,
62    ICR_Conversion,
63    ICR_Conversion,
64    ICR_Conversion,
65    ICR_Conversion,
66    ICR_Conversion
67  };
68  return Rank[(int)Kind];
69}
70
71/// GetImplicitConversionName - Return the name of this kind of
72/// implicit conversion.
73const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
74  static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
75    "No conversion",
76    "Lvalue-to-rvalue",
77    "Array-to-pointer",
78    "Function-to-pointer",
79    "Qualification",
80    "Integral promotion",
81    "Floating point promotion",
82    "Integral conversion",
83    "Floating conversion",
84    "Floating-integral conversion",
85    "Pointer conversion",
86    "Pointer-to-member conversion",
87    "Boolean conversion",
88    "Derived-to-base conversion"
89  };
90  return Name[Kind];
91}
92
93/// getRank - Retrieve the rank of this standard conversion sequence
94/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
95/// implicit conversions.
96ImplicitConversionRank StandardConversionSequence::getRank() const {
97  ImplicitConversionRank Rank = ICR_Exact_Match;
98  if  (GetConversionRank(First) > Rank)
99    Rank = GetConversionRank(First);
100  if  (GetConversionRank(Second) > Rank)
101    Rank = GetConversionRank(Second);
102  if  (GetConversionRank(Third) > Rank)
103    Rank = GetConversionRank(Third);
104  return Rank;
105}
106
107/// isPointerConversionToBool - Determines whether this conversion is
108/// a conversion of a pointer or pointer-to-member to bool. This is
109/// used as part of the ranking of standard conversion sequences
110/// (C++ 13.3.3.2p4).
111bool StandardConversionSequence::isPointerConversionToBool() const
112{
113  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
114  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
115
116  // Note that FromType has not necessarily been transformed by the
117  // array-to-pointer or function-to-pointer implicit conversions, so
118  // check for their presence as well as checking whether FromType is
119  // a pointer.
120  if (ToType->isBooleanType() &&
121      (FromType->isPointerType() ||
122       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
123    return true;
124
125  return false;
126}
127
128/// isPointerConversionToVoidPointer - Determines whether this
129/// conversion is a conversion of a pointer to a void pointer. This is
130/// used as part of the ranking of standard conversion sequences (C++
131/// 13.3.3.2p4).
132bool
133StandardConversionSequence::
134isPointerConversionToVoidPointer(ASTContext& Context) const
135{
136  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
137  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
138
139  // Note that FromType has not necessarily been transformed by the
140  // array-to-pointer implicit conversion, so check for its presence
141  // and redo the conversion to get a pointer.
142  if (First == ICK_Array_To_Pointer)
143    FromType = Context.getArrayDecayedType(FromType);
144
145  if (Second == ICK_Pointer_Conversion)
146    if (const PointerType* ToPtrType = ToType->getAsPointerType())
147      return ToPtrType->getPointeeType()->isVoidType();
148
149  return false;
150}
151
152/// DebugPrint - Print this standard conversion sequence to standard
153/// error. Useful for debugging overloading issues.
154void StandardConversionSequence::DebugPrint() const {
155  bool PrintedSomething = false;
156  if (First != ICK_Identity) {
157    fprintf(stderr, "%s", GetImplicitConversionName(First));
158    PrintedSomething = true;
159  }
160
161  if (Second != ICK_Identity) {
162    if (PrintedSomething) {
163      fprintf(stderr, " -> ");
164    }
165    fprintf(stderr, "%s", GetImplicitConversionName(Second));
166    PrintedSomething = true;
167  }
168
169  if (Third != ICK_Identity) {
170    if (PrintedSomething) {
171      fprintf(stderr, " -> ");
172    }
173    fprintf(stderr, "%s", GetImplicitConversionName(Third));
174    PrintedSomething = true;
175  }
176
177  if (!PrintedSomething) {
178    fprintf(stderr, "No conversions required");
179  }
180}
181
182/// DebugPrint - Print this user-defined conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void UserDefinedConversionSequence::DebugPrint() const {
185  if (Before.First || Before.Second || Before.Third) {
186    Before.DebugPrint();
187    fprintf(stderr, " -> ");
188  }
189  fprintf(stderr, "'%s'", ConversionFunction->getName());
190  if (After.First || After.Second || After.Third) {
191    fprintf(stderr, " -> ");
192    After.DebugPrint();
193  }
194}
195
196/// DebugPrint - Print this implicit conversion sequence to standard
197/// error. Useful for debugging overloading issues.
198void ImplicitConversionSequence::DebugPrint() const {
199  switch (ConversionKind) {
200  case StandardConversion:
201    fprintf(stderr, "Standard conversion: ");
202    Standard.DebugPrint();
203    break;
204  case UserDefinedConversion:
205    fprintf(stderr, "User-defined conversion: ");
206    UserDefined.DebugPrint();
207    break;
208  case EllipsisConversion:
209    fprintf(stderr, "Ellipsis conversion");
210    break;
211  case BadConversion:
212    fprintf(stderr, "Bad conversion");
213    break;
214  }
215
216  fprintf(stderr, "\n");
217}
218
219// IsOverload - Determine whether the given New declaration is an
220// overload of the Old declaration. This routine returns false if New
221// and Old cannot be overloaded, e.g., if they are functions with the
222// same signature (C++ 1.3.10) or if the Old declaration isn't a
223// function (or overload set). When it does return false and Old is an
224// OverloadedFunctionDecl, MatchedDecl will be set to point to the
225// FunctionDecl that New cannot be overloaded with.
226//
227// Example: Given the following input:
228//
229//   void f(int, float); // #1
230//   void f(int, int); // #2
231//   int f(int, int); // #3
232//
233// When we process #1, there is no previous declaration of "f",
234// so IsOverload will not be used.
235//
236// When we process #2, Old is a FunctionDecl for #1.  By comparing the
237// parameter types, we see that #1 and #2 are overloaded (since they
238// have different signatures), so this routine returns false;
239// MatchedDecl is unchanged.
240//
241// When we process #3, Old is an OverloadedFunctionDecl containing #1
242// and #2. We compare the signatures of #3 to #1 (they're overloaded,
243// so we do nothing) and then #3 to #2. Since the signatures of #3 and
244// #2 are identical (return types of functions are not part of the
245// signature), IsOverload returns false and MatchedDecl will be set to
246// point to the FunctionDecl for #2.
247bool
248Sema::IsOverload(FunctionDecl *New, Decl* OldD,
249                 OverloadedFunctionDecl::function_iterator& MatchedDecl)
250{
251  if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
252    // Is this new function an overload of every function in the
253    // overload set?
254    OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
255                                           FuncEnd = Ovl->function_end();
256    for (; Func != FuncEnd; ++Func) {
257      if (!IsOverload(New, *Func, MatchedDecl)) {
258        MatchedDecl = Func;
259        return false;
260      }
261    }
262
263    // This function overloads every function in the overload set.
264    return true;
265  } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
266    // Is the function New an overload of the function Old?
267    QualType OldQType = Context.getCanonicalType(Old->getType());
268    QualType NewQType = Context.getCanonicalType(New->getType());
269
270    // Compare the signatures (C++ 1.3.10) of the two functions to
271    // determine whether they are overloads. If we find any mismatch
272    // in the signature, they are overloads.
273
274    // If either of these functions is a K&R-style function (no
275    // prototype), then we consider them to have matching signatures.
276    if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
277        isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
278      return false;
279
280    FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
281    FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
282
283    // The signature of a function includes the types of its
284    // parameters (C++ 1.3.10), which includes the presence or absence
285    // of the ellipsis; see C++ DR 357).
286    if (OldQType != NewQType &&
287        (OldType->getNumArgs() != NewType->getNumArgs() ||
288         OldType->isVariadic() != NewType->isVariadic() ||
289         !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
290                     NewType->arg_type_begin())))
291      return true;
292
293    // If the function is a class member, its signature includes the
294    // cv-qualifiers (if any) on the function itself.
295    //
296    // As part of this, also check whether one of the member functions
297    // is static, in which case they are not overloads (C++
298    // 13.1p2). While not part of the definition of the signature,
299    // this check is important to determine whether these functions
300    // can be overloaded.
301    CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
302    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
303    if (OldMethod && NewMethod &&
304        !OldMethod->isStatic() && !NewMethod->isStatic() &&
305        OldQType.getCVRQualifiers() != NewQType.getCVRQualifiers())
306      return true;
307
308    // The signatures match; this is not an overload.
309    return false;
310  } else {
311    // (C++ 13p1):
312    //   Only function declarations can be overloaded; object and type
313    //   declarations cannot be overloaded.
314    return false;
315  }
316}
317
318/// TryImplicitConversion - Attempt to perform an implicit conversion
319/// from the given expression (Expr) to the given type (ToType). This
320/// function returns an implicit conversion sequence that can be used
321/// to perform the initialization. Given
322///
323///   void f(float f);
324///   void g(int i) { f(i); }
325///
326/// this routine would produce an implicit conversion sequence to
327/// describe the initialization of f from i, which will be a standard
328/// conversion sequence containing an lvalue-to-rvalue conversion (C++
329/// 4.1) followed by a floating-integral conversion (C++ 4.9).
330//
331/// Note that this routine only determines how the conversion can be
332/// performed; it does not actually perform the conversion. As such,
333/// it will not produce any diagnostics if no conversion is available,
334/// but will instead return an implicit conversion sequence of kind
335/// "BadConversion".
336ImplicitConversionSequence
337Sema::TryImplicitConversion(Expr* From, QualType ToType)
338{
339  ImplicitConversionSequence ICS;
340
341  QualType FromType = From->getType();
342
343  // Standard conversions (C++ 4)
344  ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
345  ICS.Standard.Deprecated = false;
346  ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
347
348  // The first conversion can be an lvalue-to-rvalue conversion,
349  // array-to-pointer conversion, or function-to-pointer conversion
350  // (C++ 4p1).
351
352  // Lvalue-to-rvalue conversion (C++ 4.1):
353  //   An lvalue (3.10) of a non-function, non-array type T can be
354  //   converted to an rvalue.
355  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
356  if (argIsLvalue == Expr::LV_Valid &&
357      !FromType->isFunctionType() && !FromType->isArrayType()) {
358    ICS.Standard.First = ICK_Lvalue_To_Rvalue;
359
360    // If T is a non-class type, the type of the rvalue is the
361    // cv-unqualified version of T. Otherwise, the type of the rvalue
362    // is T (C++ 4.1p1).
363    if (!FromType->isRecordType())
364      FromType = FromType.getUnqualifiedType();
365  }
366  // Array-to-pointer conversion (C++ 4.2)
367  else if (FromType->isArrayType()) {
368    ICS.Standard.First = ICK_Array_To_Pointer;
369
370    // An lvalue or rvalue of type "array of N T" or "array of unknown
371    // bound of T" can be converted to an rvalue of type "pointer to
372    // T" (C++ 4.2p1).
373    FromType = Context.getArrayDecayedType(FromType);
374
375    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
376      // This conversion is deprecated. (C++ D.4).
377      ICS.Standard.Deprecated = true;
378
379      // For the purpose of ranking in overload resolution
380      // (13.3.3.1.1), this conversion is considered an
381      // array-to-pointer conversion followed by a qualification
382      // conversion (4.4). (C++ 4.2p2)
383      ICS.Standard.Second = ICK_Identity;
384      ICS.Standard.Third = ICK_Qualification;
385      ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
386      return ICS;
387    }
388  }
389  // Function-to-pointer conversion (C++ 4.3).
390  else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
391    ICS.Standard.First = ICK_Function_To_Pointer;
392
393    // An lvalue of function type T can be converted to an rvalue of
394    // type "pointer to T." The result is a pointer to the
395    // function. (C++ 4.3p1).
396    FromType = Context.getPointerType(FromType);
397
398    // FIXME: Deal with overloaded functions here (C++ 4.3p2).
399  }
400  // We don't require any conversions for the first step.
401  else {
402    ICS.Standard.First = ICK_Identity;
403  }
404
405  // The second conversion can be an integral promotion, floating
406  // point promotion, integral conversion, floating point conversion,
407  // floating-integral conversion, pointer conversion,
408  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
409  if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
410      Context.getCanonicalType(ToType).getUnqualifiedType()) {
411    // The unqualified versions of the types are the same: there's no
412    // conversion to do.
413    ICS.Standard.Second = ICK_Identity;
414  }
415  // Integral promotion (C++ 4.5).
416  else if (IsIntegralPromotion(From, FromType, ToType)) {
417    ICS.Standard.Second = ICK_Integral_Promotion;
418    FromType = ToType.getUnqualifiedType();
419  }
420  // Floating point promotion (C++ 4.6).
421  else if (IsFloatingPointPromotion(FromType, ToType)) {
422    ICS.Standard.Second = ICK_Floating_Promotion;
423    FromType = ToType.getUnqualifiedType();
424  }
425  // Integral conversions (C++ 4.7).
426  // FIXME: isIntegralType shouldn't be true for enums in C++.
427  else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
428           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
429    ICS.Standard.Second = ICK_Integral_Conversion;
430    FromType = ToType.getUnqualifiedType();
431  }
432  // Floating point conversions (C++ 4.8).
433  else if (FromType->isFloatingType() && ToType->isFloatingType()) {
434    ICS.Standard.Second = ICK_Floating_Conversion;
435    FromType = ToType.getUnqualifiedType();
436  }
437  // Floating-integral conversions (C++ 4.9).
438  // FIXME: isIntegralType shouldn't be true for enums in C++.
439  else if ((FromType->isFloatingType() &&
440            ToType->isIntegralType() && !ToType->isBooleanType() &&
441                                        !ToType->isEnumeralType()) ||
442           ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
443            ToType->isFloatingType())) {
444    ICS.Standard.Second = ICK_Floating_Integral;
445    FromType = ToType.getUnqualifiedType();
446  }
447  // Pointer conversions (C++ 4.10).
448  else if (IsPointerConversion(From, FromType, ToType, FromType)) {
449    ICS.Standard.Second = ICK_Pointer_Conversion;
450  }
451  // FIXME: Pointer to member conversions (4.11).
452  // Boolean conversions (C++ 4.12).
453  // FIXME: pointer-to-member type
454  else if (ToType->isBooleanType() &&
455           (FromType->isArithmeticType() ||
456            FromType->isEnumeralType() ||
457            FromType->isPointerType())) {
458    ICS.Standard.Second = ICK_Boolean_Conversion;
459    FromType = Context.BoolTy;
460  } else {
461    // No second conversion required.
462    ICS.Standard.Second = ICK_Identity;
463  }
464
465  QualType CanonFrom;
466  QualType CanonTo;
467  // The third conversion can be a qualification conversion (C++ 4p1).
468  if (IsQualificationConversion(FromType, ToType)) {
469    ICS.Standard.Third = ICK_Qualification;
470    FromType = ToType;
471    CanonFrom = Context.getCanonicalType(FromType);
472    CanonTo = Context.getCanonicalType(ToType);
473  } else {
474    // No conversion required
475    ICS.Standard.Third = ICK_Identity;
476
477    // C++ [dcl.init]p14 last bullet:
478    //   [ Note: an expression of type "cv1 T" can initialize an object
479    //   of type “cv2 T” independently of the cv-qualifiers cv1 and
480    //   cv2. -- end note]
481    //
482    // FIXME: Where is the normative text?
483    CanonFrom = Context.getCanonicalType(FromType);
484    CanonTo = Context.getCanonicalType(ToType);
485    if (!FromType->isRecordType() &&
486        CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
487        CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
488      FromType = ToType;
489      CanonFrom = CanonTo;
490    }
491  }
492
493  // If we have not converted the argument type to the parameter type,
494  // this is a bad conversion sequence.
495  if (CanonFrom != CanonTo)
496    ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
497
498  ICS.Standard.ToTypePtr = FromType.getAsOpaquePtr();
499  return ICS;
500}
501
502/// IsIntegralPromotion - Determines whether the conversion from the
503/// expression From (whose potentially-adjusted type is FromType) to
504/// ToType is an integral promotion (C++ 4.5). If so, returns true and
505/// sets PromotedType to the promoted type.
506bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
507{
508  const BuiltinType *To = ToType->getAsBuiltinType();
509  if (!To) {
510    return false;
511  }
512
513  // An rvalue of type char, signed char, unsigned char, short int, or
514  // unsigned short int can be converted to an rvalue of type int if
515  // int can represent all the values of the source type; otherwise,
516  // the source rvalue can be converted to an rvalue of type unsigned
517  // int (C++ 4.5p1).
518  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
519    if (// We can promote any signed, promotable integer type to an int
520        (FromType->isSignedIntegerType() ||
521         // We can promote any unsigned integer type whose size is
522         // less than int to an int.
523         (!FromType->isSignedIntegerType() &&
524          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
525      return To->getKind() == BuiltinType::Int;
526    }
527
528    return To->getKind() == BuiltinType::UInt;
529  }
530
531  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
532  // can be converted to an rvalue of the first of the following types
533  // that can represent all the values of its underlying type: int,
534  // unsigned int, long, or unsigned long (C++ 4.5p2).
535  if ((FromType->isEnumeralType() || FromType->isWideCharType())
536      && ToType->isIntegerType()) {
537    // Determine whether the type we're converting from is signed or
538    // unsigned.
539    bool FromIsSigned;
540    uint64_t FromSize = Context.getTypeSize(FromType);
541    if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
542      QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
543      FromIsSigned = UnderlyingType->isSignedIntegerType();
544    } else {
545      // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
546      FromIsSigned = true;
547    }
548
549    // The types we'll try to promote to, in the appropriate
550    // order. Try each of these types.
551    QualType PromoteTypes[4] = {
552      Context.IntTy, Context.UnsignedIntTy,
553      Context.LongTy, Context.UnsignedLongTy
554    };
555    for (int Idx = 0; Idx < 0; ++Idx) {
556      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
557      if (FromSize < ToSize ||
558          (FromSize == ToSize &&
559           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
560        // We found the type that we can promote to. If this is the
561        // type we wanted, we have a promotion. Otherwise, no
562        // promotion.
563        return Context.getCanonicalType(ToType).getUnqualifiedType()
564          == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
565      }
566    }
567  }
568
569  // An rvalue for an integral bit-field (9.6) can be converted to an
570  // rvalue of type int if int can represent all the values of the
571  // bit-field; otherwise, it can be converted to unsigned int if
572  // unsigned int can represent all the values of the bit-field. If
573  // the bit-field is larger yet, no integral promotion applies to
574  // it. If the bit-field has an enumerated type, it is treated as any
575  // other value of that type for promotion purposes (C++ 4.5p3).
576  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
577    using llvm::APSInt;
578    FieldDecl *MemberDecl = MemRef->getMemberDecl();
579    APSInt BitWidth;
580    if (MemberDecl->isBitField() &&
581        FromType->isIntegralType() && !FromType->isEnumeralType() &&
582        From->isIntegerConstantExpr(BitWidth, Context)) {
583      APSInt ToSize(Context.getTypeSize(ToType));
584
585      // Are we promoting to an int from a bitfield that fits in an int?
586      if (BitWidth < ToSize ||
587          (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
588        return To->getKind() == BuiltinType::Int;
589      }
590
591      // Are we promoting to an unsigned int from an unsigned bitfield
592      // that fits into an unsigned int?
593      if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
594        return To->getKind() == BuiltinType::UInt;
595      }
596
597      return false;
598    }
599  }
600
601  // An rvalue of type bool can be converted to an rvalue of type int,
602  // with false becoming zero and true becoming one (C++ 4.5p4).
603  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
604    return true;
605  }
606
607  return false;
608}
609
610/// IsFloatingPointPromotion - Determines whether the conversion from
611/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
612/// returns true and sets PromotedType to the promoted type.
613bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
614{
615  /// An rvalue of type float can be converted to an rvalue of type
616  /// double. (C++ 4.6p1).
617  if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
618    if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
619      if (FromBuiltin->getKind() == BuiltinType::Float &&
620          ToBuiltin->getKind() == BuiltinType::Double)
621        return true;
622
623  return false;
624}
625
626/// IsPointerConversion - Determines whether the conversion of the
627/// expression From, which has the (possibly adjusted) type FromType,
628/// can be converted to the type ToType via a pointer conversion (C++
629/// 4.10). If so, returns true and places the converted type (that
630/// might differ from ToType in its cv-qualifiers at some level) into
631/// ConvertedType.
632bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
633                               QualType& ConvertedType)
634{
635  const PointerType* ToTypePtr = ToType->getAsPointerType();
636  if (!ToTypePtr)
637    return false;
638
639  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
640  if (From->isNullPointerConstant(Context)) {
641    ConvertedType = ToType;
642    return true;
643  }
644
645  // An rvalue of type "pointer to cv T," where T is an object type,
646  // can be converted to an rvalue of type "pointer to cv void" (C++
647  // 4.10p2).
648  if (FromType->isPointerType() &&
649      FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
650      ToTypePtr->getPointeeType()->isVoidType()) {
651    // We need to produce a pointer to cv void, where cv is the same
652    // set of cv-qualifiers as we had on the incoming pointee type.
653    QualType toPointee = ToTypePtr->getPointeeType();
654    unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
655                   ->getPointeeType().getCVRQualifiers();
656
657    if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
658	  == Quals) {
659      // ToType is exactly the type we want. Use it.
660      ConvertedType = ToType;
661    } else {
662      // Build a new type with the right qualifiers.
663      ConvertedType
664	= Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
665    }
666    return true;
667  }
668
669  // C++ [conv.ptr]p3:
670  //
671  //   An rvalue of type "pointer to cv D," where D is a class type,
672  //   can be converted to an rvalue of type "pointer to cv B," where
673  //   B is a base class (clause 10) of D. If B is an inaccessible
674  //   (clause 11) or ambiguous (10.2) base class of D, a program that
675  //   necessitates this conversion is ill-formed. The result of the
676  //   conversion is a pointer to the base class sub-object of the
677  //   derived class object. The null pointer value is converted to
678  //   the null pointer value of the destination type.
679  //
680  // Note that we do not check for ambiguity or inaccessibility
681  // here. That is handled by CheckPointerConversion.
682  if (const PointerType *FromPtrType = FromType->getAsPointerType())
683    if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
684      if (FromPtrType->getPointeeType()->isRecordType() &&
685          ToPtrType->getPointeeType()->isRecordType() &&
686          IsDerivedFrom(FromPtrType->getPointeeType(),
687                        ToPtrType->getPointeeType())) {
688        // The conversion is okay. Now, we need to produce the type
689        // that results from this conversion, which will have the same
690        // qualifiers as the incoming type.
691        QualType CanonFromPointee
692          = Context.getCanonicalType(FromPtrType->getPointeeType());
693        QualType ToPointee = ToPtrType->getPointeeType();
694        QualType CanonToPointee = Context.getCanonicalType(ToPointee);
695        unsigned Quals = CanonFromPointee.getCVRQualifiers();
696
697        if (CanonToPointee.getCVRQualifiers() == Quals) {
698          // ToType is exactly the type we want. Use it.
699          ConvertedType = ToType;
700        } else {
701          // Build a new type with the right qualifiers.
702          ConvertedType
703            = Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
704        }
705        return true;
706      }
707    }
708
709  return false;
710}
711
712/// CheckPointerConversion - Check the pointer conversion from the
713/// expression From to the type ToType. This routine checks for
714/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
715/// conversions for which IsPointerConversion has already returned
716/// true. It returns true and produces a diagnostic if there was an
717/// error, or returns false otherwise.
718bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
719  QualType FromType = From->getType();
720
721  if (const PointerType *FromPtrType = FromType->getAsPointerType())
722    if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
723      BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
724                      /*DetectVirtual=*/false);
725      QualType FromPointeeType = FromPtrType->getPointeeType(),
726               ToPointeeType   = ToPtrType->getPointeeType();
727      if (FromPointeeType->isRecordType() &&
728          ToPointeeType->isRecordType()) {
729        // We must have a derived-to-base conversion. Check an
730        // ambiguous or inaccessible conversion.
731        return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
732                                            From->getExprLoc(),
733                                            From->getSourceRange());
734      }
735    }
736
737  return false;
738}
739
740/// IsQualificationConversion - Determines whether the conversion from
741/// an rvalue of type FromType to ToType is a qualification conversion
742/// (C++ 4.4).
743bool
744Sema::IsQualificationConversion(QualType FromType, QualType ToType)
745{
746  FromType = Context.getCanonicalType(FromType);
747  ToType = Context.getCanonicalType(ToType);
748
749  // If FromType and ToType are the same type, this is not a
750  // qualification conversion.
751  if (FromType == ToType)
752    return false;
753
754  // (C++ 4.4p4):
755  //   A conversion can add cv-qualifiers at levels other than the first
756  //   in multi-level pointers, subject to the following rules: [...]
757  bool PreviousToQualsIncludeConst = true;
758  bool UnwrappedAnyPointer = false;
759  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
760    // Within each iteration of the loop, we check the qualifiers to
761    // determine if this still looks like a qualification
762    // conversion. Then, if all is well, we unwrap one more level of
763    // pointers or pointers-to-members and do it all again
764    // until there are no more pointers or pointers-to-members left to
765    // unwrap.
766    UnwrappedAnyPointer = true;
767
768    //   -- for every j > 0, if const is in cv 1,j then const is in cv
769    //      2,j, and similarly for volatile.
770    if (!ToType.isAtLeastAsQualifiedAs(FromType))
771      return false;
772
773    //   -- if the cv 1,j and cv 2,j are different, then const is in
774    //      every cv for 0 < k < j.
775    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
776        && !PreviousToQualsIncludeConst)
777      return false;
778
779    // Keep track of whether all prior cv-qualifiers in the "to" type
780    // include const.
781    PreviousToQualsIncludeConst
782      = PreviousToQualsIncludeConst && ToType.isConstQualified();
783  }
784
785  // We are left with FromType and ToType being the pointee types
786  // after unwrapping the original FromType and ToType the same number
787  // of types. If we unwrapped any pointers, and if FromType and
788  // ToType have the same unqualified type (since we checked
789  // qualifiers above), then this is a qualification conversion.
790  return UnwrappedAnyPointer &&
791    FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
792}
793
794/// CompareImplicitConversionSequences - Compare two implicit
795/// conversion sequences to determine whether one is better than the
796/// other or if they are indistinguishable (C++ 13.3.3.2).
797ImplicitConversionSequence::CompareKind
798Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
799                                         const ImplicitConversionSequence& ICS2)
800{
801  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
802  // conversion sequences (as defined in 13.3.3.1)
803  //   -- a standard conversion sequence (13.3.3.1.1) is a better
804  //      conversion sequence than a user-defined conversion sequence or
805  //      an ellipsis conversion sequence, and
806  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
807  //      conversion sequence than an ellipsis conversion sequence
808  //      (13.3.3.1.3).
809  //
810  if (ICS1.ConversionKind < ICS2.ConversionKind)
811    return ImplicitConversionSequence::Better;
812  else if (ICS2.ConversionKind < ICS1.ConversionKind)
813    return ImplicitConversionSequence::Worse;
814
815  // Two implicit conversion sequences of the same form are
816  // indistinguishable conversion sequences unless one of the
817  // following rules apply: (C++ 13.3.3.2p3):
818  if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
819    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
820  else if (ICS1.ConversionKind ==
821             ImplicitConversionSequence::UserDefinedConversion) {
822    // User-defined conversion sequence U1 is a better conversion
823    // sequence than another user-defined conversion sequence U2 if
824    // they contain the same user-defined conversion function or
825    // constructor and if the second standard conversion sequence of
826    // U1 is better than the second standard conversion sequence of
827    // U2 (C++ 13.3.3.2p3).
828    if (ICS1.UserDefined.ConversionFunction ==
829          ICS2.UserDefined.ConversionFunction)
830      return CompareStandardConversionSequences(ICS1.UserDefined.After,
831                                                ICS2.UserDefined.After);
832  }
833
834  return ImplicitConversionSequence::Indistinguishable;
835}
836
837/// CompareStandardConversionSequences - Compare two standard
838/// conversion sequences to determine whether one is better than the
839/// other or if they are indistinguishable (C++ 13.3.3.2p3).
840ImplicitConversionSequence::CompareKind
841Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
842                                         const StandardConversionSequence& SCS2)
843{
844  // Standard conversion sequence S1 is a better conversion sequence
845  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
846
847  //  -- S1 is a proper subsequence of S2 (comparing the conversion
848  //     sequences in the canonical form defined by 13.3.3.1.1,
849  //     excluding any Lvalue Transformation; the identity conversion
850  //     sequence is considered to be a subsequence of any
851  //     non-identity conversion sequence) or, if not that,
852  if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
853    // Neither is a proper subsequence of the other. Do nothing.
854    ;
855  else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
856           (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
857           (SCS1.Second == ICK_Identity &&
858            SCS1.Third == ICK_Identity))
859    // SCS1 is a proper subsequence of SCS2.
860    return ImplicitConversionSequence::Better;
861  else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
862           (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
863           (SCS2.Second == ICK_Identity &&
864            SCS2.Third == ICK_Identity))
865    // SCS2 is a proper subsequence of SCS1.
866    return ImplicitConversionSequence::Worse;
867
868  //  -- the rank of S1 is better than the rank of S2 (by the rules
869  //     defined below), or, if not that,
870  ImplicitConversionRank Rank1 = SCS1.getRank();
871  ImplicitConversionRank Rank2 = SCS2.getRank();
872  if (Rank1 < Rank2)
873    return ImplicitConversionSequence::Better;
874  else if (Rank2 < Rank1)
875    return ImplicitConversionSequence::Worse;
876
877  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
878  // are indistinguishable unless one of the following rules
879  // applies:
880
881  //   A conversion that is not a conversion of a pointer, or
882  //   pointer to member, to bool is better than another conversion
883  //   that is such a conversion.
884  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
885    return SCS2.isPointerConversionToBool()
886             ? ImplicitConversionSequence::Better
887             : ImplicitConversionSequence::Worse;
888
889  // C++ [over.ics.rank]p4b2:
890  //
891  //   If class B is derived directly or indirectly from class A,
892  //   conversion of B* to A* is better than conversion of B* to
893  //   void*, and conversion of A* to void* is better than conversion
894  //   of B* to void*.
895  bool SCS1ConvertsToVoid
896    = SCS1.isPointerConversionToVoidPointer(Context);
897  bool SCS2ConvertsToVoid
898    = SCS2.isPointerConversionToVoidPointer(Context);
899  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
900    // Exactly one of the conversion sequences is a conversion to
901    // a void pointer; it's the worse conversion.
902    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
903                              : ImplicitConversionSequence::Worse;
904  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
905    // Neither conversion sequence converts to a void pointer; compare
906    // their derived-to-base conversions.
907    if (ImplicitConversionSequence::CompareKind DerivedCK
908          = CompareDerivedToBaseConversions(SCS1, SCS2))
909      return DerivedCK;
910  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
911    // Both conversion sequences are conversions to void
912    // pointers. Compare the source types to determine if there's an
913    // inheritance relationship in their sources.
914    QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
915    QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
916
917    // Adjust the types we're converting from via the array-to-pointer
918    // conversion, if we need to.
919    if (SCS1.First == ICK_Array_To_Pointer)
920      FromType1 = Context.getArrayDecayedType(FromType1);
921    if (SCS2.First == ICK_Array_To_Pointer)
922      FromType2 = Context.getArrayDecayedType(FromType2);
923
924    QualType FromPointee1
925      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
926    QualType FromPointee2
927      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
928
929    if (IsDerivedFrom(FromPointee2, FromPointee1))
930      return ImplicitConversionSequence::Better;
931    else if (IsDerivedFrom(FromPointee1, FromPointee2))
932      return ImplicitConversionSequence::Worse;
933  }
934
935  // Compare based on qualification conversions (C++ 13.3.3.2p3,
936  // bullet 3).
937  if (ImplicitConversionSequence::CompareKind QualCK
938        = CompareQualificationConversions(SCS1, SCS2))
939    return QualCK;
940
941  // C++ [over.ics.rank]p3b4:
942  //   -- S1 and S2 are reference bindings (8.5.3), and the types to
943  //      which the references refer are the same type except for
944  //      top-level cv-qualifiers, and the type to which the reference
945  //      initialized by S2 refers is more cv-qualified than the type
946  //      to which the reference initialized by S1 refers.
947  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
948    QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
949    QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
950    T1 = Context.getCanonicalType(T1);
951    T2 = Context.getCanonicalType(T2);
952    if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
953      if (T2.isMoreQualifiedThan(T1))
954        return ImplicitConversionSequence::Better;
955      else if (T1.isMoreQualifiedThan(T2))
956        return ImplicitConversionSequence::Worse;
957    }
958  }
959
960  return ImplicitConversionSequence::Indistinguishable;
961}
962
963/// CompareQualificationConversions - Compares two standard conversion
964/// sequences to determine whether they can be ranked based on their
965/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
966ImplicitConversionSequence::CompareKind
967Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
968                                      const StandardConversionSequence& SCS2)
969{
970  // C++ 13.3.3.2p3:
971  //  -- S1 and S2 differ only in their qualification conversion and
972  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
973  //     cv-qualification signature of type T1 is a proper subset of
974  //     the cv-qualification signature of type T2, and S1 is not the
975  //     deprecated string literal array-to-pointer conversion (4.2).
976  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
977      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
978    return ImplicitConversionSequence::Indistinguishable;
979
980  // FIXME: the example in the standard doesn't use a qualification
981  // conversion (!)
982  QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
983  QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
984  T1 = Context.getCanonicalType(T1);
985  T2 = Context.getCanonicalType(T2);
986
987  // If the types are the same, we won't learn anything by unwrapped
988  // them.
989  if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
990    return ImplicitConversionSequence::Indistinguishable;
991
992  ImplicitConversionSequence::CompareKind Result
993    = ImplicitConversionSequence::Indistinguishable;
994  while (UnwrapSimilarPointerTypes(T1, T2)) {
995    // Within each iteration of the loop, we check the qualifiers to
996    // determine if this still looks like a qualification
997    // conversion. Then, if all is well, we unwrap one more level of
998    // pointers or pointers-to-members and do it all again
999    // until there are no more pointers or pointers-to-members left
1000    // to unwrap. This essentially mimics what
1001    // IsQualificationConversion does, but here we're checking for a
1002    // strict subset of qualifiers.
1003    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1004      // The qualifiers are the same, so this doesn't tell us anything
1005      // about how the sequences rank.
1006      ;
1007    else if (T2.isMoreQualifiedThan(T1)) {
1008      // T1 has fewer qualifiers, so it could be the better sequence.
1009      if (Result == ImplicitConversionSequence::Worse)
1010        // Neither has qualifiers that are a subset of the other's
1011        // qualifiers.
1012        return ImplicitConversionSequence::Indistinguishable;
1013
1014      Result = ImplicitConversionSequence::Better;
1015    } else if (T1.isMoreQualifiedThan(T2)) {
1016      // T2 has fewer qualifiers, so it could be the better sequence.
1017      if (Result == ImplicitConversionSequence::Better)
1018        // Neither has qualifiers that are a subset of the other's
1019        // qualifiers.
1020        return ImplicitConversionSequence::Indistinguishable;
1021
1022      Result = ImplicitConversionSequence::Worse;
1023    } else {
1024      // Qualifiers are disjoint.
1025      return ImplicitConversionSequence::Indistinguishable;
1026    }
1027
1028    // If the types after this point are equivalent, we're done.
1029    if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1030      break;
1031  }
1032
1033  // Check that the winning standard conversion sequence isn't using
1034  // the deprecated string literal array to pointer conversion.
1035  switch (Result) {
1036  case ImplicitConversionSequence::Better:
1037    if (SCS1.Deprecated)
1038      Result = ImplicitConversionSequence::Indistinguishable;
1039    break;
1040
1041  case ImplicitConversionSequence::Indistinguishable:
1042    break;
1043
1044  case ImplicitConversionSequence::Worse:
1045    if (SCS2.Deprecated)
1046      Result = ImplicitConversionSequence::Indistinguishable;
1047    break;
1048  }
1049
1050  return Result;
1051}
1052
1053/// CompareDerivedToBaseConversions - Compares two standard conversion
1054/// sequences to determine whether they can be ranked based on their
1055/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3).
1056ImplicitConversionSequence::CompareKind
1057Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1058                                      const StandardConversionSequence& SCS2) {
1059  QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1060  QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1061  QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1062  QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1063
1064  // Adjust the types we're converting from via the array-to-pointer
1065  // conversion, if we need to.
1066  if (SCS1.First == ICK_Array_To_Pointer)
1067    FromType1 = Context.getArrayDecayedType(FromType1);
1068  if (SCS2.First == ICK_Array_To_Pointer)
1069    FromType2 = Context.getArrayDecayedType(FromType2);
1070
1071  // Canonicalize all of the types.
1072  FromType1 = Context.getCanonicalType(FromType1);
1073  ToType1 = Context.getCanonicalType(ToType1);
1074  FromType2 = Context.getCanonicalType(FromType2);
1075  ToType2 = Context.getCanonicalType(ToType2);
1076
1077  // C++ [over.ics.rank]p4b3:
1078  //
1079  //   If class B is derived directly or indirectly from class A and
1080  //   class C is derived directly or indirectly from B,
1081
1082  // Compare based on pointer conversions.
1083  if (SCS1.Second == ICK_Pointer_Conversion &&
1084      SCS2.Second == ICK_Pointer_Conversion) {
1085    QualType FromPointee1
1086      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1087    QualType ToPointee1
1088      = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1089    QualType FromPointee2
1090      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1091    QualType ToPointee2
1092      = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1093    //   -- conversion of C* to B* is better than conversion of C* to A*,
1094    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1095      if (IsDerivedFrom(ToPointee1, ToPointee2))
1096        return ImplicitConversionSequence::Better;
1097      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1098        return ImplicitConversionSequence::Worse;
1099    }
1100
1101    //   -- conversion of B* to A* is better than conversion of C* to A*,
1102    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1103      if (IsDerivedFrom(FromPointee2, FromPointee1))
1104        return ImplicitConversionSequence::Better;
1105      else if (IsDerivedFrom(FromPointee1, FromPointee2))
1106        return ImplicitConversionSequence::Worse;
1107    }
1108  }
1109
1110  // Compare based on reference bindings.
1111  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1112      SCS1.Second == ICK_Derived_To_Base) {
1113    //   -- binding of an expression of type C to a reference of type
1114    //      B& is better than binding an expression of type C to a
1115    //      reference of type A&,
1116    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1117        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1118      if (IsDerivedFrom(ToType1, ToType2))
1119        return ImplicitConversionSequence::Better;
1120      else if (IsDerivedFrom(ToType2, ToType1))
1121        return ImplicitConversionSequence::Worse;
1122    }
1123
1124    //     -- binding of an expression of type B to a reference of type
1125    //        A& is better than binding an expression of type C to a
1126    //        reference of type A&,
1127    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1128        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1129      if (IsDerivedFrom(FromType2, FromType1))
1130        return ImplicitConversionSequence::Better;
1131      else if (IsDerivedFrom(FromType1, FromType2))
1132        return ImplicitConversionSequence::Worse;
1133    }
1134  }
1135
1136
1137  // FIXME: conversion of A::* to B::* is better than conversion of
1138  // A::* to C::*,
1139
1140  // FIXME: conversion of B::* to C::* is better than conversion of
1141  // A::* to C::*, and
1142
1143  // FIXME: conversion of C to B is better than conversion of C to A,
1144
1145  // FIXME: conversion of B to A is better than conversion of C to A.
1146
1147  return ImplicitConversionSequence::Indistinguishable;
1148}
1149
1150/// TryCopyInitialization - Try to copy-initialize a value of type
1151/// ToType from the expression From. Return the implicit conversion
1152/// sequence required to pass this argument, which may be a bad
1153/// conversion sequence (meaning that the argument cannot be passed to
1154/// a parameter of this type). This is user for argument passing,
1155ImplicitConversionSequence
1156Sema::TryCopyInitialization(Expr *From, QualType ToType) {
1157  if (!getLangOptions().CPlusPlus) {
1158    // In C, argument passing is the same as performing an assignment.
1159    AssignConvertType ConvTy =
1160      CheckSingleAssignmentConstraints(ToType, From);
1161    ImplicitConversionSequence ICS;
1162    if (getLangOptions().NoExtensions? ConvTy != Compatible
1163                                     : ConvTy == Incompatible)
1164      ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1165    else
1166      ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1167    return ICS;
1168  } else if (ToType->isReferenceType()) {
1169    ImplicitConversionSequence ICS;
1170    CheckReferenceInit(From, ToType, &ICS);
1171    return ICS;
1172  } else {
1173    return TryImplicitConversion(From, ToType);
1174  }
1175}
1176
1177/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1178/// type ToType. Returns true (and emits a diagnostic) if there was
1179/// an error, returns false if the initialization succeeded.
1180bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1181                                     const char* Flavor) {
1182  if (!getLangOptions().CPlusPlus) {
1183    // In C, argument passing is the same as performing an assignment.
1184    QualType FromType = From->getType();
1185    AssignConvertType ConvTy =
1186      CheckSingleAssignmentConstraints(ToType, From);
1187
1188    return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1189                                    FromType, From, Flavor);
1190  } else if (ToType->isReferenceType()) {
1191    return CheckReferenceInit(From, ToType);
1192  } else {
1193    if (PerformImplicitConversion(From, ToType))
1194      return Diag(From->getSourceRange().getBegin(),
1195                  diag::err_typecheck_convert_incompatible,
1196                  ToType.getAsString(), From->getType().getAsString(),
1197                  Flavor,
1198                  From->getSourceRange());
1199    else
1200      return false;
1201  }
1202}
1203
1204/// AddOverloadCandidate - Adds the given function to the set of
1205/// candidate functions, using the given function call arguments.
1206void
1207Sema::AddOverloadCandidate(FunctionDecl *Function,
1208                           Expr **Args, unsigned NumArgs,
1209                           OverloadCandidateSet& CandidateSet)
1210{
1211  const FunctionTypeProto* Proto
1212    = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1213  assert(Proto && "Functions without a prototype cannot be overloaded");
1214
1215  // Add this candidate
1216  CandidateSet.push_back(OverloadCandidate());
1217  OverloadCandidate& Candidate = CandidateSet.back();
1218  Candidate.Function = Function;
1219
1220  unsigned NumArgsInProto = Proto->getNumArgs();
1221
1222  // (C++ 13.3.2p2): A candidate function having fewer than m
1223  // parameters is viable only if it has an ellipsis in its parameter
1224  // list (8.3.5).
1225  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1226    Candidate.Viable = false;
1227    return;
1228  }
1229
1230  // (C++ 13.3.2p2): A candidate function having more than m parameters
1231  // is viable only if the (m+1)st parameter has a default argument
1232  // (8.3.6). For the purposes of overload resolution, the
1233  // parameter list is truncated on the right, so that there are
1234  // exactly m parameters.
1235  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1236  if (NumArgs < MinRequiredArgs) {
1237    // Not enough arguments.
1238    Candidate.Viable = false;
1239    return;
1240  }
1241
1242  // Determine the implicit conversion sequences for each of the
1243  // arguments.
1244  Candidate.Viable = true;
1245  Candidate.Conversions.resize(NumArgs);
1246  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1247    if (ArgIdx < NumArgsInProto) {
1248      // (C++ 13.3.2p3): for F to be a viable function, there shall
1249      // exist for each argument an implicit conversion sequence
1250      // (13.3.3.1) that converts that argument to the corresponding
1251      // parameter of F.
1252      QualType ParamType = Proto->getArgType(ArgIdx);
1253      Candidate.Conversions[ArgIdx]
1254        = TryCopyInitialization(Args[ArgIdx], ParamType);
1255      if (Candidate.Conversions[ArgIdx].ConversionKind
1256            == ImplicitConversionSequence::BadConversion)
1257        Candidate.Viable = false;
1258    } else {
1259      // (C++ 13.3.2p2): For the purposes of overload resolution, any
1260      // argument for which there is no corresponding parameter is
1261      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1262      Candidate.Conversions[ArgIdx].ConversionKind
1263        = ImplicitConversionSequence::EllipsisConversion;
1264    }
1265  }
1266}
1267
1268/// AddOverloadCandidates - Add all of the function overloads in Ovl
1269/// to the candidate set.
1270void
1271Sema::AddOverloadCandidates(OverloadedFunctionDecl *Ovl,
1272                            Expr **Args, unsigned NumArgs,
1273                            OverloadCandidateSet& CandidateSet)
1274{
1275  for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin();
1276       Func != Ovl->function_end(); ++Func)
1277    AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
1278}
1279
1280/// isBetterOverloadCandidate - Determines whether the first overload
1281/// candidate is a better candidate than the second (C++ 13.3.3p1).
1282bool
1283Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
1284                                const OverloadCandidate& Cand2)
1285{
1286  // Define viable functions to be better candidates than non-viable
1287  // functions.
1288  if (!Cand2.Viable)
1289    return Cand1.Viable;
1290  else if (!Cand1.Viable)
1291    return false;
1292
1293  // FIXME: Deal with the implicit object parameter for static member
1294  // functions. (C++ 13.3.3p1).
1295
1296  // (C++ 13.3.3p1): a viable function F1 is defined to be a better
1297  // function than another viable function F2 if for all arguments i,
1298  // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
1299  // then...
1300  unsigned NumArgs = Cand1.Conversions.size();
1301  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
1302  bool HasBetterConversion = false;
1303  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1304    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
1305                                               Cand2.Conversions[ArgIdx])) {
1306    case ImplicitConversionSequence::Better:
1307      // Cand1 has a better conversion sequence.
1308      HasBetterConversion = true;
1309      break;
1310
1311    case ImplicitConversionSequence::Worse:
1312      // Cand1 can't be better than Cand2.
1313      return false;
1314
1315    case ImplicitConversionSequence::Indistinguishable:
1316      // Do nothing.
1317      break;
1318    }
1319  }
1320
1321  if (HasBetterConversion)
1322    return true;
1323
1324  // FIXME: Several other bullets in (C++ 13.3.3p1) need to be implemented.
1325
1326  return false;
1327}
1328
1329/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
1330/// within an overload candidate set. If overloading is successful,
1331/// the result will be OR_Success and Best will be set to point to the
1332/// best viable function within the candidate set. Otherwise, one of
1333/// several kinds of errors will be returned; see
1334/// Sema::OverloadingResult.
1335Sema::OverloadingResult
1336Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
1337                         OverloadCandidateSet::iterator& Best)
1338{
1339  // Find the best viable function.
1340  Best = CandidateSet.end();
1341  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1342       Cand != CandidateSet.end(); ++Cand) {
1343    if (Cand->Viable) {
1344      if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
1345        Best = Cand;
1346    }
1347  }
1348
1349  // If we didn't find any viable functions, abort.
1350  if (Best == CandidateSet.end())
1351    return OR_No_Viable_Function;
1352
1353  // Make sure that this function is better than every other viable
1354  // function. If not, we have an ambiguity.
1355  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1356       Cand != CandidateSet.end(); ++Cand) {
1357    if (Cand->Viable &&
1358        Cand != Best &&
1359        !isBetterOverloadCandidate(*Best, *Cand))
1360      return OR_Ambiguous;
1361  }
1362
1363  // Best is the best viable function.
1364  return OR_Success;
1365}
1366
1367/// PrintOverloadCandidates - When overload resolution fails, prints
1368/// diagnostic messages containing the candidates in the candidate
1369/// set. If OnlyViable is true, only viable candidates will be printed.
1370void
1371Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
1372                              bool OnlyViable)
1373{
1374  OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1375                             LastCand = CandidateSet.end();
1376  for (; Cand != LastCand; ++Cand) {
1377    if (Cand->Viable ||!OnlyViable)
1378      Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
1379  }
1380}
1381
1382} // end namespace clang
1383