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