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