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