blob: 6d01709c5b0801a27bfab283405d32dcca15f5c2 [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"
15#include "clang/Basic/Diagnostic.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
18#include "llvm/Support/Compiler.h"
19#include <algorithm>
20
21namespace clang {
22
23/// GetConversionCategory - Retrieve the implicit conversion
24/// category corresponding to the given implicit conversion kind.
25ImplicitConversionCategory
26GetConversionCategory(ImplicitConversionKind Kind) {
27 static const ImplicitConversionCategory
28 Category[(int)ICK_Num_Conversion_Kinds] = {
29 ICC_Identity,
30 ICC_Lvalue_Transformation,
31 ICC_Lvalue_Transformation,
32 ICC_Lvalue_Transformation,
33 ICC_Qualification_Adjustment,
34 ICC_Promotion,
35 ICC_Promotion,
36 ICC_Conversion,
37 ICC_Conversion,
38 ICC_Conversion,
39 ICC_Conversion,
40 ICC_Conversion,
41 ICC_Conversion
42 };
43 return Category[(int)Kind];
44}
45
46/// GetConversionRank - Retrieve the implicit conversion rank
47/// corresponding to the given implicit conversion kind.
48ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
49 static const ImplicitConversionRank
50 Rank[(int)ICK_Num_Conversion_Kinds] = {
51 ICR_Exact_Match,
52 ICR_Exact_Match,
53 ICR_Exact_Match,
54 ICR_Exact_Match,
55 ICR_Exact_Match,
56 ICR_Promotion,
57 ICR_Promotion,
58 ICR_Conversion,
59 ICR_Conversion,
60 ICR_Conversion,
61 ICR_Conversion,
62 ICR_Conversion,
63 ICR_Conversion
64 };
65 return Rank[(int)Kind];
66}
67
68/// GetImplicitConversionName - Return the name of this kind of
69/// implicit conversion.
70const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
71 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
72 "No conversion",
73 "Lvalue-to-rvalue",
74 "Array-to-pointer",
75 "Function-to-pointer",
76 "Qualification",
77 "Integral promotion",
78 "Floating point promotion",
79 "Integral conversion",
80 "Floating conversion",
81 "Floating-integral conversion",
82 "Pointer conversion",
83 "Pointer-to-member conversion",
84 "Boolean conversion"
85 };
86 return Name[Kind];
87}
88
89/// getRank - Retrieve the rank of this standard conversion sequence
90/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
91/// implicit conversions.
92ImplicitConversionRank StandardConversionSequence::getRank() const {
93 ImplicitConversionRank Rank = ICR_Exact_Match;
94 if (GetConversionRank(First) > Rank)
95 Rank = GetConversionRank(First);
96 if (GetConversionRank(Second) > Rank)
97 Rank = GetConversionRank(Second);
98 if (GetConversionRank(Third) > Rank)
99 Rank = GetConversionRank(Third);
100 return Rank;
101}
102
103/// isPointerConversionToBool - Determines whether this conversion is
104/// a conversion of a pointer or pointer-to-member to bool. This is
105/// used as part of the ranking of standard conversion sequences
106/// (C++ 13.3.3.2p4).
107bool StandardConversionSequence::isPointerConversionToBool() const
108{
109 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
110 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
111
112 // Note that FromType has not necessarily been transformed by the
113 // array-to-pointer or function-to-pointer implicit conversions, so
114 // check for their presence as well as checking whether FromType is
115 // a pointer.
116 if (ToType->isBooleanType() &&
117 (FromType->isPointerType() ||
118 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
119 return true;
120
121 return false;
122}
123
124/// DebugPrint - Print this standard conversion sequence to standard
125/// error. Useful for debugging overloading issues.
126void StandardConversionSequence::DebugPrint() const {
127 bool PrintedSomething = false;
128 if (First != ICK_Identity) {
129 fprintf(stderr, "%s", GetImplicitConversionName(First));
130 PrintedSomething = true;
131 }
132
133 if (Second != ICK_Identity) {
134 if (PrintedSomething) {
135 fprintf(stderr, " -> ");
136 }
137 fprintf(stderr, "%s", GetImplicitConversionName(Second));
138 PrintedSomething = true;
139 }
140
141 if (Third != ICK_Identity) {
142 if (PrintedSomething) {
143 fprintf(stderr, " -> ");
144 }
145 fprintf(stderr, "%s", GetImplicitConversionName(Third));
146 PrintedSomething = true;
147 }
148
149 if (!PrintedSomething) {
150 fprintf(stderr, "No conversions required");
151 }
152}
153
154/// DebugPrint - Print this user-defined conversion sequence to standard
155/// error. Useful for debugging overloading issues.
156void UserDefinedConversionSequence::DebugPrint() const {
157 if (Before.First || Before.Second || Before.Third) {
158 Before.DebugPrint();
159 fprintf(stderr, " -> ");
160 }
161 fprintf(stderr, "'%s'", ConversionFunction->getName());
162 if (After.First || After.Second || After.Third) {
163 fprintf(stderr, " -> ");
164 After.DebugPrint();
165 }
166}
167
168/// DebugPrint - Print this implicit conversion sequence to standard
169/// error. Useful for debugging overloading issues.
170void ImplicitConversionSequence::DebugPrint() const {
171 switch (ConversionKind) {
172 case StandardConversion:
173 fprintf(stderr, "Standard conversion: ");
174 Standard.DebugPrint();
175 break;
176 case UserDefinedConversion:
177 fprintf(stderr, "User-defined conversion: ");
178 UserDefined.DebugPrint();
179 break;
180 case EllipsisConversion:
181 fprintf(stderr, "Ellipsis conversion");
182 break;
183 case BadConversion:
184 fprintf(stderr, "Bad conversion");
185 break;
186 }
187
188 fprintf(stderr, "\n");
189}
190
191// IsOverload - Determine whether the given New declaration is an
192// overload of the Old declaration. This routine returns false if New
193// and Old cannot be overloaded, e.g., if they are functions with the
194// same signature (C++ 1.3.10) or if the Old declaration isn't a
195// function (or overload set). When it does return false and Old is an
196// OverloadedFunctionDecl, MatchedDecl will be set to point to the
197// FunctionDecl that New cannot be overloaded with.
198//
199// Example: Given the following input:
200//
201// void f(int, float); // #1
202// void f(int, int); // #2
203// int f(int, int); // #3
204//
205// When we process #1, there is no previous declaration of "f",
206// so IsOverload will not be used.
207//
208// When we process #2, Old is a FunctionDecl for #1. By comparing the
209// parameter types, we see that #1 and #2 are overloaded (since they
210// have different signatures), so this routine returns false;
211// MatchedDecl is unchanged.
212//
213// When we process #3, Old is an OverloadedFunctionDecl containing #1
214// and #2. We compare the signatures of #3 to #1 (they're overloaded,
215// so we do nothing) and then #3 to #2. Since the signatures of #3 and
216// #2 are identical (return types of functions are not part of the
217// signature), IsOverload returns false and MatchedDecl will be set to
218// point to the FunctionDecl for #2.
219bool
220Sema::IsOverload(FunctionDecl *New, Decl* OldD,
221 OverloadedFunctionDecl::function_iterator& MatchedDecl)
222{
223 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
224 // Is this new function an overload of every function in the
225 // overload set?
226 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
227 FuncEnd = Ovl->function_end();
228 for (; Func != FuncEnd; ++Func) {
229 if (!IsOverload(New, *Func, MatchedDecl)) {
230 MatchedDecl = Func;
231 return false;
232 }
233 }
234
235 // This function overloads every function in the overload set.
236 return true;
237 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
238 // Is the function New an overload of the function Old?
239 QualType OldQType = Context.getCanonicalType(Old->getType());
240 QualType NewQType = Context.getCanonicalType(New->getType());
241
242 // Compare the signatures (C++ 1.3.10) of the two functions to
243 // determine whether they are overloads. If we find any mismatch
244 // in the signature, they are overloads.
245
246 // If either of these functions is a K&R-style function (no
247 // prototype), then we consider them to have matching signatures.
248 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
249 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
250 return false;
251
252 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
253 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
254
255 // The signature of a function includes the types of its
256 // parameters (C++ 1.3.10), which includes the presence or absence
257 // of the ellipsis; see C++ DR 357).
258 if (OldQType != NewQType &&
259 (OldType->getNumArgs() != NewType->getNumArgs() ||
260 OldType->isVariadic() != NewType->isVariadic() ||
261 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
262 NewType->arg_type_begin())))
263 return true;
264
265 // If the function is a class member, its signature includes the
266 // cv-qualifiers (if any) on the function itself.
267 //
268 // As part of this, also check whether one of the member functions
269 // is static, in which case they are not overloads (C++
270 // 13.1p2). While not part of the definition of the signature,
271 // this check is important to determine whether these functions
272 // can be overloaded.
273 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
274 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
275 if (OldMethod && NewMethod &&
276 !OldMethod->isStatic() && !NewMethod->isStatic() &&
277 OldQType.getCVRQualifiers() != NewQType.getCVRQualifiers())
278 return true;
279
280 // The signatures match; this is not an overload.
281 return false;
282 } else {
283 // (C++ 13p1):
284 // Only function declarations can be overloaded; object and type
285 // declarations cannot be overloaded.
286 return false;
287 }
288}
289
290/// TryCopyInitialization - Attempt to copy-initialize a value of the
291/// given type (ToType) from the given expression (Expr), as one would
292/// do when copy-initializing a function parameter. This function
293/// returns an implicit conversion sequence that can be used to
294/// perform the initialization. Given
295///
296/// void f(float f);
297/// void g(int i) { f(i); }
298///
299/// this routine would produce an implicit conversion sequence to
300/// describe the initialization of f from i, which will be a standard
301/// conversion sequence containing an lvalue-to-rvalue conversion (C++
302/// 4.1) followed by a floating-integral conversion (C++ 4.9).
303//
304/// Note that this routine only determines how the conversion can be
305/// performed; it does not actually perform the conversion. As such,
306/// it will not produce any diagnostics if no conversion is available,
307/// but will instead return an implicit conversion sequence of kind
308/// "BadConversion".
309ImplicitConversionSequence
310Sema::TryCopyInitialization(Expr* From, QualType ToType)
311{
312 ImplicitConversionSequence ICS;
313
314 QualType FromType = From->getType();
315
316 // Standard conversions (C++ 4)
317 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
318 ICS.Standard.Deprecated = false;
319 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
320
Douglas Gregor98cd5992008-10-21 23:43:52 +0000321 if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType()) {
322 // FIXME: This is a hack to deal with the initialization of
323 // references the way that the C-centric code elsewhere deals with
324 // references, by only allowing them if the referred-to type is
325 // exactly the same. This means that we're only handling the
326 // direct-binding case. The code will be replaced by an
327 // implementation of C++ 13.3.3.1.4 once we have the
328 // initialization of references implemented.
329 QualType ToPointee = Context.getCanonicalType(ToTypeRef->getPointeeType());
330
331 // Get down to the canonical type that we're converting from.
332 if (const ReferenceType *FromTypeRef = FromType->getAsReferenceType())
333 FromType = FromTypeRef->getPointeeType();
334 FromType = Context.getCanonicalType(FromType);
335
336 ICS.Standard.First = ICK_Identity;
337 ICS.Standard.Second = ICK_Identity;
338 ICS.Standard.Third = ICK_Identity;
339 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
340
341 if (FromType != ToPointee)
342 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
343
344 return ICS;
345 }
346
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000347 // The first conversion can be an lvalue-to-rvalue conversion,
348 // array-to-pointer conversion, or function-to-pointer conversion
349 // (C++ 4p1).
350
351 // Lvalue-to-rvalue conversion (C++ 4.1):
352 // An lvalue (3.10) of a non-function, non-array type T can be
353 // converted to an rvalue.
354 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
355 if (argIsLvalue == Expr::LV_Valid &&
356 !FromType->isFunctionType() && !FromType->isArrayType()) {
357 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
358
359 // If T is a non-class type, the type of the rvalue is the
360 // cv-unqualified version of T. Otherwise, the type of the rvalue
361 // is T (C++ 4.1p1).
362 if (!FromType->isRecordType())
363 FromType = FromType.getUnqualifiedType();
364 }
365 // Array-to-pointer conversion (C++ 4.2)
366 else if (FromType->isArrayType()) {
367 ICS.Standard.First = ICK_Array_To_Pointer;
368
369 // An lvalue or rvalue of type "array of N T" or "array of unknown
370 // bound of T" can be converted to an rvalue of type "pointer to
371 // T" (C++ 4.2p1).
372 FromType = Context.getArrayDecayedType(FromType);
373
374 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
375 // This conversion is deprecated. (C++ D.4).
376 ICS.Standard.Deprecated = true;
377
378 // For the purpose of ranking in overload resolution
379 // (13.3.3.1.1), this conversion is considered an
380 // array-to-pointer conversion followed by a qualification
381 // conversion (4.4). (C++ 4.2p2)
382 ICS.Standard.Second = ICK_Identity;
383 ICS.Standard.Third = ICK_Qualification;
384 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
385 return ICS;
386 }
387 }
388 // Function-to-pointer conversion (C++ 4.3).
389 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
390 ICS.Standard.First = ICK_Function_To_Pointer;
391
392 // An lvalue of function type T can be converted to an rvalue of
393 // type "pointer to T." The result is a pointer to the
394 // function. (C++ 4.3p1).
395 FromType = Context.getPointerType(FromType);
396
397 // FIXME: Deal with overloaded functions here (C++ 4.3p2).
398 }
399 // We don't require any conversions for the first step.
400 else {
401 ICS.Standard.First = ICK_Identity;
402 }
403
404 // The second conversion can be an integral promotion, floating
405 // point promotion, integral conversion, floating point conversion,
406 // floating-integral conversion, pointer conversion,
407 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
408 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
409 Context.getCanonicalType(ToType).getUnqualifiedType()) {
410 // The unqualified versions of the types are the same: there's no
411 // conversion to do.
412 ICS.Standard.Second = ICK_Identity;
413 }
414 // Integral promotion (C++ 4.5).
415 else if (IsIntegralPromotion(From, FromType, ToType)) {
416 ICS.Standard.Second = ICK_Integral_Promotion;
417 FromType = ToType.getUnqualifiedType();
418 }
419 // Floating point promotion (C++ 4.6).
420 else if (IsFloatingPointPromotion(FromType, ToType)) {
421 ICS.Standard.Second = ICK_Floating_Promotion;
422 FromType = ToType.getUnqualifiedType();
423 }
424 // Integral conversions (C++ 4.7).
425 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
426 (ToType->isIntegralType() || ToType->isEnumeralType())) {
427 ICS.Standard.Second = ICK_Integral_Conversion;
428 FromType = ToType.getUnqualifiedType();
429 }
430 // Floating point conversions (C++ 4.8).
431 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
432 ICS.Standard.Second = ICK_Floating_Conversion;
433 FromType = ToType.getUnqualifiedType();
434 }
435 // Floating-integral conversions (C++ 4.9).
436 else if ((FromType->isFloatingType() &&
437 ToType->isIntegralType() && !ToType->isBooleanType()) ||
438 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
439 ToType->isFloatingType())) {
440 ICS.Standard.Second = ICK_Floating_Integral;
441 FromType = ToType.getUnqualifiedType();
442 }
443 // Pointer conversions (C++ 4.10).
444 else if (IsPointerConversion(From, FromType, ToType, FromType))
445 ICS.Standard.Second = ICK_Pointer_Conversion;
446 // FIXME: Pointer to member conversions (4.11).
447 // Boolean conversions (C++ 4.12).
448 // FIXME: pointer-to-member type
449 else if (ToType->isBooleanType() &&
450 (FromType->isArithmeticType() ||
451 FromType->isEnumeralType() ||
452 FromType->isPointerType())) {
453 ICS.Standard.Second = ICK_Boolean_Conversion;
454 FromType = Context.BoolTy;
455 } else {
456 // No second conversion required.
457 ICS.Standard.Second = ICK_Identity;
458 }
459
460 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000461 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000462 ICS.Standard.Third = ICK_Qualification;
463 FromType = ToType;
464 } else {
465 // No conversion required
466 ICS.Standard.Third = ICK_Identity;
467 }
468
469 // If we have not converted the argument type to the parameter type,
470 // this is a bad conversion sequence.
471 if (Context.getCanonicalType(FromType) != Context.getCanonicalType(ToType))
472 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
473
474 ICS.Standard.ToTypePtr = FromType.getAsOpaquePtr();
475 return ICS;
476}
477
478/// IsIntegralPromotion - Determines whether the conversion from the
479/// expression From (whose potentially-adjusted type is FromType) to
480/// ToType is an integral promotion (C++ 4.5). If so, returns true and
481/// sets PromotedType to the promoted type.
482bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
483{
484 const BuiltinType *To = ToType->getAsBuiltinType();
485
486 // An rvalue of type char, signed char, unsigned char, short int, or
487 // unsigned short int can be converted to an rvalue of type int if
488 // int can represent all the values of the source type; otherwise,
489 // the source rvalue can be converted to an rvalue of type unsigned
490 // int (C++ 4.5p1).
491 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && To) {
492 if (// We can promote any signed, promotable integer type to an int
493 (FromType->isSignedIntegerType() ||
494 // We can promote any unsigned integer type whose size is
495 // less than int to an int.
496 (!FromType->isSignedIntegerType() &&
497 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))))
498 return To->getKind() == BuiltinType::Int;
499
500 return To->getKind() == BuiltinType::UInt;
501 }
502
503 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
504 // can be converted to an rvalue of the first of the following types
505 // that can represent all the values of its underlying type: int,
506 // unsigned int, long, or unsigned long (C++ 4.5p2).
507 if ((FromType->isEnumeralType() || FromType->isWideCharType())
508 && ToType->isIntegerType()) {
509 // Determine whether the type we're converting from is signed or
510 // unsigned.
511 bool FromIsSigned;
512 uint64_t FromSize = Context.getTypeSize(FromType);
513 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
514 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
515 FromIsSigned = UnderlyingType->isSignedIntegerType();
516 } else {
517 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
518 FromIsSigned = true;
519 }
520
521 // The types we'll try to promote to, in the appropriate
522 // order. Try each of these types.
523 QualType PromoteTypes[4] = {
524 Context.IntTy, Context.UnsignedIntTy,
525 Context.LongTy, Context.UnsignedLongTy
526 };
527 for (int Idx = 0; Idx < 0; ++Idx) {
528 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
529 if (FromSize < ToSize ||
530 (FromSize == ToSize &&
531 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
532 // We found the type that we can promote to. If this is the
533 // type we wanted, we have a promotion. Otherwise, no
534 // promotion.
535 return Context.getCanonicalType(FromType).getUnqualifiedType()
536 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
537 }
538 }
539 }
540
541 // An rvalue for an integral bit-field (9.6) can be converted to an
542 // rvalue of type int if int can represent all the values of the
543 // bit-field; otherwise, it can be converted to unsigned int if
544 // unsigned int can represent all the values of the bit-field. If
545 // the bit-field is larger yet, no integral promotion applies to
546 // it. If the bit-field has an enumerated type, it is treated as any
547 // other value of that type for promotion purposes (C++ 4.5p3).
548 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
549 using llvm::APSInt;
550 FieldDecl *MemberDecl = MemRef->getMemberDecl();
551 APSInt BitWidth;
552 if (MemberDecl->isBitField() &&
553 FromType->isIntegralType() && !FromType->isEnumeralType() &&
554 From->isIntegerConstantExpr(BitWidth, Context)) {
555 APSInt ToSize(Context.getTypeSize(ToType));
556
557 // Are we promoting to an int from a bitfield that fits in an int?
558 if (BitWidth < ToSize ||
559 (FromType->isSignedIntegerType() && BitWidth <= ToSize))
560 return To->getKind() == BuiltinType::Int;
561
562 // Are we promoting to an unsigned int from an unsigned bitfield
563 // that fits into an unsigned int?
564 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize)
565 return To->getKind() == BuiltinType::UInt;
566
567 return false;
568 }
569 }
570
571 // An rvalue of type bool can be converted to an rvalue of type int,
572 // with false becoming zero and true becoming one (C++ 4.5p4).
573 if (FromType->isBooleanType() && To && To->getKind() == BuiltinType::Int)
574 return true;
575
576 return false;
577}
578
579/// IsFloatingPointPromotion - Determines whether the conversion from
580/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
581/// returns true and sets PromotedType to the promoted type.
582bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
583{
584 /// An rvalue of type float can be converted to an rvalue of type
585 /// double. (C++ 4.6p1).
586 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
587 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
588 if (FromBuiltin->getKind() == BuiltinType::Float &&
589 ToBuiltin->getKind() == BuiltinType::Double)
590 return true;
591
592 return false;
593}
594
595/// IsPointerConversion - Determines whether the conversion of the
596/// expression From, which has the (possibly adjusted) type FromType,
597/// can be converted to the type ToType via a pointer conversion (C++
598/// 4.10). If so, returns true and places the converted type (that
599/// might differ from ToType in its cv-qualifiers at some level) into
600/// ConvertedType.
601bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
602 QualType& ConvertedType)
603{
604 const PointerType* ToTypePtr = ToType->getAsPointerType();
605 if (!ToTypePtr)
606 return false;
607
608 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
609 if (From->isNullPointerConstant(Context)) {
610 ConvertedType = ToType;
611 return true;
612 }
613
614 // An rvalue of type "pointer to cv T," where T is an object type,
615 // can be converted to an rvalue of type "pointer to cv void" (C++
616 // 4.10p2).
617 if (FromType->isPointerType() &&
618 FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
619 ToTypePtr->getPointeeType()->isVoidType()) {
620 // We need to produce a pointer to cv void, where cv is the same
621 // set of cv-qualifiers as we had on the incoming pointee type.
622 QualType toPointee = ToTypePtr->getPointeeType();
623 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
624 ->getPointeeType().getCVRQualifiers();
625
626 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
627 == Quals) {
628 // ToType is exactly the type we want. Use it.
629 ConvertedType = ToType;
630 } else {
631 // Build a new type with the right qualifiers.
632 ConvertedType
633 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
634 }
635 return true;
636 }
637
638 // FIXME: An rvalue of type "pointer to cv D," where D is a class
639 // type, can be converted to an rvalue of type "pointer to cv B,"
640 // where B is a base class (clause 10) of D (C++ 4.10p3).
641 return false;
642}
643
Douglas Gregor98cd5992008-10-21 23:43:52 +0000644/// IsQualificationConversion - Determines whether the conversion from
645/// an rvalue of type FromType to ToType is a qualification conversion
646/// (C++ 4.4).
647bool
648Sema::IsQualificationConversion(QualType FromType, QualType ToType)
649{
650 FromType = Context.getCanonicalType(FromType);
651 ToType = Context.getCanonicalType(ToType);
652
653 // If FromType and ToType are the same type, this is not a
654 // qualification conversion.
655 if (FromType == ToType)
656 return false;
657
658 // (C++ 4.4p4):
659 // A conversion can add cv-qualifiers at levels other than the first
660 // in multi-level pointers, subject to the following rules: [...]
661 bool PreviousToQualsIncludeConst = true;
662 bool UnwrappedPointer;
663 bool UnwrappedAnyPointer = false;
664 do {
665 // Within each iteration of the loop, we check the qualifiers to
666 // determine if this still looks like a qualification
667 // conversion. Then, if all is well, we unwrap one more level of
668 // pointers (FIXME: or pointers-to-members) and do it all again
669 // until there are no more pointers or pointers-to-members left to
670 // unwrap.
671 UnwrappedPointer = false;
672
673 // -- the pointer types are similar.
674 const PointerType *FromPtrType = FromType->getAsPointerType(),
675 *ToPtrType = ToType->getAsPointerType();
676 if (FromPtrType && ToPtrType) {
677 // The pointer types appear similar. Look at their pointee types.
678 FromType = FromPtrType->getPointeeType();
679 ToType = ToPtrType->getPointeeType();
680 UnwrappedPointer = true;
681 UnwrappedAnyPointer = true;
682 }
683
684 // FIXME: Cope with pointer-to-member types.
685
686 // -- for every j > 0, if const is in cv 1,j then const is in cv
687 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +0000688 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +0000689 return false;
690
691 // -- if the cv 1,j and cv 2,j are different, then const is in
692 // every cv for 0 < k < j.
693 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
694 && !PreviousToQualsIncludeConst)
695 return false;
696
697 // Keep track of whether all prior cv-qualifiers in the "to" type
698 // include const.
699 PreviousToQualsIncludeConst
700 = PreviousToQualsIncludeConst && ToType.isConstQualified();
701 } while (UnwrappedPointer);
702
703 // We are left with FromType and ToType being the pointee types
704 // after unwrapping the original FromType and ToType the same number
705 // of types. If we unwrapped any pointers, and if FromType and
706 // ToType have the same unqualified type (since we checked
707 // qualifiers above), then this is a qualification conversion.
708 return UnwrappedAnyPointer &&
709 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
710}
711
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000712/// CompareImplicitConversionSequences - Compare two implicit
713/// conversion sequences to determine whether one is better than the
714/// other or if they are indistinguishable (C++ 13.3.3.2).
715ImplicitConversionSequence::CompareKind
716Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
717 const ImplicitConversionSequence& ICS2)
718{
719 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
720 // conversion sequences (as defined in 13.3.3.1)
721 // -- a standard conversion sequence (13.3.3.1.1) is a better
722 // conversion sequence than a user-defined conversion sequence or
723 // an ellipsis conversion sequence, and
724 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
725 // conversion sequence than an ellipsis conversion sequence
726 // (13.3.3.1.3).
727 //
728 if (ICS1.ConversionKind < ICS2.ConversionKind)
729 return ImplicitConversionSequence::Better;
730 else if (ICS2.ConversionKind < ICS1.ConversionKind)
731 return ImplicitConversionSequence::Worse;
732
733 // Two implicit conversion sequences of the same form are
734 // indistinguishable conversion sequences unless one of the
735 // following rules apply: (C++ 13.3.3.2p3):
736 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
737 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
738 else if (ICS1.ConversionKind ==
739 ImplicitConversionSequence::UserDefinedConversion) {
740 // User-defined conversion sequence U1 is a better conversion
741 // sequence than another user-defined conversion sequence U2 if
742 // they contain the same user-defined conversion function or
743 // constructor and if the second standard conversion sequence of
744 // U1 is better than the second standard conversion sequence of
745 // U2 (C++ 13.3.3.2p3).
746 if (ICS1.UserDefined.ConversionFunction ==
747 ICS2.UserDefined.ConversionFunction)
748 return CompareStandardConversionSequences(ICS1.UserDefined.After,
749 ICS2.UserDefined.After);
750 }
751
752 return ImplicitConversionSequence::Indistinguishable;
753}
754
755/// CompareStandardConversionSequences - Compare two standard
756/// conversion sequences to determine whether one is better than the
757/// other or if they are indistinguishable (C++ 13.3.3.2p3).
758ImplicitConversionSequence::CompareKind
759Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
760 const StandardConversionSequence& SCS2)
761{
762 // Standard conversion sequence S1 is a better conversion sequence
763 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
764
765 // -- S1 is a proper subsequence of S2 (comparing the conversion
766 // sequences in the canonical form defined by 13.3.3.1.1,
767 // excluding any Lvalue Transformation; the identity conversion
768 // sequence is considered to be a subsequence of any
769 // non-identity conversion sequence) or, if not that,
770 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
771 // Neither is a proper subsequence of the other. Do nothing.
772 ;
773 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
774 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
775 (SCS1.Second == ICK_Identity &&
776 SCS1.Third == ICK_Identity))
777 // SCS1 is a proper subsequence of SCS2.
778 return ImplicitConversionSequence::Better;
779 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
780 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
781 (SCS2.Second == ICK_Identity &&
782 SCS2.Third == ICK_Identity))
783 // SCS2 is a proper subsequence of SCS1.
784 return ImplicitConversionSequence::Worse;
785
786 // -- the rank of S1 is better than the rank of S2 (by the rules
787 // defined below), or, if not that,
788 ImplicitConversionRank Rank1 = SCS1.getRank();
789 ImplicitConversionRank Rank2 = SCS2.getRank();
790 if (Rank1 < Rank2)
791 return ImplicitConversionSequence::Better;
792 else if (Rank2 < Rank1)
793 return ImplicitConversionSequence::Worse;
794 else {
795 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
796 // are indistinguishable unless one of the following rules
797 // applies:
798
799 // A conversion that is not a conversion of a pointer, or
800 // pointer to member, to bool is better than another conversion
801 // that is such a conversion.
802 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
803 return SCS2.isPointerConversionToBool()
804 ? ImplicitConversionSequence::Better
805 : ImplicitConversionSequence::Worse;
806
807 // FIXME: The other bullets in (C++ 13.3.3.2p4) require support
808 // for derived classes.
809 }
810
811 // FIXME: Handle comparison by qualifications.
812 // FIXME: Handle comparison of reference bindings.
813 return ImplicitConversionSequence::Indistinguishable;
814}
815
816/// AddOverloadCandidate - Adds the given function to the set of
817/// candidate functions, using the given function call arguments.
818void
819Sema::AddOverloadCandidate(FunctionDecl *Function,
820 Expr **Args, unsigned NumArgs,
821 OverloadCandidateSet& CandidateSet)
822{
823 const FunctionTypeProto* Proto
824 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
825 assert(Proto && "Functions without a prototype cannot be overloaded");
826
827 // Add this candidate
828 CandidateSet.push_back(OverloadCandidate());
829 OverloadCandidate& Candidate = CandidateSet.back();
830 Candidate.Function = Function;
831
832 unsigned NumArgsInProto = Proto->getNumArgs();
833
834 // (C++ 13.3.2p2): A candidate function having fewer than m
835 // parameters is viable only if it has an ellipsis in its parameter
836 // list (8.3.5).
837 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
838 Candidate.Viable = false;
839 return;
840 }
841
842 // (C++ 13.3.2p2): A candidate function having more than m parameters
843 // is viable only if the (m+1)st parameter has a default argument
844 // (8.3.6). For the purposes of overload resolution, the
845 // parameter list is truncated on the right, so that there are
846 // exactly m parameters.
847 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
848 if (NumArgs < MinRequiredArgs) {
849 // Not enough arguments.
850 Candidate.Viable = false;
851 return;
852 }
853
854 // Determine the implicit conversion sequences for each of the
855 // arguments.
856 Candidate.Viable = true;
857 Candidate.Conversions.resize(NumArgs);
858 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
859 if (ArgIdx < NumArgsInProto) {
860 // (C++ 13.3.2p3): for F to be a viable function, there shall
861 // exist for each argument an implicit conversion sequence
862 // (13.3.3.1) that converts that argument to the corresponding
863 // parameter of F.
864 QualType ParamType = Proto->getArgType(ArgIdx);
865 Candidate.Conversions[ArgIdx]
866 = TryCopyInitialization(Args[ArgIdx], ParamType);
867 if (Candidate.Conversions[ArgIdx].ConversionKind
868 == ImplicitConversionSequence::BadConversion)
869 Candidate.Viable = false;
870 } else {
871 // (C++ 13.3.2p2): For the purposes of overload resolution, any
872 // argument for which there is no corresponding parameter is
873 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
874 Candidate.Conversions[ArgIdx].ConversionKind
875 = ImplicitConversionSequence::EllipsisConversion;
876 }
877 }
878}
879
880/// AddOverloadCandidates - Add all of the function overloads in Ovl
881/// to the candidate set.
882void
883Sema::AddOverloadCandidates(OverloadedFunctionDecl *Ovl,
884 Expr **Args, unsigned NumArgs,
885 OverloadCandidateSet& CandidateSet)
886{
887 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin();
888 Func != Ovl->function_end(); ++Func)
889 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
890}
891
892/// isBetterOverloadCandidate - Determines whether the first overload
893/// candidate is a better candidate than the second (C++ 13.3.3p1).
894bool
895Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
896 const OverloadCandidate& Cand2)
897{
898 // Define viable functions to be better candidates than non-viable
899 // functions.
900 if (!Cand2.Viable)
901 return Cand1.Viable;
902 else if (!Cand1.Viable)
903 return false;
904
905 // FIXME: Deal with the implicit object parameter for static member
906 // functions. (C++ 13.3.3p1).
907
908 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
909 // function than another viable function F2 if for all arguments i,
910 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
911 // then...
912 unsigned NumArgs = Cand1.Conversions.size();
913 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
914 bool HasBetterConversion = false;
915 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
916 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
917 Cand2.Conversions[ArgIdx])) {
918 case ImplicitConversionSequence::Better:
919 // Cand1 has a better conversion sequence.
920 HasBetterConversion = true;
921 break;
922
923 case ImplicitConversionSequence::Worse:
924 // Cand1 can't be better than Cand2.
925 return false;
926
927 case ImplicitConversionSequence::Indistinguishable:
928 // Do nothing.
929 break;
930 }
931 }
932
933 if (HasBetterConversion)
934 return true;
935
936 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be implemented.
937
938 return false;
939}
940
941/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
942/// within an overload candidate set. If overloading is successful,
943/// the result will be OR_Success and Best will be set to point to the
944/// best viable function within the candidate set. Otherwise, one of
945/// several kinds of errors will be returned; see
946/// Sema::OverloadingResult.
947Sema::OverloadingResult
948Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
949 OverloadCandidateSet::iterator& Best)
950{
951 // Find the best viable function.
952 Best = CandidateSet.end();
953 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
954 Cand != CandidateSet.end(); ++Cand) {
955 if (Cand->Viable) {
956 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
957 Best = Cand;
958 }
959 }
960
961 // If we didn't find any viable functions, abort.
962 if (Best == CandidateSet.end())
963 return OR_No_Viable_Function;
964
965 // Make sure that this function is better than every other viable
966 // function. If not, we have an ambiguity.
967 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
968 Cand != CandidateSet.end(); ++Cand) {
969 if (Cand->Viable &&
970 Cand != Best &&
971 !isBetterOverloadCandidate(*Best, *Cand))
972 return OR_Ambiguous;
973 }
974
975 // Best is the best viable function.
976 return OR_Success;
977}
978
979/// PrintOverloadCandidates - When overload resolution fails, prints
980/// diagnostic messages containing the candidates in the candidate
981/// set. If OnlyViable is true, only viable candidates will be printed.
982void
983Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
984 bool OnlyViable)
985{
986 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
987 LastCand = CandidateSet.end();
988 for (; Cand != LastCand; ++Cand) {
989 if (Cand->Viable ||!OnlyViable)
990 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
991 }
992}
993
994} // end namespace clang