blob: cafdf8794a2fd4c2c14012cf6a1d0cd12642ada5 [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;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000662 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +0000663 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +0000664 // Within each iteration of the loop, we check the qualifiers to
665 // determine if this still looks like a qualification
666 // conversion. Then, if all is well, we unwrap one more level of
667 // pointers (FIXME: or pointers-to-members) and do it all again
668 // until there are no more pointers or pointers-to-members left to
669 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +0000670 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000671
672 // -- for every j > 0, if const is in cv 1,j then const is in cv
673 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +0000674 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +0000675 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000676
Douglas Gregor98cd5992008-10-21 23:43:52 +0000677 // -- if the cv 1,j and cv 2,j are different, then const is in
678 // every cv for 0 < k < j.
679 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +0000680 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +0000681 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000682
Douglas Gregor98cd5992008-10-21 23:43:52 +0000683 // Keep track of whether all prior cv-qualifiers in the "to" type
684 // include const.
685 PreviousToQualsIncludeConst
686 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +0000687 }
Douglas Gregor98cd5992008-10-21 23:43:52 +0000688
689 // We are left with FromType and ToType being the pointee types
690 // after unwrapping the original FromType and ToType the same number
691 // of types. If we unwrapped any pointers, and if FromType and
692 // ToType have the same unqualified type (since we checked
693 // qualifiers above), then this is a qualification conversion.
694 return UnwrappedAnyPointer &&
695 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
696}
697
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000698/// CompareImplicitConversionSequences - Compare two implicit
699/// conversion sequences to determine whether one is better than the
700/// other or if they are indistinguishable (C++ 13.3.3.2).
701ImplicitConversionSequence::CompareKind
702Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
703 const ImplicitConversionSequence& ICS2)
704{
705 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
706 // conversion sequences (as defined in 13.3.3.1)
707 // -- a standard conversion sequence (13.3.3.1.1) is a better
708 // conversion sequence than a user-defined conversion sequence or
709 // an ellipsis conversion sequence, and
710 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
711 // conversion sequence than an ellipsis conversion sequence
712 // (13.3.3.1.3).
713 //
714 if (ICS1.ConversionKind < ICS2.ConversionKind)
715 return ImplicitConversionSequence::Better;
716 else if (ICS2.ConversionKind < ICS1.ConversionKind)
717 return ImplicitConversionSequence::Worse;
718
719 // Two implicit conversion sequences of the same form are
720 // indistinguishable conversion sequences unless one of the
721 // following rules apply: (C++ 13.3.3.2p3):
722 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
723 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
724 else if (ICS1.ConversionKind ==
725 ImplicitConversionSequence::UserDefinedConversion) {
726 // User-defined conversion sequence U1 is a better conversion
727 // sequence than another user-defined conversion sequence U2 if
728 // they contain the same user-defined conversion function or
729 // constructor and if the second standard conversion sequence of
730 // U1 is better than the second standard conversion sequence of
731 // U2 (C++ 13.3.3.2p3).
732 if (ICS1.UserDefined.ConversionFunction ==
733 ICS2.UserDefined.ConversionFunction)
734 return CompareStandardConversionSequences(ICS1.UserDefined.After,
735 ICS2.UserDefined.After);
736 }
737
738 return ImplicitConversionSequence::Indistinguishable;
739}
740
741/// CompareStandardConversionSequences - Compare two standard
742/// conversion sequences to determine whether one is better than the
743/// other or if they are indistinguishable (C++ 13.3.3.2p3).
744ImplicitConversionSequence::CompareKind
745Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
746 const StandardConversionSequence& SCS2)
747{
748 // Standard conversion sequence S1 is a better conversion sequence
749 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
750
751 // -- S1 is a proper subsequence of S2 (comparing the conversion
752 // sequences in the canonical form defined by 13.3.3.1.1,
753 // excluding any Lvalue Transformation; the identity conversion
754 // sequence is considered to be a subsequence of any
755 // non-identity conversion sequence) or, if not that,
756 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
757 // Neither is a proper subsequence of the other. Do nothing.
758 ;
759 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
760 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
761 (SCS1.Second == ICK_Identity &&
762 SCS1.Third == ICK_Identity))
763 // SCS1 is a proper subsequence of SCS2.
764 return ImplicitConversionSequence::Better;
765 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
766 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
767 (SCS2.Second == ICK_Identity &&
768 SCS2.Third == ICK_Identity))
769 // SCS2 is a proper subsequence of SCS1.
770 return ImplicitConversionSequence::Worse;
771
772 // -- the rank of S1 is better than the rank of S2 (by the rules
773 // defined below), or, if not that,
774 ImplicitConversionRank Rank1 = SCS1.getRank();
775 ImplicitConversionRank Rank2 = SCS2.getRank();
776 if (Rank1 < Rank2)
777 return ImplicitConversionSequence::Better;
778 else if (Rank2 < Rank1)
779 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000780
Douglas Gregor57373262008-10-22 14:17:15 +0000781 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
782 // are indistinguishable unless one of the following rules
783 // applies:
784
785 // A conversion that is not a conversion of a pointer, or
786 // pointer to member, to bool is better than another conversion
787 // that is such a conversion.
788 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
789 return SCS2.isPointerConversionToBool()
790 ? ImplicitConversionSequence::Better
791 : ImplicitConversionSequence::Worse;
792
793 // FIXME: The other bullets in (C++ 13.3.3.2p4) require support
794 // for derived classes.
795
796 // Compare based on qualification conversions (C++ 13.3.3.2p3,
797 // bullet 3).
798 if (ImplicitConversionSequence::CompareKind CK
799 = CompareQualificationConversions(SCS1, SCS2))
800 return CK;
801
802 // FIXME: Handle comparison of reference bindings.
803
804 return ImplicitConversionSequence::Indistinguishable;
805}
806
807/// CompareQualificationConversions - Compares two standard conversion
808/// sequences to determine whether they can be ranked based on their
809/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
810ImplicitConversionSequence::CompareKind
811Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
812 const StandardConversionSequence& SCS2)
813{
Douglas Gregorba7e2102008-10-22 15:04:37 +0000814 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +0000815 // -- S1 and S2 differ only in their qualification conversion and
816 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
817 // cv-qualification signature of type T1 is a proper subset of
818 // the cv-qualification signature of type T2, and S1 is not the
819 // deprecated string literal array-to-pointer conversion (4.2).
820 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
821 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
822 return ImplicitConversionSequence::Indistinguishable;
823
824 // FIXME: the example in the standard doesn't use a qualification
825 // conversion (!)
826 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
827 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
828 T1 = Context.getCanonicalType(T1);
829 T2 = Context.getCanonicalType(T2);
830
831 // If the types are the same, we won't learn anything by unwrapped
832 // them.
833 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
834 return ImplicitConversionSequence::Indistinguishable;
835
836 ImplicitConversionSequence::CompareKind Result
837 = ImplicitConversionSequence::Indistinguishable;
838 while (UnwrapSimilarPointerTypes(T1, T2)) {
839 // Within each iteration of the loop, we check the qualifiers to
840 // determine if this still looks like a qualification
841 // conversion. Then, if all is well, we unwrap one more level of
842 // pointers (FIXME: or pointers-to-members) and do it all again
843 // until there are no more pointers or pointers-to-members left
844 // to unwrap. This essentially mimics what
845 // IsQualificationConversion does, but here we're checking for a
846 // strict subset of qualifiers.
847 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
848 // The qualifiers are the same, so this doesn't tell us anything
849 // about how the sequences rank.
850 ;
851 else if (T2.isMoreQualifiedThan(T1)) {
852 // T1 has fewer qualifiers, so it could be the better sequence.
853 if (Result == ImplicitConversionSequence::Worse)
854 // Neither has qualifiers that are a subset of the other's
855 // qualifiers.
856 return ImplicitConversionSequence::Indistinguishable;
857
858 Result = ImplicitConversionSequence::Better;
859 } else if (T1.isMoreQualifiedThan(T2)) {
860 // T2 has fewer qualifiers, so it could be the better sequence.
861 if (Result == ImplicitConversionSequence::Better)
862 // Neither has qualifiers that are a subset of the other's
863 // qualifiers.
864 return ImplicitConversionSequence::Indistinguishable;
865
866 Result = ImplicitConversionSequence::Worse;
867 } else {
868 // Qualifiers are disjoint.
869 return ImplicitConversionSequence::Indistinguishable;
870 }
871
872 // If the types after this point are equivalent, we're done.
873 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
874 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000875 }
876
Douglas Gregor57373262008-10-22 14:17:15 +0000877 // Check that the winning standard conversion sequence isn't using
878 // the deprecated string literal array to pointer conversion.
879 switch (Result) {
880 case ImplicitConversionSequence::Better:
881 if (SCS1.Deprecated)
882 Result = ImplicitConversionSequence::Indistinguishable;
883 break;
884
885 case ImplicitConversionSequence::Indistinguishable:
886 break;
887
888 case ImplicitConversionSequence::Worse:
889 if (SCS2.Deprecated)
890 Result = ImplicitConversionSequence::Indistinguishable;
891 break;
892 }
893
894 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000895}
896
897/// AddOverloadCandidate - Adds the given function to the set of
898/// candidate functions, using the given function call arguments.
899void
900Sema::AddOverloadCandidate(FunctionDecl *Function,
901 Expr **Args, unsigned NumArgs,
902 OverloadCandidateSet& CandidateSet)
903{
904 const FunctionTypeProto* Proto
905 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
906 assert(Proto && "Functions without a prototype cannot be overloaded");
907
908 // Add this candidate
909 CandidateSet.push_back(OverloadCandidate());
910 OverloadCandidate& Candidate = CandidateSet.back();
911 Candidate.Function = Function;
912
913 unsigned NumArgsInProto = Proto->getNumArgs();
914
915 // (C++ 13.3.2p2): A candidate function having fewer than m
916 // parameters is viable only if it has an ellipsis in its parameter
917 // list (8.3.5).
918 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
919 Candidate.Viable = false;
920 return;
921 }
922
923 // (C++ 13.3.2p2): A candidate function having more than m parameters
924 // is viable only if the (m+1)st parameter has a default argument
925 // (8.3.6). For the purposes of overload resolution, the
926 // parameter list is truncated on the right, so that there are
927 // exactly m parameters.
928 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
929 if (NumArgs < MinRequiredArgs) {
930 // Not enough arguments.
931 Candidate.Viable = false;
932 return;
933 }
934
935 // Determine the implicit conversion sequences for each of the
936 // arguments.
937 Candidate.Viable = true;
938 Candidate.Conversions.resize(NumArgs);
939 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
940 if (ArgIdx < NumArgsInProto) {
941 // (C++ 13.3.2p3): for F to be a viable function, there shall
942 // exist for each argument an implicit conversion sequence
943 // (13.3.3.1) that converts that argument to the corresponding
944 // parameter of F.
945 QualType ParamType = Proto->getArgType(ArgIdx);
946 Candidate.Conversions[ArgIdx]
947 = TryCopyInitialization(Args[ArgIdx], ParamType);
948 if (Candidate.Conversions[ArgIdx].ConversionKind
949 == ImplicitConversionSequence::BadConversion)
950 Candidate.Viable = false;
951 } else {
952 // (C++ 13.3.2p2): For the purposes of overload resolution, any
953 // argument for which there is no corresponding parameter is
954 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
955 Candidate.Conversions[ArgIdx].ConversionKind
956 = ImplicitConversionSequence::EllipsisConversion;
957 }
958 }
959}
960
961/// AddOverloadCandidates - Add all of the function overloads in Ovl
962/// to the candidate set.
963void
964Sema::AddOverloadCandidates(OverloadedFunctionDecl *Ovl,
965 Expr **Args, unsigned NumArgs,
966 OverloadCandidateSet& CandidateSet)
967{
968 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin();
969 Func != Ovl->function_end(); ++Func)
970 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
971}
972
973/// isBetterOverloadCandidate - Determines whether the first overload
974/// candidate is a better candidate than the second (C++ 13.3.3p1).
975bool
976Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
977 const OverloadCandidate& Cand2)
978{
979 // Define viable functions to be better candidates than non-viable
980 // functions.
981 if (!Cand2.Viable)
982 return Cand1.Viable;
983 else if (!Cand1.Viable)
984 return false;
985
986 // FIXME: Deal with the implicit object parameter for static member
987 // functions. (C++ 13.3.3p1).
988
989 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
990 // function than another viable function F2 if for all arguments i,
991 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
992 // then...
993 unsigned NumArgs = Cand1.Conversions.size();
994 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
995 bool HasBetterConversion = false;
996 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
997 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
998 Cand2.Conversions[ArgIdx])) {
999 case ImplicitConversionSequence::Better:
1000 // Cand1 has a better conversion sequence.
1001 HasBetterConversion = true;
1002 break;
1003
1004 case ImplicitConversionSequence::Worse:
1005 // Cand1 can't be better than Cand2.
1006 return false;
1007
1008 case ImplicitConversionSequence::Indistinguishable:
1009 // Do nothing.
1010 break;
1011 }
1012 }
1013
1014 if (HasBetterConversion)
1015 return true;
1016
1017 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be implemented.
1018
1019 return false;
1020}
1021
1022/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
1023/// within an overload candidate set. If overloading is successful,
1024/// the result will be OR_Success and Best will be set to point to the
1025/// best viable function within the candidate set. Otherwise, one of
1026/// several kinds of errors will be returned; see
1027/// Sema::OverloadingResult.
1028Sema::OverloadingResult
1029Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
1030 OverloadCandidateSet::iterator& Best)
1031{
1032 // Find the best viable function.
1033 Best = CandidateSet.end();
1034 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1035 Cand != CandidateSet.end(); ++Cand) {
1036 if (Cand->Viable) {
1037 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
1038 Best = Cand;
1039 }
1040 }
1041
1042 // If we didn't find any viable functions, abort.
1043 if (Best == CandidateSet.end())
1044 return OR_No_Viable_Function;
1045
1046 // Make sure that this function is better than every other viable
1047 // function. If not, we have an ambiguity.
1048 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1049 Cand != CandidateSet.end(); ++Cand) {
1050 if (Cand->Viable &&
1051 Cand != Best &&
1052 !isBetterOverloadCandidate(*Best, *Cand))
1053 return OR_Ambiguous;
1054 }
1055
1056 // Best is the best viable function.
1057 return OR_Success;
1058}
1059
1060/// PrintOverloadCandidates - When overload resolution fails, prints
1061/// diagnostic messages containing the candidates in the candidate
1062/// set. If OnlyViable is true, only viable candidates will be printed.
1063void
1064Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
1065 bool OnlyViable)
1066{
1067 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1068 LastCand = CandidateSet.end();
1069 for (; Cand != LastCand; ++Cand) {
1070 if (Cand->Viable ||!OnlyViable)
1071 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
1072 }
1073}
1074
1075} // end namespace clang