blob: 551f61a56e8bdb549b9fa5c31d0854f06b31d524 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- 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"
Douglas Gregor94b1dd22008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#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,
Douglas Gregor15da57e2008-10-29 02:00:59 +000042 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000043 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,
Douglas Gregor15da57e2008-10-29 02:00:59 +000065 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000066 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",
Douglas Gregor15da57e2008-10-29 02:00:59 +000087 "Boolean conversion",
88 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089 };
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
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000128/// 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
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152/// 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
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000318/// 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
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000322///
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
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000337Sema::TryImplicitConversion(Expr* From, QualType ToType)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000338{
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 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
427 (ToType->isIntegralType() || ToType->isEnumeralType())) {
428 ICS.Standard.Second = ICK_Integral_Conversion;
429 FromType = ToType.getUnqualifiedType();
430 }
431 // Floating point conversions (C++ 4.8).
432 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
433 ICS.Standard.Second = ICK_Floating_Conversion;
434 FromType = ToType.getUnqualifiedType();
435 }
436 // Floating-integral conversions (C++ 4.9).
437 else if ((FromType->isFloatingType() &&
438 ToType->isIntegralType() && !ToType->isBooleanType()) ||
439 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
440 ToType->isFloatingType())) {
441 ICS.Standard.Second = ICK_Floating_Integral;
442 FromType = ToType.getUnqualifiedType();
443 }
444 // Pointer conversions (C++ 4.10).
445 else if (IsPointerConversion(From, FromType, ToType, FromType))
446 ICS.Standard.Second = ICK_Pointer_Conversion;
447 // FIXME: Pointer to member conversions (4.11).
448 // Boolean conversions (C++ 4.12).
449 // FIXME: pointer-to-member type
450 else if (ToType->isBooleanType() &&
451 (FromType->isArithmeticType() ||
452 FromType->isEnumeralType() ||
453 FromType->isPointerType())) {
454 ICS.Standard.Second = ICK_Boolean_Conversion;
455 FromType = Context.BoolTy;
456 } else {
457 // No second conversion required.
458 ICS.Standard.Second = ICK_Identity;
459 }
460
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000461 QualType CanonFrom;
462 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000463 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000464 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000465 ICS.Standard.Third = ICK_Qualification;
466 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000467 CanonFrom = Context.getCanonicalType(FromType);
468 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000469 } else {
470 // No conversion required
471 ICS.Standard.Third = ICK_Identity;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000472
473 // C++ [dcl.init]p14 last bullet:
474 // Note: an expression of type "cv1 T" can initialize an object
475 // of type “cv2 T” independently of the cv-qualifiers cv1 and
476 // cv2. -- end note]
477 //
478 // FIXME: Where is the normative text?
479 CanonFrom = Context.getCanonicalType(FromType);
480 CanonTo = Context.getCanonicalType(ToType);
481 if (!FromType->isRecordType() &&
482 CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
483 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
484 FromType = ToType;
485 CanonFrom = CanonTo;
486 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 }
488
489 // If we have not converted the argument type to the parameter type,
490 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000491 if (CanonFrom != CanonTo)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000492 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
493
494 ICS.Standard.ToTypePtr = FromType.getAsOpaquePtr();
495 return ICS;
496}
497
498/// IsIntegralPromotion - Determines whether the conversion from the
499/// expression From (whose potentially-adjusted type is FromType) to
500/// ToType is an integral promotion (C++ 4.5). If so, returns true and
501/// sets PromotedType to the promoted type.
502bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
503{
504 const BuiltinType *To = ToType->getAsBuiltinType();
505
506 // An rvalue of type char, signed char, unsigned char, short int, or
507 // unsigned short int can be converted to an rvalue of type int if
508 // int can represent all the values of the source type; otherwise,
509 // the source rvalue can be converted to an rvalue of type unsigned
510 // int (C++ 4.5p1).
511 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && To) {
512 if (// We can promote any signed, promotable integer type to an int
513 (FromType->isSignedIntegerType() ||
514 // We can promote any unsigned integer type whose size is
515 // less than int to an int.
516 (!FromType->isSignedIntegerType() &&
517 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))))
518 return To->getKind() == BuiltinType::Int;
519
520 return To->getKind() == BuiltinType::UInt;
521 }
522
523 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
524 // can be converted to an rvalue of the first of the following types
525 // that can represent all the values of its underlying type: int,
526 // unsigned int, long, or unsigned long (C++ 4.5p2).
527 if ((FromType->isEnumeralType() || FromType->isWideCharType())
528 && ToType->isIntegerType()) {
529 // Determine whether the type we're converting from is signed or
530 // unsigned.
531 bool FromIsSigned;
532 uint64_t FromSize = Context.getTypeSize(FromType);
533 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
534 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
535 FromIsSigned = UnderlyingType->isSignedIntegerType();
536 } else {
537 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
538 FromIsSigned = true;
539 }
540
541 // The types we'll try to promote to, in the appropriate
542 // order. Try each of these types.
543 QualType PromoteTypes[4] = {
544 Context.IntTy, Context.UnsignedIntTy,
545 Context.LongTy, Context.UnsignedLongTy
546 };
547 for (int Idx = 0; Idx < 0; ++Idx) {
548 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
549 if (FromSize < ToSize ||
550 (FromSize == ToSize &&
551 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
552 // We found the type that we can promote to. If this is the
553 // type we wanted, we have a promotion. Otherwise, no
554 // promotion.
555 return Context.getCanonicalType(FromType).getUnqualifiedType()
556 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
557 }
558 }
559 }
560
561 // An rvalue for an integral bit-field (9.6) can be converted to an
562 // rvalue of type int if int can represent all the values of the
563 // bit-field; otherwise, it can be converted to unsigned int if
564 // unsigned int can represent all the values of the bit-field. If
565 // the bit-field is larger yet, no integral promotion applies to
566 // it. If the bit-field has an enumerated type, it is treated as any
567 // other value of that type for promotion purposes (C++ 4.5p3).
568 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
569 using llvm::APSInt;
570 FieldDecl *MemberDecl = MemRef->getMemberDecl();
571 APSInt BitWidth;
572 if (MemberDecl->isBitField() &&
573 FromType->isIntegralType() && !FromType->isEnumeralType() &&
574 From->isIntegerConstantExpr(BitWidth, Context)) {
575 APSInt ToSize(Context.getTypeSize(ToType));
576
577 // Are we promoting to an int from a bitfield that fits in an int?
578 if (BitWidth < ToSize ||
579 (FromType->isSignedIntegerType() && BitWidth <= ToSize))
580 return To->getKind() == BuiltinType::Int;
581
582 // Are we promoting to an unsigned int from an unsigned bitfield
583 // that fits into an unsigned int?
584 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize)
585 return To->getKind() == BuiltinType::UInt;
586
587 return false;
588 }
589 }
590
591 // An rvalue of type bool can be converted to an rvalue of type int,
592 // with false becoming zero and true becoming one (C++ 4.5p4).
593 if (FromType->isBooleanType() && To && To->getKind() == BuiltinType::Int)
594 return true;
595
596 return false;
597}
598
599/// IsFloatingPointPromotion - Determines whether the conversion from
600/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
601/// returns true and sets PromotedType to the promoted type.
602bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
603{
604 /// An rvalue of type float can be converted to an rvalue of type
605 /// double. (C++ 4.6p1).
606 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
607 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
608 if (FromBuiltin->getKind() == BuiltinType::Float &&
609 ToBuiltin->getKind() == BuiltinType::Double)
610 return true;
611
612 return false;
613}
614
615/// IsPointerConversion - Determines whether the conversion of the
616/// expression From, which has the (possibly adjusted) type FromType,
617/// can be converted to the type ToType via a pointer conversion (C++
618/// 4.10). If so, returns true and places the converted type (that
619/// might differ from ToType in its cv-qualifiers at some level) into
620/// ConvertedType.
621bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
622 QualType& ConvertedType)
623{
624 const PointerType* ToTypePtr = ToType->getAsPointerType();
625 if (!ToTypePtr)
626 return false;
627
628 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
629 if (From->isNullPointerConstant(Context)) {
630 ConvertedType = ToType;
631 return true;
632 }
633
634 // An rvalue of type "pointer to cv T," where T is an object type,
635 // can be converted to an rvalue of type "pointer to cv void" (C++
636 // 4.10p2).
637 if (FromType->isPointerType() &&
638 FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
639 ToTypePtr->getPointeeType()->isVoidType()) {
640 // We need to produce a pointer to cv void, where cv is the same
641 // set of cv-qualifiers as we had on the incoming pointee type.
642 QualType toPointee = ToTypePtr->getPointeeType();
643 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
644 ->getPointeeType().getCVRQualifiers();
645
646 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
647 == Quals) {
648 // ToType is exactly the type we want. Use it.
649 ConvertedType = ToType;
650 } else {
651 // Build a new type with the right qualifiers.
652 ConvertedType
653 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
654 }
655 return true;
656 }
657
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000658 // C++ [conv.ptr]p3:
659 //
660 // An rvalue of type "pointer to cv D," where D is a class type,
661 // can be converted to an rvalue of type "pointer to cv B," where
662 // B is a base class (clause 10) of D. If B is an inaccessible
663 // (clause 11) or ambiguous (10.2) base class of D, a program that
664 // necessitates this conversion is ill-formed. The result of the
665 // conversion is a pointer to the base class sub-object of the
666 // derived class object. The null pointer value is converted to
667 // the null pointer value of the destination type.
668 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000669 // Note that we do not check for ambiguity or inaccessibility
670 // here. That is handled by CheckPointerConversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000671 if (const PointerType *FromPtrType = FromType->getAsPointerType())
672 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
673 if (FromPtrType->getPointeeType()->isRecordType() &&
674 ToPtrType->getPointeeType()->isRecordType() &&
675 IsDerivedFrom(FromPtrType->getPointeeType(),
676 ToPtrType->getPointeeType())) {
677 // The conversion is okay. Now, we need to produce the type
678 // that results from this conversion, which will have the same
679 // qualifiers as the incoming type.
680 QualType CanonFromPointee
681 = Context.getCanonicalType(FromPtrType->getPointeeType());
682 QualType ToPointee = ToPtrType->getPointeeType();
683 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
684 unsigned Quals = CanonFromPointee.getCVRQualifiers();
685
686 if (CanonToPointee.getCVRQualifiers() == Quals) {
687 // ToType is exactly the type we want. Use it.
688 ConvertedType = ToType;
689 } else {
690 // Build a new type with the right qualifiers.
691 ConvertedType
692 = Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
693 }
694 return true;
695 }
696 }
697
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000698 return false;
699}
700
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000701/// CheckPointerConversion - Check the pointer conversion from the
702/// expression From to the type ToType. This routine checks for
703/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
704/// conversions for which IsPointerConversion has already returned
705/// true. It returns true and produces a diagnostic if there was an
706/// error, or returns false otherwise.
707bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
708 QualType FromType = From->getType();
709
710 if (const PointerType *FromPtrType = FromType->getAsPointerType())
711 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
712 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false);
713 QualType FromPointeeType = FromPtrType->getPointeeType(),
714 ToPointeeType = ToPtrType->getPointeeType();
715 if (FromPointeeType->isRecordType() &&
716 ToPointeeType->isRecordType()) {
717 // We must have a derived-to-base conversion. Check an
718 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000719 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
720 From->getExprLoc(),
721 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000722 }
723 }
724
725 return false;
726}
727
Douglas Gregor98cd5992008-10-21 23:43:52 +0000728/// IsQualificationConversion - Determines whether the conversion from
729/// an rvalue of type FromType to ToType is a qualification conversion
730/// (C++ 4.4).
731bool
732Sema::IsQualificationConversion(QualType FromType, QualType ToType)
733{
734 FromType = Context.getCanonicalType(FromType);
735 ToType = Context.getCanonicalType(ToType);
736
737 // If FromType and ToType are the same type, this is not a
738 // qualification conversion.
739 if (FromType == ToType)
740 return false;
741
742 // (C++ 4.4p4):
743 // A conversion can add cv-qualifiers at levels other than the first
744 // in multi-level pointers, subject to the following rules: [...]
745 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000746 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +0000747 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +0000748 // Within each iteration of the loop, we check the qualifiers to
749 // determine if this still looks like a qualification
750 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000751 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +0000752 // until there are no more pointers or pointers-to-members left to
753 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +0000754 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000755
756 // -- for every j > 0, if const is in cv 1,j then const is in cv
757 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +0000758 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +0000759 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000760
Douglas Gregor98cd5992008-10-21 23:43:52 +0000761 // -- if the cv 1,j and cv 2,j are different, then const is in
762 // every cv for 0 < k < j.
763 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +0000764 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +0000765 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000766
Douglas Gregor98cd5992008-10-21 23:43:52 +0000767 // Keep track of whether all prior cv-qualifiers in the "to" type
768 // include const.
769 PreviousToQualsIncludeConst
770 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +0000771 }
Douglas Gregor98cd5992008-10-21 23:43:52 +0000772
773 // We are left with FromType and ToType being the pointee types
774 // after unwrapping the original FromType and ToType the same number
775 // of types. If we unwrapped any pointers, and if FromType and
776 // ToType have the same unqualified type (since we checked
777 // qualifiers above), then this is a qualification conversion.
778 return UnwrappedAnyPointer &&
779 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
780}
781
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000782/// CompareImplicitConversionSequences - Compare two implicit
783/// conversion sequences to determine whether one is better than the
784/// other or if they are indistinguishable (C++ 13.3.3.2).
785ImplicitConversionSequence::CompareKind
786Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
787 const ImplicitConversionSequence& ICS2)
788{
789 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
790 // conversion sequences (as defined in 13.3.3.1)
791 // -- a standard conversion sequence (13.3.3.1.1) is a better
792 // conversion sequence than a user-defined conversion sequence or
793 // an ellipsis conversion sequence, and
794 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
795 // conversion sequence than an ellipsis conversion sequence
796 // (13.3.3.1.3).
797 //
798 if (ICS1.ConversionKind < ICS2.ConversionKind)
799 return ImplicitConversionSequence::Better;
800 else if (ICS2.ConversionKind < ICS1.ConversionKind)
801 return ImplicitConversionSequence::Worse;
802
803 // Two implicit conversion sequences of the same form are
804 // indistinguishable conversion sequences unless one of the
805 // following rules apply: (C++ 13.3.3.2p3):
806 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
807 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
808 else if (ICS1.ConversionKind ==
809 ImplicitConversionSequence::UserDefinedConversion) {
810 // User-defined conversion sequence U1 is a better conversion
811 // sequence than another user-defined conversion sequence U2 if
812 // they contain the same user-defined conversion function or
813 // constructor and if the second standard conversion sequence of
814 // U1 is better than the second standard conversion sequence of
815 // U2 (C++ 13.3.3.2p3).
816 if (ICS1.UserDefined.ConversionFunction ==
817 ICS2.UserDefined.ConversionFunction)
818 return CompareStandardConversionSequences(ICS1.UserDefined.After,
819 ICS2.UserDefined.After);
820 }
821
822 return ImplicitConversionSequence::Indistinguishable;
823}
824
825/// CompareStandardConversionSequences - Compare two standard
826/// conversion sequences to determine whether one is better than the
827/// other or if they are indistinguishable (C++ 13.3.3.2p3).
828ImplicitConversionSequence::CompareKind
829Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
830 const StandardConversionSequence& SCS2)
831{
832 // Standard conversion sequence S1 is a better conversion sequence
833 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
834
835 // -- S1 is a proper subsequence of S2 (comparing the conversion
836 // sequences in the canonical form defined by 13.3.3.1.1,
837 // excluding any Lvalue Transformation; the identity conversion
838 // sequence is considered to be a subsequence of any
839 // non-identity conversion sequence) or, if not that,
840 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
841 // Neither is a proper subsequence of the other. Do nothing.
842 ;
843 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
844 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
845 (SCS1.Second == ICK_Identity &&
846 SCS1.Third == ICK_Identity))
847 // SCS1 is a proper subsequence of SCS2.
848 return ImplicitConversionSequence::Better;
849 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
850 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
851 (SCS2.Second == ICK_Identity &&
852 SCS2.Third == ICK_Identity))
853 // SCS2 is a proper subsequence of SCS1.
854 return ImplicitConversionSequence::Worse;
855
856 // -- the rank of S1 is better than the rank of S2 (by the rules
857 // defined below), or, if not that,
858 ImplicitConversionRank Rank1 = SCS1.getRank();
859 ImplicitConversionRank Rank2 = SCS2.getRank();
860 if (Rank1 < Rank2)
861 return ImplicitConversionSequence::Better;
862 else if (Rank2 < Rank1)
863 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000864
Douglas Gregor57373262008-10-22 14:17:15 +0000865 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
866 // are indistinguishable unless one of the following rules
867 // applies:
868
869 // A conversion that is not a conversion of a pointer, or
870 // pointer to member, to bool is better than another conversion
871 // that is such a conversion.
872 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
873 return SCS2.isPointerConversionToBool()
874 ? ImplicitConversionSequence::Better
875 : ImplicitConversionSequence::Worse;
876
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000877 // C++ [over.ics.rank]p4b2:
878 //
879 // If class B is derived directly or indirectly from class A,
880 // conversion of B* to A* is better than conversion of B* to void*,
881 // and (FIXME) conversion of A* to void* is better than conversion of B*
882 // to void*.
883 bool SCS1ConvertsToVoid
884 = SCS1.isPointerConversionToVoidPointer(Context);
885 bool SCS2ConvertsToVoid
886 = SCS2.isPointerConversionToVoidPointer(Context);
887 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid)
888 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
889 : ImplicitConversionSequence::Worse;
890
891 if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid)
892 if (ImplicitConversionSequence::CompareKind DerivedCK
893 = CompareDerivedToBaseConversions(SCS1, SCS2))
894 return DerivedCK;
Douglas Gregor57373262008-10-22 14:17:15 +0000895
896 // Compare based on qualification conversions (C++ 13.3.3.2p3,
897 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000898 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +0000899 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000900 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +0000901
902 // FIXME: Handle comparison of reference bindings.
903
904 return ImplicitConversionSequence::Indistinguishable;
905}
906
907/// CompareQualificationConversions - Compares two standard conversion
908/// sequences to determine whether they can be ranked based on their
909/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
910ImplicitConversionSequence::CompareKind
911Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
912 const StandardConversionSequence& SCS2)
913{
Douglas Gregorba7e2102008-10-22 15:04:37 +0000914 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +0000915 // -- S1 and S2 differ only in their qualification conversion and
916 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
917 // cv-qualification signature of type T1 is a proper subset of
918 // the cv-qualification signature of type T2, and S1 is not the
919 // deprecated string literal array-to-pointer conversion (4.2).
920 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
921 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
922 return ImplicitConversionSequence::Indistinguishable;
923
924 // FIXME: the example in the standard doesn't use a qualification
925 // conversion (!)
926 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
927 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
928 T1 = Context.getCanonicalType(T1);
929 T2 = Context.getCanonicalType(T2);
930
931 // If the types are the same, we won't learn anything by unwrapped
932 // them.
933 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
934 return ImplicitConversionSequence::Indistinguishable;
935
936 ImplicitConversionSequence::CompareKind Result
937 = ImplicitConversionSequence::Indistinguishable;
938 while (UnwrapSimilarPointerTypes(T1, T2)) {
939 // Within each iteration of the loop, we check the qualifiers to
940 // determine if this still looks like a qualification
941 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000942 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +0000943 // until there are no more pointers or pointers-to-members left
944 // to unwrap. This essentially mimics what
945 // IsQualificationConversion does, but here we're checking for a
946 // strict subset of qualifiers.
947 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
948 // The qualifiers are the same, so this doesn't tell us anything
949 // about how the sequences rank.
950 ;
951 else if (T2.isMoreQualifiedThan(T1)) {
952 // T1 has fewer qualifiers, so it could be the better sequence.
953 if (Result == ImplicitConversionSequence::Worse)
954 // Neither has qualifiers that are a subset of the other's
955 // qualifiers.
956 return ImplicitConversionSequence::Indistinguishable;
957
958 Result = ImplicitConversionSequence::Better;
959 } else if (T1.isMoreQualifiedThan(T2)) {
960 // T2 has fewer qualifiers, so it could be the better sequence.
961 if (Result == ImplicitConversionSequence::Better)
962 // Neither has qualifiers that are a subset of the other's
963 // qualifiers.
964 return ImplicitConversionSequence::Indistinguishable;
965
966 Result = ImplicitConversionSequence::Worse;
967 } else {
968 // Qualifiers are disjoint.
969 return ImplicitConversionSequence::Indistinguishable;
970 }
971
972 // If the types after this point are equivalent, we're done.
973 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
974 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000975 }
976
Douglas Gregor57373262008-10-22 14:17:15 +0000977 // Check that the winning standard conversion sequence isn't using
978 // the deprecated string literal array to pointer conversion.
979 switch (Result) {
980 case ImplicitConversionSequence::Better:
981 if (SCS1.Deprecated)
982 Result = ImplicitConversionSequence::Indistinguishable;
983 break;
984
985 case ImplicitConversionSequence::Indistinguishable:
986 break;
987
988 case ImplicitConversionSequence::Worse:
989 if (SCS2.Deprecated)
990 Result = ImplicitConversionSequence::Indistinguishable;
991 break;
992 }
993
994 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000995}
996
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000997/// CompareDerivedToBaseConversions - Compares two standard conversion
998/// sequences to determine whether they can be ranked based on their
999/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3).
1000ImplicitConversionSequence::CompareKind
1001Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1002 const StandardConversionSequence& SCS2) {
1003 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1004 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1005 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1006 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1007
1008 // Adjust the types we're converting from via the array-to-pointer
1009 // conversion, if we need to.
1010 if (SCS1.First == ICK_Array_To_Pointer)
1011 FromType1 = Context.getArrayDecayedType(FromType1);
1012 if (SCS2.First == ICK_Array_To_Pointer)
1013 FromType2 = Context.getArrayDecayedType(FromType2);
1014
1015 // Canonicalize all of the types.
1016 FromType1 = Context.getCanonicalType(FromType1);
1017 ToType1 = Context.getCanonicalType(ToType1);
1018 FromType2 = Context.getCanonicalType(FromType2);
1019 ToType2 = Context.getCanonicalType(ToType2);
1020
1021 // C++ [over.ics.rank]p4b4:
1022 //
1023 // If class B is derived directly or indirectly from class A and
1024 // class C is derived directly or indirectly from B,
1025 //
1026 // FIXME: Verify that in this section we're talking about the
1027 // unqualified forms of C, B, and A.
1028 if (SCS1.Second == ICK_Pointer_Conversion &&
1029 SCS2.Second == ICK_Pointer_Conversion) {
1030 // -- conversion of C* to B* is better than conversion of C* to A*,
1031 QualType FromPointee1
1032 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1033 QualType ToPointee1
1034 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1035 QualType FromPointee2
1036 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1037 QualType ToPointee2
1038 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1039 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1040 if (IsDerivedFrom(ToPointee1, ToPointee2))
1041 return ImplicitConversionSequence::Better;
1042 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1043 return ImplicitConversionSequence::Worse;
1044 }
1045 }
1046
1047 // FIXME: many more sub-bullets of C++ [over.ics.rank]p4b4 to
1048 // implement.
1049 return ImplicitConversionSequence::Indistinguishable;
1050}
1051
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001052/// TryCopyInitialization - Try to copy-initialize a value of type
1053/// ToType from the expression From. Return the implicit conversion
1054/// sequence required to pass this argument, which may be a bad
1055/// conversion sequence (meaning that the argument cannot be passed to
1056/// a parameter of this type). This is user for argument passing,
1057ImplicitConversionSequence
1058Sema::TryCopyInitialization(Expr *From, QualType ToType) {
1059 if (!getLangOptions().CPlusPlus) {
1060 // In C, argument passing is the same as performing an assignment.
1061 AssignConvertType ConvTy =
1062 CheckSingleAssignmentConstraints(ToType, From);
1063 ImplicitConversionSequence ICS;
1064 if (getLangOptions().NoExtensions? ConvTy != Compatible
1065 : ConvTy == Incompatible)
1066 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1067 else
1068 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1069 return ICS;
1070 } else if (ToType->isReferenceType()) {
1071 ImplicitConversionSequence ICS;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001072 CheckReferenceInit(From, ToType, &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001073 return ICS;
1074 } else {
1075 return TryImplicitConversion(From, ToType);
1076 }
1077}
1078
1079/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1080/// type ToType. Returns true (and emits a diagnostic) if there was
1081/// an error, returns false if the initialization succeeded.
1082bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1083 const char* Flavor) {
1084 if (!getLangOptions().CPlusPlus) {
1085 // In C, argument passing is the same as performing an assignment.
1086 QualType FromType = From->getType();
1087 AssignConvertType ConvTy =
1088 CheckSingleAssignmentConstraints(ToType, From);
1089
1090 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1091 FromType, From, Flavor);
1092 } else if (ToType->isReferenceType()) {
1093 return CheckReferenceInit(From, ToType);
1094 } else {
1095 if (PerformImplicitConversion(From, ToType))
1096 return Diag(From->getSourceRange().getBegin(),
1097 diag::err_typecheck_convert_incompatible,
1098 ToType.getAsString(), From->getType().getAsString(),
1099 Flavor,
1100 From->getSourceRange());
1101 else
1102 return false;
1103 }
1104}
1105
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001106/// AddOverloadCandidate - Adds the given function to the set of
1107/// candidate functions, using the given function call arguments.
1108void
1109Sema::AddOverloadCandidate(FunctionDecl *Function,
1110 Expr **Args, unsigned NumArgs,
1111 OverloadCandidateSet& CandidateSet)
1112{
1113 const FunctionTypeProto* Proto
1114 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1115 assert(Proto && "Functions without a prototype cannot be overloaded");
1116
1117 // Add this candidate
1118 CandidateSet.push_back(OverloadCandidate());
1119 OverloadCandidate& Candidate = CandidateSet.back();
1120 Candidate.Function = Function;
1121
1122 unsigned NumArgsInProto = Proto->getNumArgs();
1123
1124 // (C++ 13.3.2p2): A candidate function having fewer than m
1125 // parameters is viable only if it has an ellipsis in its parameter
1126 // list (8.3.5).
1127 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1128 Candidate.Viable = false;
1129 return;
1130 }
1131
1132 // (C++ 13.3.2p2): A candidate function having more than m parameters
1133 // is viable only if the (m+1)st parameter has a default argument
1134 // (8.3.6). For the purposes of overload resolution, the
1135 // parameter list is truncated on the right, so that there are
1136 // exactly m parameters.
1137 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1138 if (NumArgs < MinRequiredArgs) {
1139 // Not enough arguments.
1140 Candidate.Viable = false;
1141 return;
1142 }
1143
1144 // Determine the implicit conversion sequences for each of the
1145 // arguments.
1146 Candidate.Viable = true;
1147 Candidate.Conversions.resize(NumArgs);
1148 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1149 if (ArgIdx < NumArgsInProto) {
1150 // (C++ 13.3.2p3): for F to be a viable function, there shall
1151 // exist for each argument an implicit conversion sequence
1152 // (13.3.3.1) that converts that argument to the corresponding
1153 // parameter of F.
1154 QualType ParamType = Proto->getArgType(ArgIdx);
1155 Candidate.Conversions[ArgIdx]
1156 = TryCopyInitialization(Args[ArgIdx], ParamType);
1157 if (Candidate.Conversions[ArgIdx].ConversionKind
1158 == ImplicitConversionSequence::BadConversion)
1159 Candidate.Viable = false;
1160 } else {
1161 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1162 // argument for which there is no corresponding parameter is
1163 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1164 Candidate.Conversions[ArgIdx].ConversionKind
1165 = ImplicitConversionSequence::EllipsisConversion;
1166 }
1167 }
1168}
1169
1170/// AddOverloadCandidates - Add all of the function overloads in Ovl
1171/// to the candidate set.
1172void
1173Sema::AddOverloadCandidates(OverloadedFunctionDecl *Ovl,
1174 Expr **Args, unsigned NumArgs,
1175 OverloadCandidateSet& CandidateSet)
1176{
1177 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin();
1178 Func != Ovl->function_end(); ++Func)
1179 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
1180}
1181
1182/// isBetterOverloadCandidate - Determines whether the first overload
1183/// candidate is a better candidate than the second (C++ 13.3.3p1).
1184bool
1185Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
1186 const OverloadCandidate& Cand2)
1187{
1188 // Define viable functions to be better candidates than non-viable
1189 // functions.
1190 if (!Cand2.Viable)
1191 return Cand1.Viable;
1192 else if (!Cand1.Viable)
1193 return false;
1194
1195 // FIXME: Deal with the implicit object parameter for static member
1196 // functions. (C++ 13.3.3p1).
1197
1198 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
1199 // function than another viable function F2 if for all arguments i,
1200 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
1201 // then...
1202 unsigned NumArgs = Cand1.Conversions.size();
1203 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
1204 bool HasBetterConversion = false;
1205 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1206 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
1207 Cand2.Conversions[ArgIdx])) {
1208 case ImplicitConversionSequence::Better:
1209 // Cand1 has a better conversion sequence.
1210 HasBetterConversion = true;
1211 break;
1212
1213 case ImplicitConversionSequence::Worse:
1214 // Cand1 can't be better than Cand2.
1215 return false;
1216
1217 case ImplicitConversionSequence::Indistinguishable:
1218 // Do nothing.
1219 break;
1220 }
1221 }
1222
1223 if (HasBetterConversion)
1224 return true;
1225
1226 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be implemented.
1227
1228 return false;
1229}
1230
1231/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
1232/// within an overload candidate set. If overloading is successful,
1233/// the result will be OR_Success and Best will be set to point to the
1234/// best viable function within the candidate set. Otherwise, one of
1235/// several kinds of errors will be returned; see
1236/// Sema::OverloadingResult.
1237Sema::OverloadingResult
1238Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
1239 OverloadCandidateSet::iterator& Best)
1240{
1241 // Find the best viable function.
1242 Best = CandidateSet.end();
1243 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1244 Cand != CandidateSet.end(); ++Cand) {
1245 if (Cand->Viable) {
1246 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
1247 Best = Cand;
1248 }
1249 }
1250
1251 // If we didn't find any viable functions, abort.
1252 if (Best == CandidateSet.end())
1253 return OR_No_Viable_Function;
1254
1255 // Make sure that this function is better than every other viable
1256 // function. If not, we have an ambiguity.
1257 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1258 Cand != CandidateSet.end(); ++Cand) {
1259 if (Cand->Viable &&
1260 Cand != Best &&
1261 !isBetterOverloadCandidate(*Best, *Cand))
1262 return OR_Ambiguous;
1263 }
1264
1265 // Best is the best viable function.
1266 return OR_Success;
1267}
1268
1269/// PrintOverloadCandidates - When overload resolution fails, prints
1270/// diagnostic messages containing the candidates in the candidate
1271/// set. If OnlyViable is true, only viable candidates will be printed.
1272void
1273Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
1274 bool OnlyViable)
1275{
1276 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1277 LastCand = CandidateSet.end();
1278 for (; Cand != LastCand; ++Cand) {
1279 if (Cand->Viable ||!OnlyViable)
1280 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
1281 }
1282}
1283
1284} // end namespace clang