blob: 176701e57d2a6d4c42966e6000936030006cbda8 [file] [log] [blame]
Douglas Gregord2baafd2008-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 Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-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 Gregor2aecd1f2008-10-29 02:00:59 +000042 ICC_Conversion,
Douglas Gregord2baafd2008-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 Gregor2aecd1f2008-10-29 02:00:59 +000065 ICR_Conversion,
Douglas Gregord2baafd2008-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 Gregor2aecd1f2008-10-29 02:00:59 +000087 "Boolean conversion",
88 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +000089 };
90 return Name[Kind];
91}
92
Douglas Gregorb72e9da2008-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;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000102 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000103}
104
Douglas Gregord2baafd2008-10-21 16:13:35 +0000105/// getRank - Retrieve the rank of this standard conversion sequence
106/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
107/// implicit conversions.
108ImplicitConversionRank StandardConversionSequence::getRank() const {
109 ImplicitConversionRank Rank = ICR_Exact_Match;
110 if (GetConversionRank(First) > Rank)
111 Rank = GetConversionRank(First);
112 if (GetConversionRank(Second) > Rank)
113 Rank = GetConversionRank(Second);
114 if (GetConversionRank(Third) > Rank)
115 Rank = GetConversionRank(Third);
116 return Rank;
117}
118
119/// isPointerConversionToBool - Determines whether this conversion is
120/// a conversion of a pointer or pointer-to-member to bool. This is
121/// used as part of the ranking of standard conversion sequences
122/// (C++ 13.3.3.2p4).
123bool StandardConversionSequence::isPointerConversionToBool() const
124{
125 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
126 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
127
128 // Note that FromType has not necessarily been transformed by the
129 // array-to-pointer or function-to-pointer implicit conversions, so
130 // check for their presence as well as checking whether FromType is
131 // a pointer.
132 if (ToType->isBooleanType() &&
133 (FromType->isPointerType() ||
134 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
135 return true;
136
137 return false;
138}
139
Douglas Gregor14046502008-10-23 00:40:37 +0000140/// isPointerConversionToVoidPointer - Determines whether this
141/// conversion is a conversion of a pointer to a void pointer. This is
142/// used as part of the ranking of standard conversion sequences (C++
143/// 13.3.3.2p4).
144bool
145StandardConversionSequence::
146isPointerConversionToVoidPointer(ASTContext& Context) const
147{
148 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
149 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
150
151 // Note that FromType has not necessarily been transformed by the
152 // array-to-pointer implicit conversion, so check for its presence
153 // and redo the conversion to get a pointer.
154 if (First == ICK_Array_To_Pointer)
155 FromType = Context.getArrayDecayedType(FromType);
156
157 if (Second == ICK_Pointer_Conversion)
158 if (const PointerType* ToPtrType = ToType->getAsPointerType())
159 return ToPtrType->getPointeeType()->isVoidType();
160
161 return false;
162}
163
Douglas Gregord2baafd2008-10-21 16:13:35 +0000164/// DebugPrint - Print this standard conversion sequence to standard
165/// error. Useful for debugging overloading issues.
166void StandardConversionSequence::DebugPrint() const {
167 bool PrintedSomething = false;
168 if (First != ICK_Identity) {
169 fprintf(stderr, "%s", GetImplicitConversionName(First));
170 PrintedSomething = true;
171 }
172
173 if (Second != ICK_Identity) {
174 if (PrintedSomething) {
175 fprintf(stderr, " -> ");
176 }
177 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000178
179 if (CopyConstructor) {
180 fprintf(stderr, " (by copy constructor)");
181 } else if (DirectBinding) {
182 fprintf(stderr, " (direct reference binding)");
183 } else if (ReferenceBinding) {
184 fprintf(stderr, " (reference binding)");
185 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000186 PrintedSomething = true;
187 }
188
189 if (Third != ICK_Identity) {
190 if (PrintedSomething) {
191 fprintf(stderr, " -> ");
192 }
193 fprintf(stderr, "%s", GetImplicitConversionName(Third));
194 PrintedSomething = true;
195 }
196
197 if (!PrintedSomething) {
198 fprintf(stderr, "No conversions required");
199 }
200}
201
202/// DebugPrint - Print this user-defined conversion sequence to standard
203/// error. Useful for debugging overloading issues.
204void UserDefinedConversionSequence::DebugPrint() const {
205 if (Before.First || Before.Second || Before.Third) {
206 Before.DebugPrint();
207 fprintf(stderr, " -> ");
208 }
209 fprintf(stderr, "'%s'", ConversionFunction->getName());
210 if (After.First || After.Second || After.Third) {
211 fprintf(stderr, " -> ");
212 After.DebugPrint();
213 }
214}
215
216/// DebugPrint - Print this implicit conversion sequence to standard
217/// error. Useful for debugging overloading issues.
218void ImplicitConversionSequence::DebugPrint() const {
219 switch (ConversionKind) {
220 case StandardConversion:
221 fprintf(stderr, "Standard conversion: ");
222 Standard.DebugPrint();
223 break;
224 case UserDefinedConversion:
225 fprintf(stderr, "User-defined conversion: ");
226 UserDefined.DebugPrint();
227 break;
228 case EllipsisConversion:
229 fprintf(stderr, "Ellipsis conversion");
230 break;
231 case BadConversion:
232 fprintf(stderr, "Bad conversion");
233 break;
234 }
235
236 fprintf(stderr, "\n");
237}
238
239// IsOverload - Determine whether the given New declaration is an
240// overload of the Old declaration. This routine returns false if New
241// and Old cannot be overloaded, e.g., if they are functions with the
242// same signature (C++ 1.3.10) or if the Old declaration isn't a
243// function (or overload set). When it does return false and Old is an
244// OverloadedFunctionDecl, MatchedDecl will be set to point to the
245// FunctionDecl that New cannot be overloaded with.
246//
247// Example: Given the following input:
248//
249// void f(int, float); // #1
250// void f(int, int); // #2
251// int f(int, int); // #3
252//
253// When we process #1, there is no previous declaration of "f",
254// so IsOverload will not be used.
255//
256// When we process #2, Old is a FunctionDecl for #1. By comparing the
257// parameter types, we see that #1 and #2 are overloaded (since they
258// have different signatures), so this routine returns false;
259// MatchedDecl is unchanged.
260//
261// When we process #3, Old is an OverloadedFunctionDecl containing #1
262// and #2. We compare the signatures of #3 to #1 (they're overloaded,
263// so we do nothing) and then #3 to #2. Since the signatures of #3 and
264// #2 are identical (return types of functions are not part of the
265// signature), IsOverload returns false and MatchedDecl will be set to
266// point to the FunctionDecl for #2.
267bool
268Sema::IsOverload(FunctionDecl *New, Decl* OldD,
269 OverloadedFunctionDecl::function_iterator& MatchedDecl)
270{
271 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
272 // Is this new function an overload of every function in the
273 // overload set?
274 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
275 FuncEnd = Ovl->function_end();
276 for (; Func != FuncEnd; ++Func) {
277 if (!IsOverload(New, *Func, MatchedDecl)) {
278 MatchedDecl = Func;
279 return false;
280 }
281 }
282
283 // This function overloads every function in the overload set.
284 return true;
285 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
286 // Is the function New an overload of the function Old?
287 QualType OldQType = Context.getCanonicalType(Old->getType());
288 QualType NewQType = Context.getCanonicalType(New->getType());
289
290 // Compare the signatures (C++ 1.3.10) of the two functions to
291 // determine whether they are overloads. If we find any mismatch
292 // in the signature, they are overloads.
293
294 // If either of these functions is a K&R-style function (no
295 // prototype), then we consider them to have matching signatures.
296 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
297 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
298 return false;
299
300 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
301 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
302
303 // The signature of a function includes the types of its
304 // parameters (C++ 1.3.10), which includes the presence or absence
305 // of the ellipsis; see C++ DR 357).
306 if (OldQType != NewQType &&
307 (OldType->getNumArgs() != NewType->getNumArgs() ||
308 OldType->isVariadic() != NewType->isVariadic() ||
309 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
310 NewType->arg_type_begin())))
311 return true;
312
313 // If the function is a class member, its signature includes the
314 // cv-qualifiers (if any) on the function itself.
315 //
316 // As part of this, also check whether one of the member functions
317 // is static, in which case they are not overloads (C++
318 // 13.1p2). While not part of the definition of the signature,
319 // this check is important to determine whether these functions
320 // can be overloaded.
321 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
322 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
323 if (OldMethod && NewMethod &&
324 !OldMethod->isStatic() && !NewMethod->isStatic() &&
325 OldQType.getCVRQualifiers() != NewQType.getCVRQualifiers())
326 return true;
327
328 // The signatures match; this is not an overload.
329 return false;
330 } else {
331 // (C++ 13p1):
332 // Only function declarations can be overloaded; object and type
333 // declarations cannot be overloaded.
334 return false;
335 }
336}
337
Douglas Gregor81c29152008-10-29 00:13:59 +0000338/// TryImplicitConversion - Attempt to perform an implicit conversion
339/// from the given expression (Expr) to the given type (ToType). This
340/// function returns an implicit conversion sequence that can be used
341/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000342///
343/// void f(float f);
344/// void g(int i) { f(i); }
345///
346/// this routine would produce an implicit conversion sequence to
347/// describe the initialization of f from i, which will be a standard
348/// conversion sequence containing an lvalue-to-rvalue conversion (C++
349/// 4.1) followed by a floating-integral conversion (C++ 4.9).
350//
351/// Note that this routine only determines how the conversion can be
352/// performed; it does not actually perform the conversion. As such,
353/// it will not produce any diagnostics if no conversion is available,
354/// but will instead return an implicit conversion sequence of kind
355/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000356///
357/// If @p SuppressUserConversions, then user-defined conversions are
358/// not permitted.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000359ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000360Sema::TryImplicitConversion(Expr* From, QualType ToType,
361 bool SuppressUserConversions)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000362{
363 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000364 if (IsStandardConversion(From, ToType, ICS.Standard))
365 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000366 else if (!SuppressUserConversions &&
367 IsUserDefinedConversion(From, ToType, ICS.UserDefined)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000368 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000369 // C++ [over.ics.user]p4:
370 // A conversion of an expression of class type to the same class
371 // type is given Exact Match rank, and a conversion of an
372 // expression of class type to a base class of that type is
373 // given Conversion rank, in spite of the fact that a copy
374 // constructor (i.e., a user-defined conversion function) is
375 // called for those cases.
376 if (CXXConstructorDecl *Constructor
377 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
378 if (Constructor->isCopyConstructor(Context)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000379 // Turn this into a "standard" conversion sequence, so that it
380 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000381 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
382 ICS.Standard.setAsIdentityConversion();
383 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
384 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000385 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregore640ab62008-11-03 17:51:48 +0000386 if (IsDerivedFrom(From->getType().getUnqualifiedType(),
387 ToType.getUnqualifiedType()))
388 ICS.Standard.Second = ICK_Derived_To_Base;
389 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000390 }
Douglas Gregore640ab62008-11-03 17:51:48 +0000391 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000392 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000393
394 return ICS;
395}
396
397/// IsStandardConversion - Determines whether there is a standard
398/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
399/// expression From to the type ToType. Standard conversion sequences
400/// only consider non-class types; for conversions that involve class
401/// types, use TryImplicitConversion. If a conversion exists, SCS will
402/// contain the standard conversion sequence required to perform this
403/// conversion and this routine will return true. Otherwise, this
404/// routine will return false and the value of SCS is unspecified.
405bool
406Sema::IsStandardConversion(Expr* From, QualType ToType,
407 StandardConversionSequence &SCS)
408{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000409 QualType FromType = From->getType();
410
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000411 // There are no standard conversions for class types, so abort early.
412 if (FromType->isRecordType() || ToType->isRecordType())
413 return false;
414
415 // Standard conversions (C++ [conv])
416 SCS.Deprecated = false;
417 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000418 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000419
420 // The first conversion can be an lvalue-to-rvalue conversion,
421 // array-to-pointer conversion, or function-to-pointer conversion
422 // (C++ 4p1).
423
424 // Lvalue-to-rvalue conversion (C++ 4.1):
425 // An lvalue (3.10) of a non-function, non-array type T can be
426 // converted to an rvalue.
427 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
428 if (argIsLvalue == Expr::LV_Valid &&
429 !FromType->isFunctionType() && !FromType->isArrayType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000430 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000431
432 // If T is a non-class type, the type of the rvalue is the
433 // cv-unqualified version of T. Otherwise, the type of the rvalue
434 // is T (C++ 4.1p1).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000435 FromType = FromType.getUnqualifiedType();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000436 }
437 // Array-to-pointer conversion (C++ 4.2)
438 else if (FromType->isArrayType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000439 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000440
441 // An lvalue or rvalue of type "array of N T" or "array of unknown
442 // bound of T" can be converted to an rvalue of type "pointer to
443 // T" (C++ 4.2p1).
444 FromType = Context.getArrayDecayedType(FromType);
445
446 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
447 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000448 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000449
450 // For the purpose of ranking in overload resolution
451 // (13.3.3.1.1), this conversion is considered an
452 // array-to-pointer conversion followed by a qualification
453 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000454 SCS.Second = ICK_Identity;
455 SCS.Third = ICK_Qualification;
456 SCS.ToTypePtr = ToType.getAsOpaquePtr();
457 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000458 }
459 }
460 // Function-to-pointer conversion (C++ 4.3).
461 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000462 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000463
464 // An lvalue of function type T can be converted to an rvalue of
465 // type "pointer to T." The result is a pointer to the
466 // function. (C++ 4.3p1).
467 FromType = Context.getPointerType(FromType);
468
469 // FIXME: Deal with overloaded functions here (C++ 4.3p2).
470 }
471 // We don't require any conversions for the first step.
472 else {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000473 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000474 }
475
476 // The second conversion can be an integral promotion, floating
477 // point promotion, integral conversion, floating point conversion,
478 // floating-integral conversion, pointer conversion,
479 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
480 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
481 Context.getCanonicalType(ToType).getUnqualifiedType()) {
482 // The unqualified versions of the types are the same: there's no
483 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000484 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000485 }
486 // Integral promotion (C++ 4.5).
487 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000488 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000489 FromType = ToType.getUnqualifiedType();
490 }
491 // Floating point promotion (C++ 4.6).
492 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000493 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000494 FromType = ToType.getUnqualifiedType();
495 }
496 // Integral conversions (C++ 4.7).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000497 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000498 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000499 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000500 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000501 FromType = ToType.getUnqualifiedType();
502 }
503 // Floating point conversions (C++ 4.8).
504 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000505 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000506 FromType = ToType.getUnqualifiedType();
507 }
508 // Floating-integral conversions (C++ 4.9).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000509 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000510 else if ((FromType->isFloatingType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000511 ToType->isIntegralType() && !ToType->isBooleanType() &&
512 !ToType->isEnumeralType()) ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000513 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
514 ToType->isFloatingType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000515 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000516 FromType = ToType.getUnqualifiedType();
517 }
518 // Pointer conversions (C++ 4.10).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000519 else if (IsPointerConversion(From, FromType, ToType, FromType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000520 SCS.Second = ICK_Pointer_Conversion;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000521 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000522 // FIXME: Pointer to member conversions (4.11).
523 // Boolean conversions (C++ 4.12).
524 // FIXME: pointer-to-member type
525 else if (ToType->isBooleanType() &&
526 (FromType->isArithmeticType() ||
527 FromType->isEnumeralType() ||
528 FromType->isPointerType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000529 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000530 FromType = Context.BoolTy;
531 } else {
532 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000533 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000534 }
535
Douglas Gregor81c29152008-10-29 00:13:59 +0000536 QualType CanonFrom;
537 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000538 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000539 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000540 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000541 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000542 CanonFrom = Context.getCanonicalType(FromType);
543 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000544 } else {
545 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000546 SCS.Third = ICK_Identity;
547
548 // C++ [over.best.ics]p6:
549 // [...] Any difference in top-level cv-qualification is
550 // subsumed by the initialization itself and does not constitute
551 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000552 CanonFrom = Context.getCanonicalType(FromType);
553 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000554 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000555 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
556 FromType = ToType;
557 CanonFrom = CanonTo;
558 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000559 }
560
561 // If we have not converted the argument type to the parameter type,
562 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000563 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000564 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000565
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000566 SCS.ToTypePtr = FromType.getAsOpaquePtr();
567 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000568}
569
570/// IsIntegralPromotion - Determines whether the conversion from the
571/// expression From (whose potentially-adjusted type is FromType) to
572/// ToType is an integral promotion (C++ 4.5). If so, returns true and
573/// sets PromotedType to the promoted type.
574bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
575{
576 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000577 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000578 if (!To) {
579 return false;
580 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000581
582 // An rvalue of type char, signed char, unsigned char, short int, or
583 // unsigned short int can be converted to an rvalue of type int if
584 // int can represent all the values of the source type; otherwise,
585 // the source rvalue can be converted to an rvalue of type unsigned
586 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000587 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000588 if (// We can promote any signed, promotable integer type to an int
589 (FromType->isSignedIntegerType() ||
590 // We can promote any unsigned integer type whose size is
591 // less than int to an int.
592 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000593 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000594 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000595 }
596
Douglas Gregord2baafd2008-10-21 16:13:35 +0000597 return To->getKind() == BuiltinType::UInt;
598 }
599
600 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
601 // can be converted to an rvalue of the first of the following types
602 // that can represent all the values of its underlying type: int,
603 // unsigned int, long, or unsigned long (C++ 4.5p2).
604 if ((FromType->isEnumeralType() || FromType->isWideCharType())
605 && ToType->isIntegerType()) {
606 // Determine whether the type we're converting from is signed or
607 // unsigned.
608 bool FromIsSigned;
609 uint64_t FromSize = Context.getTypeSize(FromType);
610 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
611 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
612 FromIsSigned = UnderlyingType->isSignedIntegerType();
613 } else {
614 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
615 FromIsSigned = true;
616 }
617
618 // The types we'll try to promote to, in the appropriate
619 // order. Try each of these types.
620 QualType PromoteTypes[4] = {
621 Context.IntTy, Context.UnsignedIntTy,
622 Context.LongTy, Context.UnsignedLongTy
623 };
624 for (int Idx = 0; Idx < 0; ++Idx) {
625 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
626 if (FromSize < ToSize ||
627 (FromSize == ToSize &&
628 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
629 // We found the type that we can promote to. If this is the
630 // type we wanted, we have a promotion. Otherwise, no
631 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000632 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000633 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
634 }
635 }
636 }
637
638 // An rvalue for an integral bit-field (9.6) can be converted to an
639 // rvalue of type int if int can represent all the values of the
640 // bit-field; otherwise, it can be converted to unsigned int if
641 // unsigned int can represent all the values of the bit-field. If
642 // the bit-field is larger yet, no integral promotion applies to
643 // it. If the bit-field has an enumerated type, it is treated as any
644 // other value of that type for promotion purposes (C++ 4.5p3).
645 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
646 using llvm::APSInt;
647 FieldDecl *MemberDecl = MemRef->getMemberDecl();
648 APSInt BitWidth;
649 if (MemberDecl->isBitField() &&
650 FromType->isIntegralType() && !FromType->isEnumeralType() &&
651 From->isIntegerConstantExpr(BitWidth, Context)) {
652 APSInt ToSize(Context.getTypeSize(ToType));
653
654 // Are we promoting to an int from a bitfield that fits in an int?
655 if (BitWidth < ToSize ||
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000656 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000657 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000658 }
659
Douglas Gregord2baafd2008-10-21 16:13:35 +0000660 // Are we promoting to an unsigned int from an unsigned bitfield
661 // that fits into an unsigned int?
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000662 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000663 return To->getKind() == BuiltinType::UInt;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000664 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000665
666 return false;
667 }
668 }
669
670 // An rvalue of type bool can be converted to an rvalue of type int,
671 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000672 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000673 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000674 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000675
676 return false;
677}
678
679/// IsFloatingPointPromotion - Determines whether the conversion from
680/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
681/// returns true and sets PromotedType to the promoted type.
682bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
683{
684 /// An rvalue of type float can be converted to an rvalue of type
685 /// double. (C++ 4.6p1).
686 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
687 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
688 if (FromBuiltin->getKind() == BuiltinType::Float &&
689 ToBuiltin->getKind() == BuiltinType::Double)
690 return true;
691
692 return false;
693}
694
695/// IsPointerConversion - Determines whether the conversion of the
696/// expression From, which has the (possibly adjusted) type FromType,
697/// can be converted to the type ToType via a pointer conversion (C++
698/// 4.10). If so, returns true and places the converted type (that
699/// might differ from ToType in its cv-qualifiers at some level) into
700/// ConvertedType.
701bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
702 QualType& ConvertedType)
703{
704 const PointerType* ToTypePtr = ToType->getAsPointerType();
705 if (!ToTypePtr)
706 return false;
707
708 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
709 if (From->isNullPointerConstant(Context)) {
710 ConvertedType = ToType;
711 return true;
712 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000713
Douglas Gregord2baafd2008-10-21 16:13:35 +0000714 // An rvalue of type "pointer to cv T," where T is an object type,
715 // can be converted to an rvalue of type "pointer to cv void" (C++
716 // 4.10p2).
717 if (FromType->isPointerType() &&
718 FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
719 ToTypePtr->getPointeeType()->isVoidType()) {
720 // We need to produce a pointer to cv void, where cv is the same
721 // set of cv-qualifiers as we had on the incoming pointee type.
722 QualType toPointee = ToTypePtr->getPointeeType();
723 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
724 ->getPointeeType().getCVRQualifiers();
725
726 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
727 == Quals) {
728 // ToType is exactly the type we want. Use it.
729 ConvertedType = ToType;
730 } else {
731 // Build a new type with the right qualifiers.
732 ConvertedType
733 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
734 }
735 return true;
736 }
737
Douglas Gregor14046502008-10-23 00:40:37 +0000738 // C++ [conv.ptr]p3:
739 //
740 // An rvalue of type "pointer to cv D," where D is a class type,
741 // can be converted to an rvalue of type "pointer to cv B," where
742 // B is a base class (clause 10) of D. If B is an inaccessible
743 // (clause 11) or ambiguous (10.2) base class of D, a program that
744 // necessitates this conversion is ill-formed. The result of the
745 // conversion is a pointer to the base class sub-object of the
746 // derived class object. The null pointer value is converted to
747 // the null pointer value of the destination type.
748 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000749 // Note that we do not check for ambiguity or inaccessibility
750 // here. That is handled by CheckPointerConversion.
Douglas Gregor14046502008-10-23 00:40:37 +0000751 if (const PointerType *FromPtrType = FromType->getAsPointerType())
752 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
753 if (FromPtrType->getPointeeType()->isRecordType() &&
754 ToPtrType->getPointeeType()->isRecordType() &&
755 IsDerivedFrom(FromPtrType->getPointeeType(),
756 ToPtrType->getPointeeType())) {
757 // The conversion is okay. Now, we need to produce the type
758 // that results from this conversion, which will have the same
759 // qualifiers as the incoming type.
760 QualType CanonFromPointee
761 = Context.getCanonicalType(FromPtrType->getPointeeType());
762 QualType ToPointee = ToPtrType->getPointeeType();
763 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
764 unsigned Quals = CanonFromPointee.getCVRQualifiers();
765
766 if (CanonToPointee.getCVRQualifiers() == Quals) {
767 // ToType is exactly the type we want. Use it.
768 ConvertedType = ToType;
769 } else {
770 // Build a new type with the right qualifiers.
771 ConvertedType
772 = Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
773 }
774 return true;
775 }
776 }
777
Douglas Gregord2baafd2008-10-21 16:13:35 +0000778 return false;
779}
780
Douglas Gregorbb461502008-10-24 04:54:22 +0000781/// CheckPointerConversion - Check the pointer conversion from the
782/// expression From to the type ToType. This routine checks for
783/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
784/// conversions for which IsPointerConversion has already returned
785/// true. It returns true and produces a diagnostic if there was an
786/// error, or returns false otherwise.
787bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
788 QualType FromType = From->getType();
789
790 if (const PointerType *FromPtrType = FromType->getAsPointerType())
791 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000792 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
793 /*DetectVirtual=*/false);
Douglas Gregorbb461502008-10-24 04:54:22 +0000794 QualType FromPointeeType = FromPtrType->getPointeeType(),
795 ToPointeeType = ToPtrType->getPointeeType();
796 if (FromPointeeType->isRecordType() &&
797 ToPointeeType->isRecordType()) {
798 // We must have a derived-to-base conversion. Check an
799 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +0000800 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
801 From->getExprLoc(),
802 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +0000803 }
804 }
805
806 return false;
807}
808
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000809/// IsQualificationConversion - Determines whether the conversion from
810/// an rvalue of type FromType to ToType is a qualification conversion
811/// (C++ 4.4).
812bool
813Sema::IsQualificationConversion(QualType FromType, QualType ToType)
814{
815 FromType = Context.getCanonicalType(FromType);
816 ToType = Context.getCanonicalType(ToType);
817
818 // If FromType and ToType are the same type, this is not a
819 // qualification conversion.
820 if (FromType == ToType)
821 return false;
822
823 // (C++ 4.4p4):
824 // A conversion can add cv-qualifiers at levels other than the first
825 // in multi-level pointers, subject to the following rules: [...]
826 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000827 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +0000828 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000829 // Within each iteration of the loop, we check the qualifiers to
830 // determine if this still looks like a qualification
831 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +0000832 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000833 // until there are no more pointers or pointers-to-members left to
834 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +0000835 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000836
837 // -- for every j > 0, if const is in cv 1,j then const is in cv
838 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +0000839 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000840 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +0000841
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000842 // -- if the cv 1,j and cv 2,j are different, then const is in
843 // every cv for 0 < k < j.
844 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +0000845 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000846 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +0000847
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000848 // Keep track of whether all prior cv-qualifiers in the "to" type
849 // include const.
850 PreviousToQualsIncludeConst
851 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +0000852 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000853
854 // We are left with FromType and ToType being the pointee types
855 // after unwrapping the original FromType and ToType the same number
856 // of types. If we unwrapped any pointers, and if FromType and
857 // ToType have the same unqualified type (since we checked
858 // qualifiers above), then this is a qualification conversion.
859 return UnwrappedAnyPointer &&
860 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
861}
862
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000863/// IsUserDefinedConversion - Determines whether there is a
864/// user-defined conversion sequence (C++ [over.ics.user]) that
865/// converts expression From to the type ToType. If such a conversion
866/// exists, User will contain the user-defined conversion sequence
867/// that performs such a conversion and this routine will return
868/// true. Otherwise, this routine returns false and User is
869/// unspecified.
870bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
871 UserDefinedConversionSequence& User)
872{
873 OverloadCandidateSet CandidateSet;
874 if (const CXXRecordType *ToRecordType
875 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
876 // C++ [over.match.ctor]p1:
877 // When objects of class type are direct-initialized (8.5), or
878 // copy-initialized from an expression of the same or a
879 // derived class type (8.5), overload resolution selects the
880 // constructor. [...] For copy-initialization, the candidate
881 // functions are all the converting constructors (12.3.1) of
882 // that class. The argument list is the expression-list within
883 // the parentheses of the initializer.
884 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
885 const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors();
886 for (OverloadedFunctionDecl::function_const_iterator func
887 = Constructors->function_begin();
888 func != Constructors->function_end(); ++func) {
889 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
890 if (Constructor->isConvertingConstructor())
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000891 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
892 /*SuppressUserConversions=*/true);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000893 }
894 }
895
Douglas Gregor60714f92008-11-07 22:36:19 +0000896 if (const CXXRecordType *FromRecordType
897 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
898 // Add all of the conversion functions as candidates.
899 // FIXME: Look for conversions in base classes!
900 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
901 OverloadedFunctionDecl *Conversions
902 = FromRecordDecl->getConversionFunctions();
903 for (OverloadedFunctionDecl::function_iterator Func
904 = Conversions->function_begin();
905 Func != Conversions->function_end(); ++Func) {
906 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
907 AddConversionCandidate(Conv, From, ToType, CandidateSet);
908 }
909 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000910
911 OverloadCandidateSet::iterator Best;
912 switch (BestViableFunction(CandidateSet, Best)) {
913 case OR_Success:
914 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000915 if (CXXConstructorDecl *Constructor
916 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
917 // C++ [over.ics.user]p1:
918 // If the user-defined conversion is specified by a
919 // constructor (12.3.1), the initial standard conversion
920 // sequence converts the source type to the type required by
921 // the argument of the constructor.
922 //
923 // FIXME: What about ellipsis conversions?
924 QualType ThisType = Constructor->getThisType(Context);
925 User.Before = Best->Conversions[0].Standard;
926 User.ConversionFunction = Constructor;
927 User.After.setAsIdentityConversion();
928 User.After.FromTypePtr
929 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
930 User.After.ToTypePtr = ToType.getAsOpaquePtr();
931 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +0000932 } else if (CXXConversionDecl *Conversion
933 = dyn_cast<CXXConversionDecl>(Best->Function)) {
934 // C++ [over.ics.user]p1:
935 //
936 // [...] If the user-defined conversion is specified by a
937 // conversion function (12.3.2), the initial standard
938 // conversion sequence converts the source type to the
939 // implicit object parameter of the conversion function.
940 User.Before = Best->Conversions[0].Standard;
941 User.ConversionFunction = Conversion;
942
943 // C++ [over.ics.user]p2:
944 // The second standard conversion sequence converts the
945 // result of the user-defined conversion to the target type
946 // for the sequence. Since an implicit conversion sequence
947 // is an initialization, the special rules for
948 // initialization by user-defined conversion apply when
949 // selecting the best user-defined conversion for a
950 // user-defined conversion sequence (see 13.3.3 and
951 // 13.3.3.1).
952 User.After = Best->FinalConversion;
953 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000954 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +0000955 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000956 return false;
957 }
958
959 case OR_No_Viable_Function:
960 // No conversion here! We're done.
961 return false;
962
963 case OR_Ambiguous:
964 // FIXME: See C++ [over.best.ics]p10 for the handling of
965 // ambiguous conversion sequences.
966 return false;
967 }
968
969 return false;
970}
971
Douglas Gregord2baafd2008-10-21 16:13:35 +0000972/// CompareImplicitConversionSequences - Compare two implicit
973/// conversion sequences to determine whether one is better than the
974/// other or if they are indistinguishable (C++ 13.3.3.2).
975ImplicitConversionSequence::CompareKind
976Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
977 const ImplicitConversionSequence& ICS2)
978{
979 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
980 // conversion sequences (as defined in 13.3.3.1)
981 // -- a standard conversion sequence (13.3.3.1.1) is a better
982 // conversion sequence than a user-defined conversion sequence or
983 // an ellipsis conversion sequence, and
984 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
985 // conversion sequence than an ellipsis conversion sequence
986 // (13.3.3.1.3).
987 //
988 if (ICS1.ConversionKind < ICS2.ConversionKind)
989 return ImplicitConversionSequence::Better;
990 else if (ICS2.ConversionKind < ICS1.ConversionKind)
991 return ImplicitConversionSequence::Worse;
992
993 // Two implicit conversion sequences of the same form are
994 // indistinguishable conversion sequences unless one of the
995 // following rules apply: (C++ 13.3.3.2p3):
996 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
997 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
998 else if (ICS1.ConversionKind ==
999 ImplicitConversionSequence::UserDefinedConversion) {
1000 // User-defined conversion sequence U1 is a better conversion
1001 // sequence than another user-defined conversion sequence U2 if
1002 // they contain the same user-defined conversion function or
1003 // constructor and if the second standard conversion sequence of
1004 // U1 is better than the second standard conversion sequence of
1005 // U2 (C++ 13.3.3.2p3).
1006 if (ICS1.UserDefined.ConversionFunction ==
1007 ICS2.UserDefined.ConversionFunction)
1008 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1009 ICS2.UserDefined.After);
1010 }
1011
1012 return ImplicitConversionSequence::Indistinguishable;
1013}
1014
1015/// CompareStandardConversionSequences - Compare two standard
1016/// conversion sequences to determine whether one is better than the
1017/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1018ImplicitConversionSequence::CompareKind
1019Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1020 const StandardConversionSequence& SCS2)
1021{
1022 // Standard conversion sequence S1 is a better conversion sequence
1023 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1024
1025 // -- S1 is a proper subsequence of S2 (comparing the conversion
1026 // sequences in the canonical form defined by 13.3.3.1.1,
1027 // excluding any Lvalue Transformation; the identity conversion
1028 // sequence is considered to be a subsequence of any
1029 // non-identity conversion sequence) or, if not that,
1030 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1031 // Neither is a proper subsequence of the other. Do nothing.
1032 ;
1033 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1034 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1035 (SCS1.Second == ICK_Identity &&
1036 SCS1.Third == ICK_Identity))
1037 // SCS1 is a proper subsequence of SCS2.
1038 return ImplicitConversionSequence::Better;
1039 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1040 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1041 (SCS2.Second == ICK_Identity &&
1042 SCS2.Third == ICK_Identity))
1043 // SCS2 is a proper subsequence of SCS1.
1044 return ImplicitConversionSequence::Worse;
1045
1046 // -- the rank of S1 is better than the rank of S2 (by the rules
1047 // defined below), or, if not that,
1048 ImplicitConversionRank Rank1 = SCS1.getRank();
1049 ImplicitConversionRank Rank2 = SCS2.getRank();
1050 if (Rank1 < Rank2)
1051 return ImplicitConversionSequence::Better;
1052 else if (Rank2 < Rank1)
1053 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001054
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001055 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1056 // are indistinguishable unless one of the following rules
1057 // applies:
1058
1059 // A conversion that is not a conversion of a pointer, or
1060 // pointer to member, to bool is better than another conversion
1061 // that is such a conversion.
1062 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1063 return SCS2.isPointerConversionToBool()
1064 ? ImplicitConversionSequence::Better
1065 : ImplicitConversionSequence::Worse;
1066
Douglas Gregor14046502008-10-23 00:40:37 +00001067 // C++ [over.ics.rank]p4b2:
1068 //
1069 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001070 // conversion of B* to A* is better than conversion of B* to
1071 // void*, and conversion of A* to void* is better than conversion
1072 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001073 bool SCS1ConvertsToVoid
1074 = SCS1.isPointerConversionToVoidPointer(Context);
1075 bool SCS2ConvertsToVoid
1076 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001077 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1078 // Exactly one of the conversion sequences is a conversion to
1079 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001080 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1081 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001082 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1083 // Neither conversion sequence converts to a void pointer; compare
1084 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001085 if (ImplicitConversionSequence::CompareKind DerivedCK
1086 = CompareDerivedToBaseConversions(SCS1, SCS2))
1087 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001088 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1089 // Both conversion sequences are conversions to void
1090 // pointers. Compare the source types to determine if there's an
1091 // inheritance relationship in their sources.
1092 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1093 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1094
1095 // Adjust the types we're converting from via the array-to-pointer
1096 // conversion, if we need to.
1097 if (SCS1.First == ICK_Array_To_Pointer)
1098 FromType1 = Context.getArrayDecayedType(FromType1);
1099 if (SCS2.First == ICK_Array_To_Pointer)
1100 FromType2 = Context.getArrayDecayedType(FromType2);
1101
1102 QualType FromPointee1
1103 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1104 QualType FromPointee2
1105 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1106
1107 if (IsDerivedFrom(FromPointee2, FromPointee1))
1108 return ImplicitConversionSequence::Better;
1109 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1110 return ImplicitConversionSequence::Worse;
1111 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001112
1113 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1114 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001115 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001116 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001117 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001118
Douglas Gregor0e343382008-10-29 14:50:44 +00001119 // C++ [over.ics.rank]p3b4:
1120 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1121 // which the references refer are the same type except for
1122 // top-level cv-qualifiers, and the type to which the reference
1123 // initialized by S2 refers is more cv-qualified than the type
1124 // to which the reference initialized by S1 refers.
1125 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1126 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1127 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1128 T1 = Context.getCanonicalType(T1);
1129 T2 = Context.getCanonicalType(T2);
1130 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1131 if (T2.isMoreQualifiedThan(T1))
1132 return ImplicitConversionSequence::Better;
1133 else if (T1.isMoreQualifiedThan(T2))
1134 return ImplicitConversionSequence::Worse;
1135 }
1136 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001137
1138 return ImplicitConversionSequence::Indistinguishable;
1139}
1140
1141/// CompareQualificationConversions - Compares two standard conversion
1142/// sequences to determine whether they can be ranked based on their
1143/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1144ImplicitConversionSequence::CompareKind
1145Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1146 const StandardConversionSequence& SCS2)
1147{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001148 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001149 // -- S1 and S2 differ only in their qualification conversion and
1150 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1151 // cv-qualification signature of type T1 is a proper subset of
1152 // the cv-qualification signature of type T2, and S1 is not the
1153 // deprecated string literal array-to-pointer conversion (4.2).
1154 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1155 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1156 return ImplicitConversionSequence::Indistinguishable;
1157
1158 // FIXME: the example in the standard doesn't use a qualification
1159 // conversion (!)
1160 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1161 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1162 T1 = Context.getCanonicalType(T1);
1163 T2 = Context.getCanonicalType(T2);
1164
1165 // If the types are the same, we won't learn anything by unwrapped
1166 // them.
1167 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1168 return ImplicitConversionSequence::Indistinguishable;
1169
1170 ImplicitConversionSequence::CompareKind Result
1171 = ImplicitConversionSequence::Indistinguishable;
1172 while (UnwrapSimilarPointerTypes(T1, T2)) {
1173 // Within each iteration of the loop, we check the qualifiers to
1174 // determine if this still looks like a qualification
1175 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001176 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001177 // until there are no more pointers or pointers-to-members left
1178 // to unwrap. This essentially mimics what
1179 // IsQualificationConversion does, but here we're checking for a
1180 // strict subset of qualifiers.
1181 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1182 // The qualifiers are the same, so this doesn't tell us anything
1183 // about how the sequences rank.
1184 ;
1185 else if (T2.isMoreQualifiedThan(T1)) {
1186 // T1 has fewer qualifiers, so it could be the better sequence.
1187 if (Result == ImplicitConversionSequence::Worse)
1188 // Neither has qualifiers that are a subset of the other's
1189 // qualifiers.
1190 return ImplicitConversionSequence::Indistinguishable;
1191
1192 Result = ImplicitConversionSequence::Better;
1193 } else if (T1.isMoreQualifiedThan(T2)) {
1194 // T2 has fewer qualifiers, so it could be the better sequence.
1195 if (Result == ImplicitConversionSequence::Better)
1196 // Neither has qualifiers that are a subset of the other's
1197 // qualifiers.
1198 return ImplicitConversionSequence::Indistinguishable;
1199
1200 Result = ImplicitConversionSequence::Worse;
1201 } else {
1202 // Qualifiers are disjoint.
1203 return ImplicitConversionSequence::Indistinguishable;
1204 }
1205
1206 // If the types after this point are equivalent, we're done.
1207 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1208 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001209 }
1210
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001211 // Check that the winning standard conversion sequence isn't using
1212 // the deprecated string literal array to pointer conversion.
1213 switch (Result) {
1214 case ImplicitConversionSequence::Better:
1215 if (SCS1.Deprecated)
1216 Result = ImplicitConversionSequence::Indistinguishable;
1217 break;
1218
1219 case ImplicitConversionSequence::Indistinguishable:
1220 break;
1221
1222 case ImplicitConversionSequence::Worse:
1223 if (SCS2.Deprecated)
1224 Result = ImplicitConversionSequence::Indistinguishable;
1225 break;
1226 }
1227
1228 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001229}
1230
Douglas Gregor14046502008-10-23 00:40:37 +00001231/// CompareDerivedToBaseConversions - Compares two standard conversion
1232/// sequences to determine whether they can be ranked based on their
1233/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3).
1234ImplicitConversionSequence::CompareKind
1235Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1236 const StandardConversionSequence& SCS2) {
1237 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1238 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1239 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1240 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1241
1242 // Adjust the types we're converting from via the array-to-pointer
1243 // conversion, if we need to.
1244 if (SCS1.First == ICK_Array_To_Pointer)
1245 FromType1 = Context.getArrayDecayedType(FromType1);
1246 if (SCS2.First == ICK_Array_To_Pointer)
1247 FromType2 = Context.getArrayDecayedType(FromType2);
1248
1249 // Canonicalize all of the types.
1250 FromType1 = Context.getCanonicalType(FromType1);
1251 ToType1 = Context.getCanonicalType(ToType1);
1252 FromType2 = Context.getCanonicalType(FromType2);
1253 ToType2 = Context.getCanonicalType(ToType2);
1254
Douglas Gregor0e343382008-10-29 14:50:44 +00001255 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001256 //
1257 // If class B is derived directly or indirectly from class A and
1258 // class C is derived directly or indirectly from B,
Douglas Gregor0e343382008-10-29 14:50:44 +00001259
1260 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001261 if (SCS1.Second == ICK_Pointer_Conversion &&
1262 SCS2.Second == ICK_Pointer_Conversion) {
Douglas Gregor14046502008-10-23 00:40:37 +00001263 QualType FromPointee1
1264 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1265 QualType ToPointee1
1266 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1267 QualType FromPointee2
1268 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1269 QualType ToPointee2
1270 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001271 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001272 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1273 if (IsDerivedFrom(ToPointee1, ToPointee2))
1274 return ImplicitConversionSequence::Better;
1275 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1276 return ImplicitConversionSequence::Worse;
1277 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001278
1279 // -- conversion of B* to A* is better than conversion of C* to A*,
1280 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1281 if (IsDerivedFrom(FromPointee2, FromPointee1))
1282 return ImplicitConversionSequence::Better;
1283 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1284 return ImplicitConversionSequence::Worse;
1285 }
Douglas Gregor14046502008-10-23 00:40:37 +00001286 }
1287
Douglas Gregor0e343382008-10-29 14:50:44 +00001288 // Compare based on reference bindings.
1289 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1290 SCS1.Second == ICK_Derived_To_Base) {
1291 // -- binding of an expression of type C to a reference of type
1292 // B& is better than binding an expression of type C to a
1293 // reference of type A&,
1294 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1295 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1296 if (IsDerivedFrom(ToType1, ToType2))
1297 return ImplicitConversionSequence::Better;
1298 else if (IsDerivedFrom(ToType2, ToType1))
1299 return ImplicitConversionSequence::Worse;
1300 }
1301
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001302 // -- binding of an expression of type B to a reference of type
1303 // A& is better than binding an expression of type C to a
1304 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001305 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1306 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1307 if (IsDerivedFrom(FromType2, FromType1))
1308 return ImplicitConversionSequence::Better;
1309 else if (IsDerivedFrom(FromType1, FromType2))
1310 return ImplicitConversionSequence::Worse;
1311 }
1312 }
1313
1314
1315 // FIXME: conversion of A::* to B::* is better than conversion of
1316 // A::* to C::*,
1317
1318 // FIXME: conversion of B::* to C::* is better than conversion of
1319 // A::* to C::*, and
1320
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001321 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1322 SCS1.Second == ICK_Derived_To_Base) {
1323 // -- conversion of C to B is better than conversion of C to A,
1324 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1325 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1326 if (IsDerivedFrom(ToType1, ToType2))
1327 return ImplicitConversionSequence::Better;
1328 else if (IsDerivedFrom(ToType2, ToType1))
1329 return ImplicitConversionSequence::Worse;
1330 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001331
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001332 // -- conversion of B to A is better than conversion of C to A.
1333 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1334 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1335 if (IsDerivedFrom(FromType2, FromType1))
1336 return ImplicitConversionSequence::Better;
1337 else if (IsDerivedFrom(FromType1, FromType2))
1338 return ImplicitConversionSequence::Worse;
1339 }
1340 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001341
Douglas Gregor14046502008-10-23 00:40:37 +00001342 return ImplicitConversionSequence::Indistinguishable;
1343}
1344
Douglas Gregor81c29152008-10-29 00:13:59 +00001345/// TryCopyInitialization - Try to copy-initialize a value of type
1346/// ToType from the expression From. Return the implicit conversion
1347/// sequence required to pass this argument, which may be a bad
1348/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001349/// a parameter of this type). If @p SuppressUserConversions, then we
1350/// do not permit any user-defined conversion sequences.
Douglas Gregor81c29152008-10-29 00:13:59 +00001351ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001352Sema::TryCopyInitialization(Expr *From, QualType ToType,
1353 bool SuppressUserConversions) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001354 if (!getLangOptions().CPlusPlus) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001355 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor81c29152008-10-29 00:13:59 +00001356 AssignConvertType ConvTy =
1357 CheckSingleAssignmentConstraints(ToType, From);
1358 ImplicitConversionSequence ICS;
1359 if (getLangOptions().NoExtensions? ConvTy != Compatible
1360 : ConvTy == Incompatible)
1361 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1362 else
1363 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1364 return ICS;
1365 } else if (ToType->isReferenceType()) {
1366 ImplicitConversionSequence ICS;
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001367 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001368 return ICS;
1369 } else {
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001370 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001371 }
1372}
1373
1374/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1375/// type ToType. Returns true (and emits a diagnostic) if there was
1376/// an error, returns false if the initialization succeeded.
1377bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1378 const char* Flavor) {
1379 if (!getLangOptions().CPlusPlus) {
1380 // In C, argument passing is the same as performing an assignment.
1381 QualType FromType = From->getType();
1382 AssignConvertType ConvTy =
1383 CheckSingleAssignmentConstraints(ToType, From);
1384
1385 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1386 FromType, From, Flavor);
1387 } else if (ToType->isReferenceType()) {
1388 return CheckReferenceInit(From, ToType);
1389 } else {
1390 if (PerformImplicitConversion(From, ToType))
1391 return Diag(From->getSourceRange().getBegin(),
1392 diag::err_typecheck_convert_incompatible,
1393 ToType.getAsString(), From->getType().getAsString(),
1394 Flavor,
1395 From->getSourceRange());
1396 else
1397 return false;
1398 }
1399}
1400
Douglas Gregord2baafd2008-10-21 16:13:35 +00001401/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001402/// candidate functions, using the given function call arguments. If
1403/// @p SuppressUserConversions, then don't allow user-defined
1404/// conversions via constructors or conversion operators.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001405void
1406Sema::AddOverloadCandidate(FunctionDecl *Function,
1407 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001408 OverloadCandidateSet& CandidateSet,
1409 bool SuppressUserConversions)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001410{
1411 const FunctionTypeProto* Proto
1412 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1413 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00001414 assert(!isa<CXXConversionDecl>(Function) &&
1415 "Use AddConversionCandidate for conversion functions");
Douglas Gregord2baafd2008-10-21 16:13:35 +00001416
1417 // Add this candidate
1418 CandidateSet.push_back(OverloadCandidate());
1419 OverloadCandidate& Candidate = CandidateSet.back();
1420 Candidate.Function = Function;
1421
1422 unsigned NumArgsInProto = Proto->getNumArgs();
1423
1424 // (C++ 13.3.2p2): A candidate function having fewer than m
1425 // parameters is viable only if it has an ellipsis in its parameter
1426 // list (8.3.5).
1427 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1428 Candidate.Viable = false;
1429 return;
1430 }
1431
1432 // (C++ 13.3.2p2): A candidate function having more than m parameters
1433 // is viable only if the (m+1)st parameter has a default argument
1434 // (8.3.6). For the purposes of overload resolution, the
1435 // parameter list is truncated on the right, so that there are
1436 // exactly m parameters.
1437 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1438 if (NumArgs < MinRequiredArgs) {
1439 // Not enough arguments.
1440 Candidate.Viable = false;
1441 return;
1442 }
1443
1444 // Determine the implicit conversion sequences for each of the
1445 // arguments.
1446 Candidate.Viable = true;
1447 Candidate.Conversions.resize(NumArgs);
1448 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1449 if (ArgIdx < NumArgsInProto) {
1450 // (C++ 13.3.2p3): for F to be a viable function, there shall
1451 // exist for each argument an implicit conversion sequence
1452 // (13.3.3.1) that converts that argument to the corresponding
1453 // parameter of F.
1454 QualType ParamType = Proto->getArgType(ArgIdx);
1455 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001456 = TryCopyInitialization(Args[ArgIdx], ParamType,
1457 SuppressUserConversions);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001458 if (Candidate.Conversions[ArgIdx].ConversionKind
1459 == ImplicitConversionSequence::BadConversion)
1460 Candidate.Viable = false;
1461 } else {
1462 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1463 // argument for which there is no corresponding parameter is
1464 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1465 Candidate.Conversions[ArgIdx].ConversionKind
1466 = ImplicitConversionSequence::EllipsisConversion;
1467 }
1468 }
1469}
1470
Douglas Gregor60714f92008-11-07 22:36:19 +00001471/// AddConversionCandidate - Add a C++ conversion function as a
1472/// candidate in the candidate set (C++ [over.match.conv],
1473/// C++ [over.match.copy]). From is the expression we're converting from,
1474/// and ToType is the type that we're eventually trying to convert to
1475/// (which may or may not be the same type as the type that the
1476/// conversion function produces).
1477void
1478Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1479 Expr *From, QualType ToType,
1480 OverloadCandidateSet& CandidateSet) {
1481 // Add this candidate
1482 CandidateSet.push_back(OverloadCandidate());
1483 OverloadCandidate& Candidate = CandidateSet.back();
1484 Candidate.Function = Conversion;
1485 Candidate.FinalConversion.setAsIdentityConversion();
1486 Candidate.FinalConversion.FromTypePtr
1487 = Conversion->getConversionType().getAsOpaquePtr();
1488 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1489
1490 // Determine the implicit conversion sequences for each of the
1491 // arguments.
1492 Candidate.Viable = true;
1493 Candidate.Conversions.resize(1);
1494
1495 // FIXME: We need to follow the rules for the implicit object
1496 // parameter.
1497 QualType ImplicitObjectType
1498 = Context.getTypeDeclType(Conversion->getParent());
1499 ImplicitObjectType
1500 = ImplicitObjectType.getQualifiedType(Conversion->getTypeQualifiers());
1501 ImplicitObjectType = Context.getReferenceType(ImplicitObjectType);
1502 Candidate.Conversions[0] = TryCopyInitialization(From, ImplicitObjectType,
1503 true);
1504 if (Candidate.Conversions[0].ConversionKind
1505 == ImplicitConversionSequence::BadConversion) {
1506 Candidate.Viable = false;
1507 return;
1508 }
1509
1510 // To determine what the conversion from the result of calling the
1511 // conversion function to the type we're eventually trying to
1512 // convert to (ToType), we need to synthesize a call to the
1513 // conversion function and attempt copy initialization from it. This
1514 // makes sure that we get the right semantics with respect to
1515 // lvalues/rvalues and the type. Fortunately, we can allocate this
1516 // call on the stack and we don't need its arguments to be
1517 // well-formed.
1518 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1519 SourceLocation());
1520 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
1521 &ConversionRef);
1522 CallExpr Call(&ConversionFn, 0, 0,
1523 Conversion->getConversionType().getNonReferenceType(),
1524 SourceLocation());
1525 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1526 switch (ICS.ConversionKind) {
1527 case ImplicitConversionSequence::StandardConversion:
1528 Candidate.FinalConversion = ICS.Standard;
1529 break;
1530
1531 case ImplicitConversionSequence::BadConversion:
1532 Candidate.Viable = false;
1533 break;
1534
1535 default:
1536 assert(false &&
1537 "Can only end up with a standard conversion sequence or failure");
1538 }
1539}
1540
Douglas Gregord2baafd2008-10-21 16:13:35 +00001541/// AddOverloadCandidates - Add all of the function overloads in Ovl
1542/// to the candidate set.
1543void
Douglas Gregor5870a952008-11-03 20:45:27 +00001544Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregord2baafd2008-10-21 16:13:35 +00001545 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001546 OverloadCandidateSet& CandidateSet,
1547 bool SuppressUserConversions)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001548{
Douglas Gregor5870a952008-11-03 20:45:27 +00001549 for (OverloadedFunctionDecl::function_const_iterator Func
1550 = Ovl->function_begin();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001551 Func != Ovl->function_end(); ++Func)
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001552 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
1553 SuppressUserConversions);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001554}
1555
1556/// isBetterOverloadCandidate - Determines whether the first overload
1557/// candidate is a better candidate than the second (C++ 13.3.3p1).
1558bool
1559Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
1560 const OverloadCandidate& Cand2)
1561{
1562 // Define viable functions to be better candidates than non-viable
1563 // functions.
1564 if (!Cand2.Viable)
1565 return Cand1.Viable;
1566 else if (!Cand1.Viable)
1567 return false;
1568
1569 // FIXME: Deal with the implicit object parameter for static member
1570 // functions. (C++ 13.3.3p1).
1571
1572 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
1573 // function than another viable function F2 if for all arguments i,
1574 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
1575 // then...
1576 unsigned NumArgs = Cand1.Conversions.size();
1577 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
1578 bool HasBetterConversion = false;
1579 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1580 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
1581 Cand2.Conversions[ArgIdx])) {
1582 case ImplicitConversionSequence::Better:
1583 // Cand1 has a better conversion sequence.
1584 HasBetterConversion = true;
1585 break;
1586
1587 case ImplicitConversionSequence::Worse:
1588 // Cand1 can't be better than Cand2.
1589 return false;
1590
1591 case ImplicitConversionSequence::Indistinguishable:
1592 // Do nothing.
1593 break;
1594 }
1595 }
1596
1597 if (HasBetterConversion)
1598 return true;
1599
1600 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be implemented.
1601
Douglas Gregor60714f92008-11-07 22:36:19 +00001602 // C++ [over.match.best]p1b4:
1603 //
1604 // -- the context is an initialization by user-defined conversion
1605 // (see 8.5, 13.3.1.5) and the standard conversion sequence
1606 // from the return type of F1 to the destination type (i.e.,
1607 // the type of the entity being initialized) is a better
1608 // conversion sequence than the standard conversion sequence
1609 // from the return type of F2 to the destination type.
1610 if (isa<CXXConversionDecl>(Cand1.Function) &&
1611 isa<CXXConversionDecl>(Cand2.Function)) {
1612 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
1613 Cand2.FinalConversion)) {
1614 case ImplicitConversionSequence::Better:
1615 // Cand1 has a better conversion sequence.
1616 return true;
1617
1618 case ImplicitConversionSequence::Worse:
1619 // Cand1 can't be better than Cand2.
1620 return false;
1621
1622 case ImplicitConversionSequence::Indistinguishable:
1623 // Do nothing
1624 break;
1625 }
1626 }
1627
Douglas Gregord2baafd2008-10-21 16:13:35 +00001628 return false;
1629}
1630
1631/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
1632/// within an overload candidate set. If overloading is successful,
1633/// the result will be OR_Success and Best will be set to point to the
1634/// best viable function within the candidate set. Otherwise, one of
1635/// several kinds of errors will be returned; see
1636/// Sema::OverloadingResult.
1637Sema::OverloadingResult
1638Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
1639 OverloadCandidateSet::iterator& Best)
1640{
1641 // Find the best viable function.
1642 Best = CandidateSet.end();
1643 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1644 Cand != CandidateSet.end(); ++Cand) {
1645 if (Cand->Viable) {
1646 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
1647 Best = Cand;
1648 }
1649 }
1650
1651 // If we didn't find any viable functions, abort.
1652 if (Best == CandidateSet.end())
1653 return OR_No_Viable_Function;
1654
1655 // Make sure that this function is better than every other viable
1656 // function. If not, we have an ambiguity.
1657 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1658 Cand != CandidateSet.end(); ++Cand) {
1659 if (Cand->Viable &&
1660 Cand != Best &&
1661 !isBetterOverloadCandidate(*Best, *Cand))
1662 return OR_Ambiguous;
1663 }
1664
1665 // Best is the best viable function.
1666 return OR_Success;
1667}
1668
1669/// PrintOverloadCandidates - When overload resolution fails, prints
1670/// diagnostic messages containing the candidates in the candidate
1671/// set. If OnlyViable is true, only viable candidates will be printed.
1672void
1673Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
1674 bool OnlyViable)
1675{
1676 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1677 LastCand = CandidateSet.end();
1678 for (; Cand != LastCand; ++Cand) {
1679 if (Cand->Viable ||!OnlyViable)
1680 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
1681 }
1682}
1683
1684} // end namespace clang