blob: 98a32ef26791cd395d0419f2eb2b926bbfb2da91 [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"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/AST/TypeOrdering.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000021#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000022#include "llvm/Support/Compiler.h"
23#include <algorithm>
24
25namespace clang {
26
27/// GetConversionCategory - Retrieve the implicit conversion
28/// category corresponding to the given implicit conversion kind.
29ImplicitConversionCategory
30GetConversionCategory(ImplicitConversionKind Kind) {
31 static const ImplicitConversionCategory
32 Category[(int)ICK_Num_Conversion_Kinds] = {
33 ICC_Identity,
34 ICC_Lvalue_Transformation,
35 ICC_Lvalue_Transformation,
36 ICC_Lvalue_Transformation,
37 ICC_Qualification_Adjustment,
38 ICC_Promotion,
39 ICC_Promotion,
40 ICC_Conversion,
41 ICC_Conversion,
42 ICC_Conversion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000045 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000046 ICC_Conversion
47 };
48 return Category[(int)Kind];
49}
50
51/// GetConversionRank - Retrieve the implicit conversion rank
52/// corresponding to the given implicit conversion kind.
53ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
54 static const ImplicitConversionRank
55 Rank[(int)ICK_Num_Conversion_Kinds] = {
56 ICR_Exact_Match,
57 ICR_Exact_Match,
58 ICR_Exact_Match,
59 ICR_Exact_Match,
60 ICR_Exact_Match,
61 ICR_Promotion,
62 ICR_Promotion,
63 ICR_Conversion,
64 ICR_Conversion,
65 ICR_Conversion,
66 ICR_Conversion,
67 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000068 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000069 ICR_Conversion
70 };
71 return Rank[(int)Kind];
72}
73
74/// GetImplicitConversionName - Return the name of this kind of
75/// implicit conversion.
76const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
77 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
78 "No conversion",
79 "Lvalue-to-rvalue",
80 "Array-to-pointer",
81 "Function-to-pointer",
82 "Qualification",
83 "Integral promotion",
84 "Floating point promotion",
85 "Integral conversion",
86 "Floating conversion",
87 "Floating-integral conversion",
88 "Pointer conversion",
89 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +000090 "Boolean conversion",
91 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092 };
93 return Name[Kind];
94}
95
Douglas Gregor60d62c22008-10-31 16:23:19 +000096/// StandardConversionSequence - Set the standard conversion
97/// sequence to the identity conversion.
98void StandardConversionSequence::setAsIdentityConversion() {
99 First = ICK_Identity;
100 Second = ICK_Identity;
101 Third = ICK_Identity;
102 Deprecated = false;
103 ReferenceBinding = false;
104 DirectBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000105 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000106}
107
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108/// getRank - Retrieve the rank of this standard conversion sequence
109/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
110/// implicit conversions.
111ImplicitConversionRank StandardConversionSequence::getRank() const {
112 ImplicitConversionRank Rank = ICR_Exact_Match;
113 if (GetConversionRank(First) > Rank)
114 Rank = GetConversionRank(First);
115 if (GetConversionRank(Second) > Rank)
116 Rank = GetConversionRank(Second);
117 if (GetConversionRank(Third) > Rank)
118 Rank = GetConversionRank(Third);
119 return Rank;
120}
121
122/// isPointerConversionToBool - Determines whether this conversion is
123/// a conversion of a pointer or pointer-to-member to bool. This is
124/// used as part of the ranking of standard conversion sequences
125/// (C++ 13.3.3.2p4).
126bool StandardConversionSequence::isPointerConversionToBool() const
127{
128 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
129 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
130
131 // Note that FromType has not necessarily been transformed by the
132 // array-to-pointer or function-to-pointer implicit conversions, so
133 // check for their presence as well as checking whether FromType is
134 // a pointer.
135 if (ToType->isBooleanType() &&
136 (FromType->isPointerType() ||
137 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
138 return true;
139
140 return false;
141}
142
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000143/// isPointerConversionToVoidPointer - Determines whether this
144/// conversion is a conversion of a pointer to a void pointer. This is
145/// used as part of the ranking of standard conversion sequences (C++
146/// 13.3.3.2p4).
147bool
148StandardConversionSequence::
149isPointerConversionToVoidPointer(ASTContext& Context) const
150{
151 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
152 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
153
154 // Note that FromType has not necessarily been transformed by the
155 // array-to-pointer implicit conversion, so check for its presence
156 // and redo the conversion to get a pointer.
157 if (First == ICK_Array_To_Pointer)
158 FromType = Context.getArrayDecayedType(FromType);
159
160 if (Second == ICK_Pointer_Conversion)
161 if (const PointerType* ToPtrType = ToType->getAsPointerType())
162 return ToPtrType->getPointeeType()->isVoidType();
163
164 return false;
165}
166
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167/// DebugPrint - Print this standard conversion sequence to standard
168/// error. Useful for debugging overloading issues.
169void StandardConversionSequence::DebugPrint() const {
170 bool PrintedSomething = false;
171 if (First != ICK_Identity) {
172 fprintf(stderr, "%s", GetImplicitConversionName(First));
173 PrintedSomething = true;
174 }
175
176 if (Second != ICK_Identity) {
177 if (PrintedSomething) {
178 fprintf(stderr, " -> ");
179 }
180 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000181
182 if (CopyConstructor) {
183 fprintf(stderr, " (by copy constructor)");
184 } else if (DirectBinding) {
185 fprintf(stderr, " (direct reference binding)");
186 } else if (ReferenceBinding) {
187 fprintf(stderr, " (reference binding)");
188 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Third != ICK_Identity) {
193 if (PrintedSomething) {
194 fprintf(stderr, " -> ");
195 }
196 fprintf(stderr, "%s", GetImplicitConversionName(Third));
197 PrintedSomething = true;
198 }
199
200 if (!PrintedSomething) {
201 fprintf(stderr, "No conversions required");
202 }
203}
204
205/// DebugPrint - Print this user-defined conversion sequence to standard
206/// error. Useful for debugging overloading issues.
207void UserDefinedConversionSequence::DebugPrint() const {
208 if (Before.First || Before.Second || Before.Third) {
209 Before.DebugPrint();
210 fprintf(stderr, " -> ");
211 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000212 fprintf(stderr, "'%s'", ConversionFunction->getName().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213 if (After.First || After.Second || After.Third) {
214 fprintf(stderr, " -> ");
215 After.DebugPrint();
216 }
217}
218
219/// DebugPrint - Print this implicit conversion sequence to standard
220/// error. Useful for debugging overloading issues.
221void ImplicitConversionSequence::DebugPrint() const {
222 switch (ConversionKind) {
223 case StandardConversion:
224 fprintf(stderr, "Standard conversion: ");
225 Standard.DebugPrint();
226 break;
227 case UserDefinedConversion:
228 fprintf(stderr, "User-defined conversion: ");
229 UserDefined.DebugPrint();
230 break;
231 case EllipsisConversion:
232 fprintf(stderr, "Ellipsis conversion");
233 break;
234 case BadConversion:
235 fprintf(stderr, "Bad conversion");
236 break;
237 }
238
239 fprintf(stderr, "\n");
240}
241
242// IsOverload - Determine whether the given New declaration is an
243// overload of the Old declaration. This routine returns false if New
244// and Old cannot be overloaded, e.g., if they are functions with the
245// same signature (C++ 1.3.10) or if the Old declaration isn't a
246// function (or overload set). When it does return false and Old is an
247// OverloadedFunctionDecl, MatchedDecl will be set to point to the
248// FunctionDecl that New cannot be overloaded with.
249//
250// Example: Given the following input:
251//
252// void f(int, float); // #1
253// void f(int, int); // #2
254// int f(int, int); // #3
255//
256// When we process #1, there is no previous declaration of "f",
257// so IsOverload will not be used.
258//
259// When we process #2, Old is a FunctionDecl for #1. By comparing the
260// parameter types, we see that #1 and #2 are overloaded (since they
261// have different signatures), so this routine returns false;
262// MatchedDecl is unchanged.
263//
264// When we process #3, Old is an OverloadedFunctionDecl containing #1
265// and #2. We compare the signatures of #3 to #1 (they're overloaded,
266// so we do nothing) and then #3 to #2. Since the signatures of #3 and
267// #2 are identical (return types of functions are not part of the
268// signature), IsOverload returns false and MatchedDecl will be set to
269// point to the FunctionDecl for #2.
270bool
271Sema::IsOverload(FunctionDecl *New, Decl* OldD,
272 OverloadedFunctionDecl::function_iterator& MatchedDecl)
273{
274 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
275 // Is this new function an overload of every function in the
276 // overload set?
277 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
278 FuncEnd = Ovl->function_end();
279 for (; Func != FuncEnd; ++Func) {
280 if (!IsOverload(New, *Func, MatchedDecl)) {
281 MatchedDecl = Func;
282 return false;
283 }
284 }
285
286 // This function overloads every function in the overload set.
287 return true;
288 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
289 // Is the function New an overload of the function Old?
290 QualType OldQType = Context.getCanonicalType(Old->getType());
291 QualType NewQType = Context.getCanonicalType(New->getType());
292
293 // Compare the signatures (C++ 1.3.10) of the two functions to
294 // determine whether they are overloads. If we find any mismatch
295 // in the signature, they are overloads.
296
297 // If either of these functions is a K&R-style function (no
298 // prototype), then we consider them to have matching signatures.
299 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
300 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
301 return false;
302
303 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
304 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
305
306 // The signature of a function includes the types of its
307 // parameters (C++ 1.3.10), which includes the presence or absence
308 // of the ellipsis; see C++ DR 357).
309 if (OldQType != NewQType &&
310 (OldType->getNumArgs() != NewType->getNumArgs() ||
311 OldType->isVariadic() != NewType->isVariadic() ||
312 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
313 NewType->arg_type_begin())))
314 return true;
315
316 // If the function is a class member, its signature includes the
317 // cv-qualifiers (if any) on the function itself.
318 //
319 // As part of this, also check whether one of the member functions
320 // is static, in which case they are not overloads (C++
321 // 13.1p2). While not part of the definition of the signature,
322 // this check is important to determine whether these functions
323 // can be overloaded.
324 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
325 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
326 if (OldMethod && NewMethod &&
327 !OldMethod->isStatic() && !NewMethod->isStatic() &&
328 OldQType.getCVRQualifiers() != NewQType.getCVRQualifiers())
329 return true;
330
331 // The signatures match; this is not an overload.
332 return false;
333 } else {
334 // (C++ 13p1):
335 // Only function declarations can be overloaded; object and type
336 // declarations cannot be overloaded.
337 return false;
338 }
339}
340
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000341/// TryImplicitConversion - Attempt to perform an implicit conversion
342/// from the given expression (Expr) to the given type (ToType). This
343/// function returns an implicit conversion sequence that can be used
344/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000345///
346/// void f(float f);
347/// void g(int i) { f(i); }
348///
349/// this routine would produce an implicit conversion sequence to
350/// describe the initialization of f from i, which will be a standard
351/// conversion sequence containing an lvalue-to-rvalue conversion (C++
352/// 4.1) followed by a floating-integral conversion (C++ 4.9).
353//
354/// Note that this routine only determines how the conversion can be
355/// performed; it does not actually perform the conversion. As such,
356/// it will not produce any diagnostics if no conversion is available,
357/// but will instead return an implicit conversion sequence of kind
358/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000359///
360/// If @p SuppressUserConversions, then user-defined conversions are
361/// not permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000362ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000363Sema::TryImplicitConversion(Expr* From, QualType ToType,
364 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000365{
366 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000367 if (IsStandardConversion(From, ToType, ICS.Standard))
368 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000369 else if (!SuppressUserConversions &&
370 IsUserDefinedConversion(From, ToType, ICS.UserDefined)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000371 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000372 // C++ [over.ics.user]p4:
373 // A conversion of an expression of class type to the same class
374 // type is given Exact Match rank, and a conversion of an
375 // expression of class type to a base class of that type is
376 // given Conversion rank, in spite of the fact that a copy
377 // constructor (i.e., a user-defined conversion function) is
378 // called for those cases.
379 if (CXXConstructorDecl *Constructor
380 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
381 if (Constructor->isCopyConstructor(Context)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000382 // Turn this into a "standard" conversion sequence, so that it
383 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000384 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
385 ICS.Standard.setAsIdentityConversion();
386 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
387 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000388 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000389 if (IsDerivedFrom(From->getType().getUnqualifiedType(),
390 ToType.getUnqualifiedType()))
391 ICS.Standard.Second = ICK_Derived_To_Base;
392 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000393 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000394 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000395 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000396
397 return ICS;
398}
399
400/// IsStandardConversion - Determines whether there is a standard
401/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
402/// expression From to the type ToType. Standard conversion sequences
403/// only consider non-class types; for conversions that involve class
404/// types, use TryImplicitConversion. If a conversion exists, SCS will
405/// contain the standard conversion sequence required to perform this
406/// conversion and this routine will return true. Otherwise, this
407/// routine will return false and the value of SCS is unspecified.
408bool
409Sema::IsStandardConversion(Expr* From, QualType ToType,
410 StandardConversionSequence &SCS)
411{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000412 QualType FromType = From->getType();
413
Douglas Gregor60d62c22008-10-31 16:23:19 +0000414 // There are no standard conversions for class types, so abort early.
415 if (FromType->isRecordType() || ToType->isRecordType())
416 return false;
417
418 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000419 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000420 SCS.Deprecated = false;
421 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000422 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000423
424 // The first conversion can be an lvalue-to-rvalue conversion,
425 // array-to-pointer conversion, or function-to-pointer conversion
426 // (C++ 4p1).
427
428 // Lvalue-to-rvalue conversion (C++ 4.1):
429 // An lvalue (3.10) of a non-function, non-array type T can be
430 // converted to an rvalue.
431 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
432 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000433 !FromType->isFunctionType() && !FromType->isArrayType() &&
434 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000435 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000436
437 // If T is a non-class type, the type of the rvalue is the
438 // cv-unqualified version of T. Otherwise, the type of the rvalue
439 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000440 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000441 }
442 // Array-to-pointer conversion (C++ 4.2)
443 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000444 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000445
446 // An lvalue or rvalue of type "array of N T" or "array of unknown
447 // bound of T" can be converted to an rvalue of type "pointer to
448 // T" (C++ 4.2p1).
449 FromType = Context.getArrayDecayedType(FromType);
450
451 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
452 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000453 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000454
455 // For the purpose of ranking in overload resolution
456 // (13.3.3.1.1), this conversion is considered an
457 // array-to-pointer conversion followed by a qualification
458 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000459 SCS.Second = ICK_Identity;
460 SCS.Third = ICK_Qualification;
461 SCS.ToTypePtr = ToType.getAsOpaquePtr();
462 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000463 }
464 }
465 // Function-to-pointer conversion (C++ 4.3).
466 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000467 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000468
469 // An lvalue of function type T can be converted to an rvalue of
470 // type "pointer to T." The result is a pointer to the
471 // function. (C++ 4.3p1).
472 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000474 // Address of overloaded function (C++ [over.over]).
475 else if (FunctionDecl *Fn
476 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
477 SCS.First = ICK_Function_To_Pointer;
478
479 // We were able to resolve the address of the overloaded function,
480 // so we can convert to the type of that function.
481 FromType = Fn->getType();
482 if (ToType->isReferenceType())
483 FromType = Context.getReferenceType(FromType);
484 else
485 FromType = Context.getPointerType(FromType);
486 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 // We don't require any conversions for the first step.
488 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000489 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490 }
491
492 // The second conversion can be an integral promotion, floating
493 // point promotion, integral conversion, floating point conversion,
494 // floating-integral conversion, pointer conversion,
495 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
496 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
497 Context.getCanonicalType(ToType).getUnqualifiedType()) {
498 // The unqualified versions of the types are the same: there's no
499 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000500 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501 }
502 // Integral promotion (C++ 4.5).
503 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000504 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 FromType = ToType.getUnqualifiedType();
506 }
507 // Floating point promotion (C++ 4.6).
508 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000509 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000510 FromType = ToType.getUnqualifiedType();
511 }
512 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000513 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000515 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000516 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000517 FromType = ToType.getUnqualifiedType();
518 }
519 // Floating point conversions (C++ 4.8).
520 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000521 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000522 FromType = ToType.getUnqualifiedType();
523 }
524 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000525 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000526 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000527 ToType->isIntegralType() && !ToType->isBooleanType() &&
528 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
530 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000531 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000532 FromType = ToType.getUnqualifiedType();
533 }
534 // Pointer conversions (C++ 4.10).
Sebastian Redl07779722008-10-31 14:43:28 +0000535 else if (IsPointerConversion(From, FromType, ToType, FromType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000536 SCS.Second = ICK_Pointer_Conversion;
Sebastian Redl07779722008-10-31 14:43:28 +0000537 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000538 // FIXME: Pointer to member conversions (4.11).
539 // Boolean conversions (C++ 4.12).
540 // FIXME: pointer-to-member type
541 else if (ToType->isBooleanType() &&
542 (FromType->isArithmeticType() ||
543 FromType->isEnumeralType() ||
544 FromType->isPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000545 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000546 FromType = Context.BoolTy;
547 } else {
548 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000549 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000550 }
551
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000552 QualType CanonFrom;
553 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000554 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000555 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000556 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000557 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000558 CanonFrom = Context.getCanonicalType(FromType);
559 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000560 } else {
561 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000562 SCS.Third = ICK_Identity;
563
564 // C++ [over.best.ics]p6:
565 // [...] Any difference in top-level cv-qualification is
566 // subsumed by the initialization itself and does not constitute
567 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000568 CanonFrom = Context.getCanonicalType(FromType);
569 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000570 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000571 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
572 FromType = ToType;
573 CanonFrom = CanonTo;
574 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000575 }
576
577 // If we have not converted the argument type to the parameter type,
578 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000579 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000580 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000581
Douglas Gregor60d62c22008-10-31 16:23:19 +0000582 SCS.ToTypePtr = FromType.getAsOpaquePtr();
583 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000584}
585
586/// IsIntegralPromotion - Determines whether the conversion from the
587/// expression From (whose potentially-adjusted type is FromType) to
588/// ToType is an integral promotion (C++ 4.5). If so, returns true and
589/// sets PromotedType to the promoted type.
590bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
591{
592 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000593 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000594 if (!To) {
595 return false;
596 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000597
598 // An rvalue of type char, signed char, unsigned char, short int, or
599 // unsigned short int can be converted to an rvalue of type int if
600 // int can represent all the values of the source type; otherwise,
601 // the source rvalue can be converted to an rvalue of type unsigned
602 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000603 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604 if (// We can promote any signed, promotable integer type to an int
605 (FromType->isSignedIntegerType() ||
606 // We can promote any unsigned integer type whose size is
607 // less than int to an int.
608 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000609 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000610 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000611 }
612
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000613 return To->getKind() == BuiltinType::UInt;
614 }
615
616 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
617 // can be converted to an rvalue of the first of the following types
618 // that can represent all the values of its underlying type: int,
619 // unsigned int, long, or unsigned long (C++ 4.5p2).
620 if ((FromType->isEnumeralType() || FromType->isWideCharType())
621 && ToType->isIntegerType()) {
622 // Determine whether the type we're converting from is signed or
623 // unsigned.
624 bool FromIsSigned;
625 uint64_t FromSize = Context.getTypeSize(FromType);
626 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
627 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
628 FromIsSigned = UnderlyingType->isSignedIntegerType();
629 } else {
630 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
631 FromIsSigned = true;
632 }
633
634 // The types we'll try to promote to, in the appropriate
635 // order. Try each of these types.
636 QualType PromoteTypes[4] = {
637 Context.IntTy, Context.UnsignedIntTy,
638 Context.LongTy, Context.UnsignedLongTy
639 };
Douglas Gregor447b69e2008-11-19 03:25:36 +0000640 for (int Idx = 0; Idx < 4; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000641 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
642 if (FromSize < ToSize ||
643 (FromSize == ToSize &&
644 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
645 // We found the type that we can promote to. If this is the
646 // type we wanted, we have a promotion. Otherwise, no
647 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000648 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000649 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
650 }
651 }
652 }
653
654 // An rvalue for an integral bit-field (9.6) can be converted to an
655 // rvalue of type int if int can represent all the values of the
656 // bit-field; otherwise, it can be converted to unsigned int if
657 // unsigned int can represent all the values of the bit-field. If
658 // the bit-field is larger yet, no integral promotion applies to
659 // it. If the bit-field has an enumerated type, it is treated as any
660 // other value of that type for promotion purposes (C++ 4.5p3).
661 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
662 using llvm::APSInt;
663 FieldDecl *MemberDecl = MemRef->getMemberDecl();
664 APSInt BitWidth;
665 if (MemberDecl->isBitField() &&
666 FromType->isIntegralType() && !FromType->isEnumeralType() &&
667 From->isIntegerConstantExpr(BitWidth, Context)) {
668 APSInt ToSize(Context.getTypeSize(ToType));
669
670 // Are we promoting to an int from a bitfield that fits in an int?
671 if (BitWidth < ToSize ||
Sebastian Redl07779722008-10-31 14:43:28 +0000672 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000673 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000674 }
675
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000676 // Are we promoting to an unsigned int from an unsigned bitfield
677 // that fits into an unsigned int?
Sebastian Redl07779722008-10-31 14:43:28 +0000678 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000679 return To->getKind() == BuiltinType::UInt;
Sebastian Redl07779722008-10-31 14:43:28 +0000680 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000681
682 return false;
683 }
684 }
685
686 // An rvalue of type bool can be converted to an rvalue of type int,
687 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000688 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000689 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000690 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000691
692 return false;
693}
694
695/// IsFloatingPointPromotion - Determines whether the conversion from
696/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
697/// returns true and sets PromotedType to the promoted type.
698bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
699{
700 /// An rvalue of type float can be converted to an rvalue of type
701 /// double. (C++ 4.6p1).
702 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
703 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
704 if (FromBuiltin->getKind() == BuiltinType::Float &&
705 ToBuiltin->getKind() == BuiltinType::Double)
706 return true;
707
708 return false;
709}
710
711/// IsPointerConversion - Determines whether the conversion of the
712/// expression From, which has the (possibly adjusted) type FromType,
713/// can be converted to the type ToType via a pointer conversion (C++
714/// 4.10). If so, returns true and places the converted type (that
715/// might differ from ToType in its cv-qualifiers at some level) into
716/// ConvertedType.
717bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
718 QualType& ConvertedType)
719{
720 const PointerType* ToTypePtr = ToType->getAsPointerType();
721 if (!ToTypePtr)
722 return false;
723
724 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
725 if (From->isNullPointerConstant(Context)) {
726 ConvertedType = ToType;
727 return true;
728 }
Sebastian Redl07779722008-10-31 14:43:28 +0000729
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000730 // An rvalue of type "pointer to cv T," where T is an object type,
731 // can be converted to an rvalue of type "pointer to cv void" (C++
732 // 4.10p2).
733 if (FromType->isPointerType() &&
734 FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
735 ToTypePtr->getPointeeType()->isVoidType()) {
736 // We need to produce a pointer to cv void, where cv is the same
737 // set of cv-qualifiers as we had on the incoming pointee type.
738 QualType toPointee = ToTypePtr->getPointeeType();
739 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
740 ->getPointeeType().getCVRQualifiers();
741
742 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
743 == Quals) {
744 // ToType is exactly the type we want. Use it.
745 ConvertedType = ToType;
746 } else {
747 // Build a new type with the right qualifiers.
748 ConvertedType
749 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
750 }
751 return true;
752 }
753
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000754 // C++ [conv.ptr]p3:
755 //
756 // An rvalue of type "pointer to cv D," where D is a class type,
757 // can be converted to an rvalue of type "pointer to cv B," where
758 // B is a base class (clause 10) of D. If B is an inaccessible
759 // (clause 11) or ambiguous (10.2) base class of D, a program that
760 // necessitates this conversion is ill-formed. The result of the
761 // conversion is a pointer to the base class sub-object of the
762 // derived class object. The null pointer value is converted to
763 // the null pointer value of the destination type.
764 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000765 // Note that we do not check for ambiguity or inaccessibility
766 // here. That is handled by CheckPointerConversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000767 if (const PointerType *FromPtrType = FromType->getAsPointerType())
768 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
769 if (FromPtrType->getPointeeType()->isRecordType() &&
770 ToPtrType->getPointeeType()->isRecordType() &&
771 IsDerivedFrom(FromPtrType->getPointeeType(),
772 ToPtrType->getPointeeType())) {
773 // The conversion is okay. Now, we need to produce the type
774 // that results from this conversion, which will have the same
775 // qualifiers as the incoming type.
776 QualType CanonFromPointee
777 = Context.getCanonicalType(FromPtrType->getPointeeType());
778 QualType ToPointee = ToPtrType->getPointeeType();
779 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
780 unsigned Quals = CanonFromPointee.getCVRQualifiers();
781
782 if (CanonToPointee.getCVRQualifiers() == Quals) {
783 // ToType is exactly the type we want. Use it.
784 ConvertedType = ToType;
785 } else {
786 // Build a new type with the right qualifiers.
787 ConvertedType
788 = Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
789 }
790 return true;
791 }
792 }
793
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000794 return false;
795}
796
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000797/// CheckPointerConversion - Check the pointer conversion from the
798/// expression From to the type ToType. This routine checks for
799/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
800/// conversions for which IsPointerConversion has already returned
801/// true. It returns true and produces a diagnostic if there was an
802/// error, or returns false otherwise.
803bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
804 QualType FromType = From->getType();
805
806 if (const PointerType *FromPtrType = FromType->getAsPointerType())
807 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl07779722008-10-31 14:43:28 +0000808 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
809 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000810 QualType FromPointeeType = FromPtrType->getPointeeType(),
811 ToPointeeType = ToPtrType->getPointeeType();
812 if (FromPointeeType->isRecordType() &&
813 ToPointeeType->isRecordType()) {
814 // We must have a derived-to-base conversion. Check an
815 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000816 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
817 From->getExprLoc(),
818 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000819 }
820 }
821
822 return false;
823}
824
Douglas Gregor98cd5992008-10-21 23:43:52 +0000825/// IsQualificationConversion - Determines whether the conversion from
826/// an rvalue of type FromType to ToType is a qualification conversion
827/// (C++ 4.4).
828bool
829Sema::IsQualificationConversion(QualType FromType, QualType ToType)
830{
831 FromType = Context.getCanonicalType(FromType);
832 ToType = Context.getCanonicalType(ToType);
833
834 // If FromType and ToType are the same type, this is not a
835 // qualification conversion.
836 if (FromType == ToType)
837 return false;
838
839 // (C++ 4.4p4):
840 // A conversion can add cv-qualifiers at levels other than the first
841 // in multi-level pointers, subject to the following rules: [...]
842 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000843 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +0000844 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +0000845 // Within each iteration of the loop, we check the qualifiers to
846 // determine if this still looks like a qualification
847 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000848 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +0000849 // until there are no more pointers or pointers-to-members left to
850 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +0000851 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000852
853 // -- for every j > 0, if const is in cv 1,j then const is in cv
854 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +0000855 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +0000856 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000857
Douglas Gregor98cd5992008-10-21 23:43:52 +0000858 // -- if the cv 1,j and cv 2,j are different, then const is in
859 // every cv for 0 < k < j.
860 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +0000861 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +0000862 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000863
Douglas Gregor98cd5992008-10-21 23:43:52 +0000864 // Keep track of whether all prior cv-qualifiers in the "to" type
865 // include const.
866 PreviousToQualsIncludeConst
867 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +0000868 }
Douglas Gregor98cd5992008-10-21 23:43:52 +0000869
870 // We are left with FromType and ToType being the pointee types
871 // after unwrapping the original FromType and ToType the same number
872 // of types. If we unwrapped any pointers, and if FromType and
873 // ToType have the same unqualified type (since we checked
874 // qualifiers above), then this is a qualification conversion.
875 return UnwrappedAnyPointer &&
876 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
877}
878
Douglas Gregor60d62c22008-10-31 16:23:19 +0000879/// IsUserDefinedConversion - Determines whether there is a
880/// user-defined conversion sequence (C++ [over.ics.user]) that
881/// converts expression From to the type ToType. If such a conversion
882/// exists, User will contain the user-defined conversion sequence
883/// that performs such a conversion and this routine will return
884/// true. Otherwise, this routine returns false and User is
885/// unspecified.
886bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
887 UserDefinedConversionSequence& User)
888{
889 OverloadCandidateSet CandidateSet;
890 if (const CXXRecordType *ToRecordType
891 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
892 // C++ [over.match.ctor]p1:
893 // When objects of class type are direct-initialized (8.5), or
894 // copy-initialized from an expression of the same or a
895 // derived class type (8.5), overload resolution selects the
896 // constructor. [...] For copy-initialization, the candidate
897 // functions are all the converting constructors (12.3.1) of
898 // that class. The argument list is the expression-list within
899 // the parentheses of the initializer.
900 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
901 const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors();
902 for (OverloadedFunctionDecl::function_const_iterator func
903 = Constructors->function_begin();
904 func != Constructors->function_end(); ++func) {
905 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
906 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +0000907 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
908 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000909 }
910 }
911
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000912 if (const CXXRecordType *FromRecordType
913 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
914 // Add all of the conversion functions as candidates.
915 // FIXME: Look for conversions in base classes!
916 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
917 OverloadedFunctionDecl *Conversions
918 = FromRecordDecl->getConversionFunctions();
919 for (OverloadedFunctionDecl::function_iterator Func
920 = Conversions->function_begin();
921 Func != Conversions->function_end(); ++Func) {
922 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
923 AddConversionCandidate(Conv, From, ToType, CandidateSet);
924 }
925 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000926
927 OverloadCandidateSet::iterator Best;
928 switch (BestViableFunction(CandidateSet, Best)) {
929 case OR_Success:
930 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000931 if (CXXConstructorDecl *Constructor
932 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
933 // C++ [over.ics.user]p1:
934 // If the user-defined conversion is specified by a
935 // constructor (12.3.1), the initial standard conversion
936 // sequence converts the source type to the type required by
937 // the argument of the constructor.
938 //
939 // FIXME: What about ellipsis conversions?
940 QualType ThisType = Constructor->getThisType(Context);
941 User.Before = Best->Conversions[0].Standard;
942 User.ConversionFunction = Constructor;
943 User.After.setAsIdentityConversion();
944 User.After.FromTypePtr
945 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
946 User.After.ToTypePtr = ToType.getAsOpaquePtr();
947 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000948 } else if (CXXConversionDecl *Conversion
949 = dyn_cast<CXXConversionDecl>(Best->Function)) {
950 // C++ [over.ics.user]p1:
951 //
952 // [...] If the user-defined conversion is specified by a
953 // conversion function (12.3.2), the initial standard
954 // conversion sequence converts the source type to the
955 // implicit object parameter of the conversion function.
956 User.Before = Best->Conversions[0].Standard;
957 User.ConversionFunction = Conversion;
958
959 // C++ [over.ics.user]p2:
960 // The second standard conversion sequence converts the
961 // result of the user-defined conversion to the target type
962 // for the sequence. Since an implicit conversion sequence
963 // is an initialization, the special rules for
964 // initialization by user-defined conversion apply when
965 // selecting the best user-defined conversion for a
966 // user-defined conversion sequence (see 13.3.3 and
967 // 13.3.3.1).
968 User.After = Best->FinalConversion;
969 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000970 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000971 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000972 return false;
973 }
974
975 case OR_No_Viable_Function:
976 // No conversion here! We're done.
977 return false;
978
979 case OR_Ambiguous:
980 // FIXME: See C++ [over.best.ics]p10 for the handling of
981 // ambiguous conversion sequences.
982 return false;
983 }
984
985 return false;
986}
987
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000988/// CompareImplicitConversionSequences - Compare two implicit
989/// conversion sequences to determine whether one is better than the
990/// other or if they are indistinguishable (C++ 13.3.3.2).
991ImplicitConversionSequence::CompareKind
992Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
993 const ImplicitConversionSequence& ICS2)
994{
995 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
996 // conversion sequences (as defined in 13.3.3.1)
997 // -- a standard conversion sequence (13.3.3.1.1) is a better
998 // conversion sequence than a user-defined conversion sequence or
999 // an ellipsis conversion sequence, and
1000 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1001 // conversion sequence than an ellipsis conversion sequence
1002 // (13.3.3.1.3).
1003 //
1004 if (ICS1.ConversionKind < ICS2.ConversionKind)
1005 return ImplicitConversionSequence::Better;
1006 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1007 return ImplicitConversionSequence::Worse;
1008
1009 // Two implicit conversion sequences of the same form are
1010 // indistinguishable conversion sequences unless one of the
1011 // following rules apply: (C++ 13.3.3.2p3):
1012 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1013 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1014 else if (ICS1.ConversionKind ==
1015 ImplicitConversionSequence::UserDefinedConversion) {
1016 // User-defined conversion sequence U1 is a better conversion
1017 // sequence than another user-defined conversion sequence U2 if
1018 // they contain the same user-defined conversion function or
1019 // constructor and if the second standard conversion sequence of
1020 // U1 is better than the second standard conversion sequence of
1021 // U2 (C++ 13.3.3.2p3).
1022 if (ICS1.UserDefined.ConversionFunction ==
1023 ICS2.UserDefined.ConversionFunction)
1024 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1025 ICS2.UserDefined.After);
1026 }
1027
1028 return ImplicitConversionSequence::Indistinguishable;
1029}
1030
1031/// CompareStandardConversionSequences - Compare two standard
1032/// conversion sequences to determine whether one is better than the
1033/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1034ImplicitConversionSequence::CompareKind
1035Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1036 const StandardConversionSequence& SCS2)
1037{
1038 // Standard conversion sequence S1 is a better conversion sequence
1039 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1040
1041 // -- S1 is a proper subsequence of S2 (comparing the conversion
1042 // sequences in the canonical form defined by 13.3.3.1.1,
1043 // excluding any Lvalue Transformation; the identity conversion
1044 // sequence is considered to be a subsequence of any
1045 // non-identity conversion sequence) or, if not that,
1046 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1047 // Neither is a proper subsequence of the other. Do nothing.
1048 ;
1049 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1050 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1051 (SCS1.Second == ICK_Identity &&
1052 SCS1.Third == ICK_Identity))
1053 // SCS1 is a proper subsequence of SCS2.
1054 return ImplicitConversionSequence::Better;
1055 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1056 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1057 (SCS2.Second == ICK_Identity &&
1058 SCS2.Third == ICK_Identity))
1059 // SCS2 is a proper subsequence of SCS1.
1060 return ImplicitConversionSequence::Worse;
1061
1062 // -- the rank of S1 is better than the rank of S2 (by the rules
1063 // defined below), or, if not that,
1064 ImplicitConversionRank Rank1 = SCS1.getRank();
1065 ImplicitConversionRank Rank2 = SCS2.getRank();
1066 if (Rank1 < Rank2)
1067 return ImplicitConversionSequence::Better;
1068 else if (Rank2 < Rank1)
1069 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001070
Douglas Gregor57373262008-10-22 14:17:15 +00001071 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1072 // are indistinguishable unless one of the following rules
1073 // applies:
1074
1075 // A conversion that is not a conversion of a pointer, or
1076 // pointer to member, to bool is better than another conversion
1077 // that is such a conversion.
1078 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1079 return SCS2.isPointerConversionToBool()
1080 ? ImplicitConversionSequence::Better
1081 : ImplicitConversionSequence::Worse;
1082
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001083 // C++ [over.ics.rank]p4b2:
1084 //
1085 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001086 // conversion of B* to A* is better than conversion of B* to
1087 // void*, and conversion of A* to void* is better than conversion
1088 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001089 bool SCS1ConvertsToVoid
1090 = SCS1.isPointerConversionToVoidPointer(Context);
1091 bool SCS2ConvertsToVoid
1092 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001093 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1094 // Exactly one of the conversion sequences is a conversion to
1095 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001096 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1097 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001098 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1099 // Neither conversion sequence converts to a void pointer; compare
1100 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001101 if (ImplicitConversionSequence::CompareKind DerivedCK
1102 = CompareDerivedToBaseConversions(SCS1, SCS2))
1103 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001104 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1105 // Both conversion sequences are conversions to void
1106 // pointers. Compare the source types to determine if there's an
1107 // inheritance relationship in their sources.
1108 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1109 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1110
1111 // Adjust the types we're converting from via the array-to-pointer
1112 // conversion, if we need to.
1113 if (SCS1.First == ICK_Array_To_Pointer)
1114 FromType1 = Context.getArrayDecayedType(FromType1);
1115 if (SCS2.First == ICK_Array_To_Pointer)
1116 FromType2 = Context.getArrayDecayedType(FromType2);
1117
1118 QualType FromPointee1
1119 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1120 QualType FromPointee2
1121 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1122
1123 if (IsDerivedFrom(FromPointee2, FromPointee1))
1124 return ImplicitConversionSequence::Better;
1125 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1126 return ImplicitConversionSequence::Worse;
1127 }
Douglas Gregor57373262008-10-22 14:17:15 +00001128
1129 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1130 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001131 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001132 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001133 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001134
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001135 // C++ [over.ics.rank]p3b4:
1136 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1137 // which the references refer are the same type except for
1138 // top-level cv-qualifiers, and the type to which the reference
1139 // initialized by S2 refers is more cv-qualified than the type
1140 // to which the reference initialized by S1 refers.
1141 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1142 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1143 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1144 T1 = Context.getCanonicalType(T1);
1145 T2 = Context.getCanonicalType(T2);
1146 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1147 if (T2.isMoreQualifiedThan(T1))
1148 return ImplicitConversionSequence::Better;
1149 else if (T1.isMoreQualifiedThan(T2))
1150 return ImplicitConversionSequence::Worse;
1151 }
1152 }
Douglas Gregor57373262008-10-22 14:17:15 +00001153
1154 return ImplicitConversionSequence::Indistinguishable;
1155}
1156
1157/// CompareQualificationConversions - Compares two standard conversion
1158/// sequences to determine whether they can be ranked based on their
1159/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1160ImplicitConversionSequence::CompareKind
1161Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1162 const StandardConversionSequence& SCS2)
1163{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001164 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001165 // -- S1 and S2 differ only in their qualification conversion and
1166 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1167 // cv-qualification signature of type T1 is a proper subset of
1168 // the cv-qualification signature of type T2, and S1 is not the
1169 // deprecated string literal array-to-pointer conversion (4.2).
1170 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1171 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1172 return ImplicitConversionSequence::Indistinguishable;
1173
1174 // FIXME: the example in the standard doesn't use a qualification
1175 // conversion (!)
1176 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1177 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1178 T1 = Context.getCanonicalType(T1);
1179 T2 = Context.getCanonicalType(T2);
1180
1181 // If the types are the same, we won't learn anything by unwrapped
1182 // them.
1183 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1184 return ImplicitConversionSequence::Indistinguishable;
1185
1186 ImplicitConversionSequence::CompareKind Result
1187 = ImplicitConversionSequence::Indistinguishable;
1188 while (UnwrapSimilarPointerTypes(T1, T2)) {
1189 // Within each iteration of the loop, we check the qualifiers to
1190 // determine if this still looks like a qualification
1191 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001192 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001193 // until there are no more pointers or pointers-to-members left
1194 // to unwrap. This essentially mimics what
1195 // IsQualificationConversion does, but here we're checking for a
1196 // strict subset of qualifiers.
1197 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1198 // The qualifiers are the same, so this doesn't tell us anything
1199 // about how the sequences rank.
1200 ;
1201 else if (T2.isMoreQualifiedThan(T1)) {
1202 // T1 has fewer qualifiers, so it could be the better sequence.
1203 if (Result == ImplicitConversionSequence::Worse)
1204 // Neither has qualifiers that are a subset of the other's
1205 // qualifiers.
1206 return ImplicitConversionSequence::Indistinguishable;
1207
1208 Result = ImplicitConversionSequence::Better;
1209 } else if (T1.isMoreQualifiedThan(T2)) {
1210 // T2 has fewer qualifiers, so it could be the better sequence.
1211 if (Result == ImplicitConversionSequence::Better)
1212 // Neither has qualifiers that are a subset of the other's
1213 // qualifiers.
1214 return ImplicitConversionSequence::Indistinguishable;
1215
1216 Result = ImplicitConversionSequence::Worse;
1217 } else {
1218 // Qualifiers are disjoint.
1219 return ImplicitConversionSequence::Indistinguishable;
1220 }
1221
1222 // If the types after this point are equivalent, we're done.
1223 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1224 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001225 }
1226
Douglas Gregor57373262008-10-22 14:17:15 +00001227 // Check that the winning standard conversion sequence isn't using
1228 // the deprecated string literal array to pointer conversion.
1229 switch (Result) {
1230 case ImplicitConversionSequence::Better:
1231 if (SCS1.Deprecated)
1232 Result = ImplicitConversionSequence::Indistinguishable;
1233 break;
1234
1235 case ImplicitConversionSequence::Indistinguishable:
1236 break;
1237
1238 case ImplicitConversionSequence::Worse:
1239 if (SCS2.Deprecated)
1240 Result = ImplicitConversionSequence::Indistinguishable;
1241 break;
1242 }
1243
1244 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001245}
1246
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001247/// CompareDerivedToBaseConversions - Compares two standard conversion
1248/// sequences to determine whether they can be ranked based on their
1249/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3).
1250ImplicitConversionSequence::CompareKind
1251Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1252 const StandardConversionSequence& SCS2) {
1253 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1254 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1255 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1256 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1257
1258 // Adjust the types we're converting from via the array-to-pointer
1259 // conversion, if we need to.
1260 if (SCS1.First == ICK_Array_To_Pointer)
1261 FromType1 = Context.getArrayDecayedType(FromType1);
1262 if (SCS2.First == ICK_Array_To_Pointer)
1263 FromType2 = Context.getArrayDecayedType(FromType2);
1264
1265 // Canonicalize all of the types.
1266 FromType1 = Context.getCanonicalType(FromType1);
1267 ToType1 = Context.getCanonicalType(ToType1);
1268 FromType2 = Context.getCanonicalType(FromType2);
1269 ToType2 = Context.getCanonicalType(ToType2);
1270
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001271 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001272 //
1273 // If class B is derived directly or indirectly from class A and
1274 // class C is derived directly or indirectly from B,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001275
1276 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001277 if (SCS1.Second == ICK_Pointer_Conversion &&
1278 SCS2.Second == ICK_Pointer_Conversion) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001279 QualType FromPointee1
1280 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1281 QualType ToPointee1
1282 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1283 QualType FromPointee2
1284 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1285 QualType ToPointee2
1286 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001287 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001288 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1289 if (IsDerivedFrom(ToPointee1, ToPointee2))
1290 return ImplicitConversionSequence::Better;
1291 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1292 return ImplicitConversionSequence::Worse;
1293 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001294
1295 // -- conversion of B* to A* is better than conversion of C* to A*,
1296 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1297 if (IsDerivedFrom(FromPointee2, FromPointee1))
1298 return ImplicitConversionSequence::Better;
1299 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1300 return ImplicitConversionSequence::Worse;
1301 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001302 }
1303
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001304 // Compare based on reference bindings.
1305 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1306 SCS1.Second == ICK_Derived_To_Base) {
1307 // -- binding of an expression of type C to a reference of type
1308 // B& is better than binding an expression of type C to a
1309 // reference of type A&,
1310 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1311 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1312 if (IsDerivedFrom(ToType1, ToType2))
1313 return ImplicitConversionSequence::Better;
1314 else if (IsDerivedFrom(ToType2, ToType1))
1315 return ImplicitConversionSequence::Worse;
1316 }
1317
Douglas Gregor225c41e2008-11-03 19:09:14 +00001318 // -- binding of an expression of type B to a reference of type
1319 // A& is better than binding an expression of type C to a
1320 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001321 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1322 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1323 if (IsDerivedFrom(FromType2, FromType1))
1324 return ImplicitConversionSequence::Better;
1325 else if (IsDerivedFrom(FromType1, FromType2))
1326 return ImplicitConversionSequence::Worse;
1327 }
1328 }
1329
1330
1331 // FIXME: conversion of A::* to B::* is better than conversion of
1332 // A::* to C::*,
1333
1334 // FIXME: conversion of B::* to C::* is better than conversion of
1335 // A::* to C::*, and
1336
Douglas Gregor225c41e2008-11-03 19:09:14 +00001337 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1338 SCS1.Second == ICK_Derived_To_Base) {
1339 // -- conversion of C to B is better than conversion of C to A,
1340 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1341 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1342 if (IsDerivedFrom(ToType1, ToType2))
1343 return ImplicitConversionSequence::Better;
1344 else if (IsDerivedFrom(ToType2, ToType1))
1345 return ImplicitConversionSequence::Worse;
1346 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001347
Douglas Gregor225c41e2008-11-03 19:09:14 +00001348 // -- conversion of B to A is better than conversion of C to A.
1349 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1350 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1351 if (IsDerivedFrom(FromType2, FromType1))
1352 return ImplicitConversionSequence::Better;
1353 else if (IsDerivedFrom(FromType1, FromType2))
1354 return ImplicitConversionSequence::Worse;
1355 }
1356 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001357
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001358 return ImplicitConversionSequence::Indistinguishable;
1359}
1360
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001361/// TryCopyInitialization - Try to copy-initialize a value of type
1362/// ToType from the expression From. Return the implicit conversion
1363/// sequence required to pass this argument, which may be a bad
1364/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001365/// a parameter of this type). If @p SuppressUserConversions, then we
1366/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001367ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001368Sema::TryCopyInitialization(Expr *From, QualType ToType,
1369 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001370 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001371 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001372 AssignConvertType ConvTy =
1373 CheckSingleAssignmentConstraints(ToType, From);
1374 ImplicitConversionSequence ICS;
1375 if (getLangOptions().NoExtensions? ConvTy != Compatible
1376 : ConvTy == Incompatible)
1377 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1378 else
1379 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1380 return ICS;
1381 } else if (ToType->isReferenceType()) {
1382 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001383 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001384 return ICS;
1385 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001386 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001387 }
1388}
1389
1390/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1391/// type ToType. Returns true (and emits a diagnostic) if there was
1392/// an error, returns false if the initialization succeeded.
1393bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1394 const char* Flavor) {
1395 if (!getLangOptions().CPlusPlus) {
1396 // In C, argument passing is the same as performing an assignment.
1397 QualType FromType = From->getType();
1398 AssignConvertType ConvTy =
1399 CheckSingleAssignmentConstraints(ToType, From);
1400
1401 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1402 FromType, From, Flavor);
1403 } else if (ToType->isReferenceType()) {
1404 return CheckReferenceInit(From, ToType);
1405 } else {
1406 if (PerformImplicitConversion(From, ToType))
1407 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001408 diag::err_typecheck_convert_incompatible)
1409 << ToType.getAsString() << From->getType().getAsString()
1410 << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001411 else
1412 return false;
1413 }
1414}
1415
Douglas Gregor96176b32008-11-18 23:14:02 +00001416/// TryObjectArgumentInitialization - Try to initialize the object
1417/// parameter of the given member function (@c Method) from the
1418/// expression @p From.
1419ImplicitConversionSequence
1420Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1421 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1422 unsigned MethodQuals = Method->getTypeQualifiers();
1423 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1424
1425 // Set up the conversion sequence as a "bad" conversion, to allow us
1426 // to exit early.
1427 ImplicitConversionSequence ICS;
1428 ICS.Standard.setAsIdentityConversion();
1429 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1430
1431 // We need to have an object of class type.
1432 QualType FromType = From->getType();
1433 if (!FromType->isRecordType())
1434 return ICS;
1435
1436 // The implicit object parmeter is has the type "reference to cv X",
1437 // where X is the class of which the function is a member
1438 // (C++ [over.match.funcs]p4). However, when finding an implicit
1439 // conversion sequence for the argument, we are not allowed to
1440 // create temporaries or perform user-defined conversions
1441 // (C++ [over.match.funcs]p5). We perform a simplified version of
1442 // reference binding here, that allows class rvalues to bind to
1443 // non-constant references.
1444
1445 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1446 // with the implicit object parameter (C++ [over.match.funcs]p5).
1447 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1448 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1449 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1450 return ICS;
1451
1452 // Check that we have either the same type or a derived type. It
1453 // affects the conversion rank.
1454 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1455 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1456 ICS.Standard.Second = ICK_Identity;
1457 else if (IsDerivedFrom(FromType, ClassType))
1458 ICS.Standard.Second = ICK_Derived_To_Base;
1459 else
1460 return ICS;
1461
1462 // Success. Mark this as a reference binding.
1463 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1464 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1465 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1466 ICS.Standard.ReferenceBinding = true;
1467 ICS.Standard.DirectBinding = true;
1468 return ICS;
1469}
1470
1471/// PerformObjectArgumentInitialization - Perform initialization of
1472/// the implicit object parameter for the given Method with the given
1473/// expression.
1474bool
1475Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1476 QualType ImplicitParamType
1477 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1478 ImplicitConversionSequence ICS
1479 = TryObjectArgumentInitialization(From, Method);
1480 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1481 return Diag(From->getSourceRange().getBegin(),
1482 diag::err_implicit_object_parameter_init,
1483 ImplicitParamType.getAsString(), From->getType().getAsString(),
1484 From->getSourceRange());
1485
1486 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1487 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1488 From->getSourceRange().getBegin(),
1489 From->getSourceRange()))
1490 return true;
1491
1492 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1493 return false;
1494}
1495
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001496/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001497/// candidate functions, using the given function call arguments. If
1498/// @p SuppressUserConversions, then don't allow user-defined
1499/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001500void
1501Sema::AddOverloadCandidate(FunctionDecl *Function,
1502 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001503 OverloadCandidateSet& CandidateSet,
1504 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001505{
1506 const FunctionTypeProto* Proto
1507 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1508 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001509 assert(!isa<CXXConversionDecl>(Function) &&
1510 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001511
1512 // Add this candidate
1513 CandidateSet.push_back(OverloadCandidate());
1514 OverloadCandidate& Candidate = CandidateSet.back();
1515 Candidate.Function = Function;
1516
1517 unsigned NumArgsInProto = Proto->getNumArgs();
1518
1519 // (C++ 13.3.2p2): A candidate function having fewer than m
1520 // parameters is viable only if it has an ellipsis in its parameter
1521 // list (8.3.5).
1522 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1523 Candidate.Viable = false;
1524 return;
1525 }
1526
1527 // (C++ 13.3.2p2): A candidate function having more than m parameters
1528 // is viable only if the (m+1)st parameter has a default argument
1529 // (8.3.6). For the purposes of overload resolution, the
1530 // parameter list is truncated on the right, so that there are
1531 // exactly m parameters.
1532 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1533 if (NumArgs < MinRequiredArgs) {
1534 // Not enough arguments.
1535 Candidate.Viable = false;
1536 return;
1537 }
1538
1539 // Determine the implicit conversion sequences for each of the
1540 // arguments.
1541 Candidate.Viable = true;
1542 Candidate.Conversions.resize(NumArgs);
1543 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1544 if (ArgIdx < NumArgsInProto) {
1545 // (C++ 13.3.2p3): for F to be a viable function, there shall
1546 // exist for each argument an implicit conversion sequence
1547 // (13.3.3.1) that converts that argument to the corresponding
1548 // parameter of F.
1549 QualType ParamType = Proto->getArgType(ArgIdx);
1550 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001551 = TryCopyInitialization(Args[ArgIdx], ParamType,
1552 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001554 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001555 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001556 break;
1557 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001558 } else {
1559 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1560 // argument for which there is no corresponding parameter is
1561 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1562 Candidate.Conversions[ArgIdx].ConversionKind
1563 = ImplicitConversionSequence::EllipsisConversion;
1564 }
1565 }
1566}
1567
Douglas Gregor96176b32008-11-18 23:14:02 +00001568/// AddMethodCandidate - Adds the given C++ member function to the set
1569/// of candidate functions, using the given function call arguments
1570/// and the object argument (@c Object). For example, in a call
1571/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1572/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1573/// allow user-defined conversions via constructors or conversion
1574/// operators.
1575void
1576Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1577 Expr **Args, unsigned NumArgs,
1578 OverloadCandidateSet& CandidateSet,
1579 bool SuppressUserConversions)
1580{
1581 const FunctionTypeProto* Proto
1582 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1583 assert(Proto && "Methods without a prototype cannot be overloaded");
1584 assert(!isa<CXXConversionDecl>(Method) &&
1585 "Use AddConversionCandidate for conversion functions");
1586
1587 // Add this candidate
1588 CandidateSet.push_back(OverloadCandidate());
1589 OverloadCandidate& Candidate = CandidateSet.back();
1590 Candidate.Function = Method;
1591
1592 unsigned NumArgsInProto = Proto->getNumArgs();
1593
1594 // (C++ 13.3.2p2): A candidate function having fewer than m
1595 // parameters is viable only if it has an ellipsis in its parameter
1596 // list (8.3.5).
1597 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1598 Candidate.Viable = false;
1599 return;
1600 }
1601
1602 // (C++ 13.3.2p2): A candidate function having more than m parameters
1603 // is viable only if the (m+1)st parameter has a default argument
1604 // (8.3.6). For the purposes of overload resolution, the
1605 // parameter list is truncated on the right, so that there are
1606 // exactly m parameters.
1607 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1608 if (NumArgs < MinRequiredArgs) {
1609 // Not enough arguments.
1610 Candidate.Viable = false;
1611 return;
1612 }
1613
1614 Candidate.Viable = true;
1615 Candidate.Conversions.resize(NumArgs + 1);
1616
1617 // Determine the implicit conversion sequence for the object
1618 // parameter.
1619 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1620 if (Candidate.Conversions[0].ConversionKind
1621 == ImplicitConversionSequence::BadConversion) {
1622 Candidate.Viable = false;
1623 return;
1624 }
1625
1626 // Determine the implicit conversion sequences for each of the
1627 // arguments.
1628 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1629 if (ArgIdx < NumArgsInProto) {
1630 // (C++ 13.3.2p3): for F to be a viable function, there shall
1631 // exist for each argument an implicit conversion sequence
1632 // (13.3.3.1) that converts that argument to the corresponding
1633 // parameter of F.
1634 QualType ParamType = Proto->getArgType(ArgIdx);
1635 Candidate.Conversions[ArgIdx + 1]
1636 = TryCopyInitialization(Args[ArgIdx], ParamType,
1637 SuppressUserConversions);
1638 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1639 == ImplicitConversionSequence::BadConversion) {
1640 Candidate.Viable = false;
1641 break;
1642 }
1643 } else {
1644 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1645 // argument for which there is no corresponding parameter is
1646 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1647 Candidate.Conversions[ArgIdx + 1].ConversionKind
1648 = ImplicitConversionSequence::EllipsisConversion;
1649 }
1650 }
1651}
1652
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001653/// AddConversionCandidate - Add a C++ conversion function as a
1654/// candidate in the candidate set (C++ [over.match.conv],
1655/// C++ [over.match.copy]). From is the expression we're converting from,
1656/// and ToType is the type that we're eventually trying to convert to
1657/// (which may or may not be the same type as the type that the
1658/// conversion function produces).
1659void
1660Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1661 Expr *From, QualType ToType,
1662 OverloadCandidateSet& CandidateSet) {
1663 // Add this candidate
1664 CandidateSet.push_back(OverloadCandidate());
1665 OverloadCandidate& Candidate = CandidateSet.back();
1666 Candidate.Function = Conversion;
1667 Candidate.FinalConversion.setAsIdentityConversion();
1668 Candidate.FinalConversion.FromTypePtr
1669 = Conversion->getConversionType().getAsOpaquePtr();
1670 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1671
Douglas Gregor96176b32008-11-18 23:14:02 +00001672 // Determine the implicit conversion sequence for the implicit
1673 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001674 Candidate.Viable = true;
1675 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00001676 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001677
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001678 if (Candidate.Conversions[0].ConversionKind
1679 == ImplicitConversionSequence::BadConversion) {
1680 Candidate.Viable = false;
1681 return;
1682 }
1683
1684 // To determine what the conversion from the result of calling the
1685 // conversion function to the type we're eventually trying to
1686 // convert to (ToType), we need to synthesize a call to the
1687 // conversion function and attempt copy initialization from it. This
1688 // makes sure that we get the right semantics with respect to
1689 // lvalues/rvalues and the type. Fortunately, we can allocate this
1690 // call on the stack and we don't need its arguments to be
1691 // well-formed.
1692 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1693 SourceLocation());
1694 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001695 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001696 CallExpr Call(&ConversionFn, 0, 0,
1697 Conversion->getConversionType().getNonReferenceType(),
1698 SourceLocation());
1699 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1700 switch (ICS.ConversionKind) {
1701 case ImplicitConversionSequence::StandardConversion:
1702 Candidate.FinalConversion = ICS.Standard;
1703 break;
1704
1705 case ImplicitConversionSequence::BadConversion:
1706 Candidate.Viable = false;
1707 break;
1708
1709 default:
1710 assert(false &&
1711 "Can only end up with a standard conversion sequence or failure");
1712 }
1713}
1714
Douglas Gregor447b69e2008-11-19 03:25:36 +00001715/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1716/// an acceptable non-member overloaded operator for a call whose
1717/// arguments have types T1 (and, if non-empty, T2). This routine
1718/// implements the check in C++ [over.match.oper]p3b2 concerning
1719/// enumeration types.
1720static bool
1721IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1722 QualType T1, QualType T2,
1723 ASTContext &Context) {
1724 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1725 return true;
1726
1727 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
1728 if (Proto->getNumArgs() < 1)
1729 return false;
1730
1731 if (T1->isEnumeralType()) {
1732 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1733 if (Context.getCanonicalType(T1).getUnqualifiedType()
1734 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1735 return true;
1736 }
1737
1738 if (Proto->getNumArgs() < 2)
1739 return false;
1740
1741 if (!T2.isNull() && T2->isEnumeralType()) {
1742 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1743 if (Context.getCanonicalType(T2).getUnqualifiedType()
1744 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1745 return true;
1746 }
1747
1748 return false;
1749}
1750
Douglas Gregor96176b32008-11-18 23:14:02 +00001751/// AddOperatorCandidates - Add the overloaded operator candidates for
1752/// the operator Op that was used in an operator expression such as "x
1753/// Op y". S is the scope in which the expression occurred (used for
1754/// name lookup of the operator), Args/NumArgs provides the operator
1755/// arguments, and CandidateSet will store the added overload
1756/// candidates. (C++ [over.match.oper]).
1757void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
1758 Expr **Args, unsigned NumArgs,
1759 OverloadCandidateSet& CandidateSet) {
1760 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1761
1762 // C++ [over.match.oper]p3:
1763 // For a unary operator @ with an operand of a type whose
1764 // cv-unqualified version is T1, and for a binary operator @ with
1765 // a left operand of a type whose cv-unqualified version is T1 and
1766 // a right operand of a type whose cv-unqualified version is T2,
1767 // three sets of candidate functions, designated member
1768 // candidates, non-member candidates and built-in candidates, are
1769 // constructed as follows:
1770 QualType T1 = Args[0]->getType();
1771 QualType T2;
1772 if (NumArgs > 1)
1773 T2 = Args[1]->getType();
1774
1775 // -- If T1 is a class type, the set of member candidates is the
1776 // result of the qualified lookup of T1::operator@
1777 // (13.3.1.1.1); otherwise, the set of member candidates is
1778 // empty.
1779 if (const RecordType *T1Rec = T1->getAsRecordType()) {
1780 IdentifierResolver::iterator I
1781 = IdResolver.begin(OpName, cast<CXXRecordType>(T1Rec)->getDecl(),
1782 /*LookInParentCtx=*/false);
1783 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
1784 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
1785 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1786 /*SuppressUserConversions=*/false);
1787 else if (OverloadedFunctionDecl *Ovl
1788 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
1789 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1790 FEnd = Ovl->function_end();
1791 F != FEnd; ++F) {
1792 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
1793 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1794 /*SuppressUserConversions=*/false);
1795 }
1796 }
1797 }
1798
1799 // -- The set of non-member candidates is the result of the
1800 // unqualified lookup of operator@ in the context of the
1801 // expression according to the usual rules for name lookup in
1802 // unqualified function calls (3.4.2) except that all member
1803 // functions are ignored. However, if no operand has a class
1804 // type, only those non-member functions in the lookup set
1805 // that have a first parameter of type T1 or “reference to
1806 // (possibly cv-qualified) T1”, when T1 is an enumeration
1807 // type, or (if there is a right operand) a second parameter
1808 // of type T2 or “reference to (possibly cv-qualified) T2”,
1809 // when T2 is an enumeration type, are candidate functions.
1810 {
1811 NamedDecl *NonMemberOps = 0;
1812 for (IdentifierResolver::iterator I
1813 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
1814 I != IdResolver.end(); ++I) {
1815 // We don't need to check the identifier namespace, because
1816 // operator names can only be ordinary identifiers.
1817
1818 // Ignore member functions.
1819 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
1820 if (SD->getDeclContext()->isCXXRecord())
1821 continue;
1822 }
1823
1824 // We found something with this name. We're done.
1825 NonMemberOps = *I;
1826 break;
1827 }
1828
Douglas Gregor447b69e2008-11-19 03:25:36 +00001829 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) {
1830 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1831 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
1832 /*SuppressUserConversions=*/false);
1833 } else if (OverloadedFunctionDecl *Ovl
1834 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
Douglas Gregor96176b32008-11-18 23:14:02 +00001835 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1836 FEnd = Ovl->function_end();
Douglas Gregor447b69e2008-11-19 03:25:36 +00001837 F != FEnd; ++F) {
1838 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context))
1839 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
1840 /*SuppressUserConversions=*/false);
1841 }
Douglas Gregor96176b32008-11-18 23:14:02 +00001842 }
1843 }
1844
1845 // Add builtin overload candidates (C++ [over.built]).
1846 if (NumArgs == 2)
1847 return AddBuiltinBinaryOperatorCandidates(Op, Args, CandidateSet);
1848}
1849
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001850/// AddBuiltinCandidate - Add a candidate for a built-in
1851/// operator. ResultTy and ParamTys are the result and parameter types
1852/// of the built-in candidate, respectively. Args and NumArgs are the
1853/// arguments being passed to the candidate.
1854void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1855 Expr **Args, unsigned NumArgs,
1856 OverloadCandidateSet& CandidateSet) {
1857 // Add this candidate
1858 CandidateSet.push_back(OverloadCandidate());
1859 OverloadCandidate& Candidate = CandidateSet.back();
1860 Candidate.Function = 0;
1861 Candidate.BuiltinTypes.ResultTy = ResultTy;
1862 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
1863 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
1864
1865 // Determine the implicit conversion sequences for each of the
1866 // arguments.
1867 Candidate.Viable = true;
1868 Candidate.Conversions.resize(NumArgs);
1869 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1870 Candidate.Conversions[ArgIdx]
1871 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
1872 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001873 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001874 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001875 break;
1876 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001877 }
1878}
1879
1880/// BuiltinCandidateTypeSet - A set of types that will be used for the
1881/// candidate operator functions for built-in operators (C++
1882/// [over.built]). The types are separated into pointer types and
1883/// enumeration types.
1884class BuiltinCandidateTypeSet {
1885 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001886 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001887
1888 /// PointerTypes - The set of pointer types that will be used in the
1889 /// built-in candidates.
1890 TypeSet PointerTypes;
1891
1892 /// EnumerationTypes - The set of enumeration types that will be
1893 /// used in the built-in candidates.
1894 TypeSet EnumerationTypes;
1895
1896 /// Context - The AST context in which we will build the type sets.
1897 ASTContext &Context;
1898
1899 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
1900
1901public:
1902 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001903 class iterator {
1904 TypeSet::iterator Base;
1905
1906 public:
1907 typedef QualType value_type;
1908 typedef QualType reference;
1909 typedef QualType pointer;
1910 typedef std::ptrdiff_t difference_type;
1911 typedef std::input_iterator_tag iterator_category;
1912
1913 iterator(TypeSet::iterator B) : Base(B) { }
1914
1915 iterator& operator++() {
1916 ++Base;
1917 return *this;
1918 }
1919
1920 iterator operator++(int) {
1921 iterator tmp(*this);
1922 ++(*this);
1923 return tmp;
1924 }
1925
1926 reference operator*() const {
1927 return QualType::getFromOpaquePtr(*Base);
1928 }
1929
1930 pointer operator->() const {
1931 return **this;
1932 }
1933
1934 friend bool operator==(iterator LHS, iterator RHS) {
1935 return LHS.Base == RHS.Base;
1936 }
1937
1938 friend bool operator!=(iterator LHS, iterator RHS) {
1939 return LHS.Base != RHS.Base;
1940 }
1941 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001942
1943 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
1944
1945 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
1946
1947 /// pointer_begin - First pointer type found;
1948 iterator pointer_begin() { return PointerTypes.begin(); }
1949
1950 /// pointer_end - Last pointer type found;
1951 iterator pointer_end() { return PointerTypes.end(); }
1952
1953 /// enumeration_begin - First enumeration type found;
1954 iterator enumeration_begin() { return EnumerationTypes.begin(); }
1955
1956 /// enumeration_end - Last enumeration type found;
1957 iterator enumeration_end() { return EnumerationTypes.end(); }
1958};
1959
1960/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
1961/// the set of pointer types along with any more-qualified variants of
1962/// that type. For example, if @p Ty is "int const *", this routine
1963/// will add "int const *", "int const volatile *", "int const
1964/// restrict *", and "int const volatile restrict *" to the set of
1965/// pointer types. Returns true if the add of @p Ty itself succeeded,
1966/// false otherwise.
1967bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
1968 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001969 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001970 return false;
1971
1972 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
1973 QualType PointeeTy = PointerTy->getPointeeType();
1974 // FIXME: Optimize this so that we don't keep trying to add the same types.
1975
1976 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
1977 // with all pointer conversions that don't cast away constness?
1978 if (!PointeeTy.isConstQualified())
1979 AddWithMoreQualifiedTypeVariants
1980 (Context.getPointerType(PointeeTy.withConst()));
1981 if (!PointeeTy.isVolatileQualified())
1982 AddWithMoreQualifiedTypeVariants
1983 (Context.getPointerType(PointeeTy.withVolatile()));
1984 if (!PointeeTy.isRestrictQualified())
1985 AddWithMoreQualifiedTypeVariants
1986 (Context.getPointerType(PointeeTy.withRestrict()));
1987 }
1988
1989 return true;
1990}
1991
1992/// AddTypesConvertedFrom - Add each of the types to which the type @p
1993/// Ty can be implicit converted to the given set of @p Types. We're
1994/// primarily interested in pointer types, enumeration types,
1995void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
1996 bool AllowUserConversions) {
1997 // Only deal with canonical types.
1998 Ty = Context.getCanonicalType(Ty);
1999
2000 // Look through reference types; they aren't part of the type of an
2001 // expression for the purposes of conversions.
2002 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2003 Ty = RefTy->getPointeeType();
2004
2005 // We don't care about qualifiers on the type.
2006 Ty = Ty.getUnqualifiedType();
2007
2008 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2009 QualType PointeeTy = PointerTy->getPointeeType();
2010
2011 // Insert our type, and its more-qualified variants, into the set
2012 // of types.
2013 if (!AddWithMoreQualifiedTypeVariants(Ty))
2014 return;
2015
2016 // Add 'cv void*' to our set of types.
2017 if (!Ty->isVoidType()) {
2018 QualType QualVoid
2019 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2020 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2021 }
2022
2023 // If this is a pointer to a class type, add pointers to its bases
2024 // (with the same level of cv-qualification as the original
2025 // derived class, of course).
2026 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2027 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2028 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2029 Base != ClassDecl->bases_end(); ++Base) {
2030 QualType BaseTy = Context.getCanonicalType(Base->getType());
2031 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2032
2033 // Add the pointer type, recursively, so that we get all of
2034 // the indirect base classes, too.
2035 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
2036 }
2037 }
2038 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002039 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002040 } else if (AllowUserConversions) {
2041 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2042 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2043 // FIXME: Visit conversion functions in the base classes, too.
2044 OverloadedFunctionDecl *Conversions
2045 = ClassDecl->getConversionFunctions();
2046 for (OverloadedFunctionDecl::function_iterator Func
2047 = Conversions->function_begin();
2048 Func != Conversions->function_end(); ++Func) {
2049 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2050 AddTypesConvertedFrom(Conv->getConversionType(), false);
2051 }
2052 }
2053 }
2054}
2055
2056/// AddBuiltinCandidates - Add the appropriate built-in operator
2057/// overloads to the candidate set (C++ [over.built]), based on the
2058/// operator @p Op and the arguments given. For example, if the
2059/// operator is a binary '+', this routine might add
2060/// "int operator+(int, int)"
2061/// to cover integer addition.
2062void
2063Sema::AddBuiltinBinaryOperatorCandidates(OverloadedOperatorKind Op,
2064 Expr **Args,
2065 OverloadCandidateSet& CandidateSet) {
2066 // The set of "promoted arithmetic types", which are the arithmetic
2067 // types are that preserved by promotion (C++ [over.built]p2). Note
2068 // that the first few of these types are the promoted integral
2069 // types; these types need to be first.
2070 // FIXME: What about complex?
2071 const unsigned FirstIntegralType = 0;
2072 const unsigned LastIntegralType = 13;
2073 const unsigned FirstPromotedIntegralType = 7,
2074 LastPromotedIntegralType = 13;
2075 const unsigned FirstPromotedArithmeticType = 7,
2076 LastPromotedArithmeticType = 16;
2077 const unsigned NumArithmeticTypes = 16;
2078 QualType ArithmeticTypes[NumArithmeticTypes] = {
2079 Context.BoolTy, Context.CharTy, Context.WCharTy,
2080 Context.SignedCharTy, Context.ShortTy,
2081 Context.UnsignedCharTy, Context.UnsignedShortTy,
2082 Context.IntTy, Context.LongTy, Context.LongLongTy,
2083 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2084 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2085 };
2086
2087 // Find all of the types that the arguments can convert to, but only
2088 // if the operator we're looking at has built-in operator candidates
2089 // that make use of these types.
2090 BuiltinCandidateTypeSet CandidateTypes(Context);
2091 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2092 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
2093 Op == OO_Plus || Op == OO_Minus || Op == OO_Equal ||
2094 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
2095 Op == OO_ArrowStar) {
2096 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx)
2097 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2098 }
2099
2100 bool isComparison = false;
2101 switch (Op) {
2102 case OO_None:
2103 case NUM_OVERLOADED_OPERATORS:
2104 assert(false && "Expected an overloaded operator");
2105 break;
2106
2107 case OO_New:
2108 case OO_Delete:
2109 case OO_Array_New:
2110 case OO_Array_Delete:
2111 case OO_Tilde:
2112 case OO_Exclaim:
2113 case OO_PlusPlus:
2114 case OO_MinusMinus:
2115 case OO_Arrow:
2116 case OO_Call:
2117 assert(false && "Expected a binary operator");
2118 break;
2119
2120 case OO_Comma:
2121 // C++ [over.match.oper]p3:
2122 // -- For the operator ',', the unary operator '&', or the
2123 // operator '->', the built-in candidates set is empty.
2124 // We don't check '&' or '->' here, since they are unary operators.
2125 break;
2126
2127 case OO_Less:
2128 case OO_Greater:
2129 case OO_LessEqual:
2130 case OO_GreaterEqual:
2131 case OO_EqualEqual:
2132 case OO_ExclaimEqual:
2133 // C++ [over.built]p15:
2134 //
2135 // For every pointer or enumeration type T, there exist
2136 // candidate operator functions of the form
2137 //
2138 // bool operator<(T, T);
2139 // bool operator>(T, T);
2140 // bool operator<=(T, T);
2141 // bool operator>=(T, T);
2142 // bool operator==(T, T);
2143 // bool operator!=(T, T);
2144 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2145 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2146 QualType ParamTypes[2] = { *Ptr, *Ptr };
2147 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2148 }
2149 for (BuiltinCandidateTypeSet::iterator Enum
2150 = CandidateTypes.enumeration_begin();
2151 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2152 QualType ParamTypes[2] = { *Enum, *Enum };
2153 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2154 }
2155
2156 // Fall through.
2157 isComparison = true;
2158
2159 case OO_Plus:
2160 case OO_Minus:
2161 if (!isComparison) {
2162 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2163
2164 // C++ [over.built]p13:
2165 //
2166 // For every cv-qualified or cv-unqualified object type T
2167 // there exist candidate operator functions of the form
2168 //
2169 // T* operator+(T*, ptrdiff_t);
2170 // T& operator[](T*, ptrdiff_t); [BELOW]
2171 // T* operator-(T*, ptrdiff_t);
2172 // T* operator+(ptrdiff_t, T*);
2173 // T& operator[](ptrdiff_t, T*); [BELOW]
2174 //
2175 // C++ [over.built]p14:
2176 //
2177 // For every T, where T is a pointer to object type, there
2178 // exist candidate operator functions of the form
2179 //
2180 // ptrdiff_t operator-(T, T);
2181 for (BuiltinCandidateTypeSet::iterator Ptr
2182 = CandidateTypes.pointer_begin();
2183 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2184 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2185
2186 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2187 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2188
2189 if (Op == OO_Plus) {
2190 // T* operator+(ptrdiff_t, T*);
2191 ParamTypes[0] = ParamTypes[1];
2192 ParamTypes[1] = *Ptr;
2193 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2194 } else {
2195 // ptrdiff_t operator-(T, T);
2196 ParamTypes[1] = *Ptr;
2197 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2198 Args, 2, CandidateSet);
2199 }
2200 }
2201 }
2202 // Fall through
2203
2204 case OO_Star:
2205 case OO_Slash:
2206 // C++ [over.built]p12:
2207 //
2208 // For every pair of promoted arithmetic types L and R, there
2209 // exist candidate operator functions of the form
2210 //
2211 // LR operator*(L, R);
2212 // LR operator/(L, R);
2213 // LR operator+(L, R);
2214 // LR operator-(L, R);
2215 // bool operator<(L, R);
2216 // bool operator>(L, R);
2217 // bool operator<=(L, R);
2218 // bool operator>=(L, R);
2219 // bool operator==(L, R);
2220 // bool operator!=(L, R);
2221 //
2222 // where LR is the result of the usual arithmetic conversions
2223 // between types L and R.
2224 for (unsigned Left = FirstPromotedArithmeticType;
2225 Left < LastPromotedArithmeticType; ++Left) {
2226 for (unsigned Right = FirstPromotedArithmeticType;
2227 Right < LastPromotedArithmeticType; ++Right) {
2228 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2229 QualType Result
2230 = isComparison? Context.BoolTy
2231 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2232 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2233 }
2234 }
2235 break;
2236
2237 case OO_Percent:
2238 case OO_Amp:
2239 case OO_Caret:
2240 case OO_Pipe:
2241 case OO_LessLess:
2242 case OO_GreaterGreater:
2243 // C++ [over.built]p17:
2244 //
2245 // For every pair of promoted integral types L and R, there
2246 // exist candidate operator functions of the form
2247 //
2248 // LR operator%(L, R);
2249 // LR operator&(L, R);
2250 // LR operator^(L, R);
2251 // LR operator|(L, R);
2252 // L operator<<(L, R);
2253 // L operator>>(L, R);
2254 //
2255 // where LR is the result of the usual arithmetic conversions
2256 // between types L and R.
2257 for (unsigned Left = FirstPromotedIntegralType;
2258 Left < LastPromotedIntegralType; ++Left) {
2259 for (unsigned Right = FirstPromotedIntegralType;
2260 Right < LastPromotedIntegralType; ++Right) {
2261 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2262 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2263 ? LandR[0]
2264 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2265 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2266 }
2267 }
2268 break;
2269
2270 case OO_Equal:
2271 // C++ [over.built]p20:
2272 //
2273 // For every pair (T, VQ), where T is an enumeration or
2274 // (FIXME:) pointer to member type and VQ is either volatile or
2275 // empty, there exist candidate operator functions of the form
2276 //
2277 // VQ T& operator=(VQ T&, T);
2278 for (BuiltinCandidateTypeSet::iterator Enum
2279 = CandidateTypes.enumeration_begin();
2280 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2281 QualType ParamTypes[2];
2282
2283 // T& operator=(T&, T)
2284 ParamTypes[0] = Context.getReferenceType(*Enum);
2285 ParamTypes[1] = *Enum;
2286 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2287
2288 // volatile T& operator=(volatile T&, T)
Douglas Gregorbf3af052008-11-13 20:12:29 +00002289 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002290 ParamTypes[1] = *Enum;
2291 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2292 }
2293 // Fall through.
2294
2295 case OO_PlusEqual:
2296 case OO_MinusEqual:
2297 // C++ [over.built]p19:
2298 //
2299 // For every pair (T, VQ), where T is any type and VQ is either
2300 // volatile or empty, there exist candidate operator functions
2301 // of the form
2302 //
2303 // T*VQ& operator=(T*VQ&, T*);
2304 //
2305 // C++ [over.built]p21:
2306 //
2307 // For every pair (T, VQ), where T is a cv-qualified or
2308 // cv-unqualified object type and VQ is either volatile or
2309 // empty, there exist candidate operator functions of the form
2310 //
2311 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2312 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2313 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2314 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2315 QualType ParamTypes[2];
2316 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2317
2318 // non-volatile version
2319 ParamTypes[0] = Context.getReferenceType(*Ptr);
2320 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2321
2322 // volatile version
Douglas Gregorbf3af052008-11-13 20:12:29 +00002323 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002324 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2325 }
2326 // Fall through.
2327
2328 case OO_StarEqual:
2329 case OO_SlashEqual:
2330 // C++ [over.built]p18:
2331 //
2332 // For every triple (L, VQ, R), where L is an arithmetic type,
2333 // VQ is either volatile or empty, and R is a promoted
2334 // arithmetic type, there exist candidate operator functions of
2335 // the form
2336 //
2337 // VQ L& operator=(VQ L&, R);
2338 // VQ L& operator*=(VQ L&, R);
2339 // VQ L& operator/=(VQ L&, R);
2340 // VQ L& operator+=(VQ L&, R);
2341 // VQ L& operator-=(VQ L&, R);
2342 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2343 for (unsigned Right = FirstPromotedArithmeticType;
2344 Right < LastPromotedArithmeticType; ++Right) {
2345 QualType ParamTypes[2];
2346 ParamTypes[1] = ArithmeticTypes[Right];
2347
2348 // Add this built-in operator as a candidate (VQ is empty).
2349 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2350 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2351
2352 // Add this built-in operator as a candidate (VQ is 'volatile').
2353 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2354 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2355 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2356 }
2357 }
2358 break;
2359
2360 case OO_PercentEqual:
2361 case OO_LessLessEqual:
2362 case OO_GreaterGreaterEqual:
2363 case OO_AmpEqual:
2364 case OO_CaretEqual:
2365 case OO_PipeEqual:
2366 // C++ [over.built]p22:
2367 //
2368 // For every triple (L, VQ, R), where L is an integral type, VQ
2369 // is either volatile or empty, and R is a promoted integral
2370 // type, there exist candidate operator functions of the form
2371 //
2372 // VQ L& operator%=(VQ L&, R);
2373 // VQ L& operator<<=(VQ L&, R);
2374 // VQ L& operator>>=(VQ L&, R);
2375 // VQ L& operator&=(VQ L&, R);
2376 // VQ L& operator^=(VQ L&, R);
2377 // VQ L& operator|=(VQ L&, R);
2378 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2379 for (unsigned Right = FirstPromotedIntegralType;
2380 Right < LastPromotedIntegralType; ++Right) {
2381 QualType ParamTypes[2];
2382 ParamTypes[1] = ArithmeticTypes[Right];
2383
2384 // Add this built-in operator as a candidate (VQ is empty).
2385 // FIXME: We should be caching these declarations somewhere,
2386 // rather than re-building them every time.
2387 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2388 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2389
2390 // Add this built-in operator as a candidate (VQ is 'volatile').
2391 ParamTypes[0] = ArithmeticTypes[Left];
2392 ParamTypes[0].addVolatile();
2393 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2394 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2395 }
2396 }
2397 break;
2398
2399 case OO_AmpAmp:
2400 case OO_PipePipe: {
2401 // C++ [over.operator]p23:
2402 //
2403 // There also exist candidate operator functions of the form
2404 //
2405 // bool operator!(bool); [In Unary version]
2406 // bool operator&&(bool, bool);
2407 // bool operator||(bool, bool);
2408 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2409 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2410 break;
2411 }
2412
2413 case OO_Subscript:
2414 // C++ [over.built]p13:
2415 //
2416 // For every cv-qualified or cv-unqualified object type T there
2417 // exist candidate operator functions of the form
2418 //
2419 // T* operator+(T*, ptrdiff_t); [ABOVE]
2420 // T& operator[](T*, ptrdiff_t);
2421 // T* operator-(T*, ptrdiff_t); [ABOVE]
2422 // T* operator+(ptrdiff_t, T*); [ABOVE]
2423 // T& operator[](ptrdiff_t, T*);
2424 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2425 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2426 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2427 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2428 QualType ResultTy = Context.getReferenceType(PointeeType);
2429
2430 // T& operator[](T*, ptrdiff_t)
2431 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2432
2433 // T& operator[](ptrdiff_t, T*);
2434 ParamTypes[0] = ParamTypes[1];
2435 ParamTypes[1] = *Ptr;
2436 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2437 }
2438 break;
2439
2440 case OO_ArrowStar:
2441 // FIXME: No support for pointer-to-members yet.
2442 break;
2443 }
2444}
2445
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002446/// AddOverloadCandidates - Add all of the function overloads in Ovl
2447/// to the candidate set.
2448void
Douglas Gregor18fe5682008-11-03 20:45:27 +00002449Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002450 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002451 OverloadCandidateSet& CandidateSet,
2452 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002453{
Douglas Gregor18fe5682008-11-03 20:45:27 +00002454 for (OverloadedFunctionDecl::function_const_iterator Func
2455 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002456 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00002457 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2458 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002459}
2460
2461/// isBetterOverloadCandidate - Determines whether the first overload
2462/// candidate is a better candidate than the second (C++ 13.3.3p1).
2463bool
2464Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2465 const OverloadCandidate& Cand2)
2466{
2467 // Define viable functions to be better candidates than non-viable
2468 // functions.
2469 if (!Cand2.Viable)
2470 return Cand1.Viable;
2471 else if (!Cand1.Viable)
2472 return false;
2473
2474 // FIXME: Deal with the implicit object parameter for static member
2475 // functions. (C++ 13.3.3p1).
2476
2477 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
2478 // function than another viable function F2 if for all arguments i,
2479 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
2480 // then...
2481 unsigned NumArgs = Cand1.Conversions.size();
2482 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
2483 bool HasBetterConversion = false;
2484 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2485 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
2486 Cand2.Conversions[ArgIdx])) {
2487 case ImplicitConversionSequence::Better:
2488 // Cand1 has a better conversion sequence.
2489 HasBetterConversion = true;
2490 break;
2491
2492 case ImplicitConversionSequence::Worse:
2493 // Cand1 can't be better than Cand2.
2494 return false;
2495
2496 case ImplicitConversionSequence::Indistinguishable:
2497 // Do nothing.
2498 break;
2499 }
2500 }
2501
2502 if (HasBetterConversion)
2503 return true;
2504
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002505 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
2506 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002507
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002508 // C++ [over.match.best]p1b4:
2509 //
2510 // -- the context is an initialization by user-defined conversion
2511 // (see 8.5, 13.3.1.5) and the standard conversion sequence
2512 // from the return type of F1 to the destination type (i.e.,
2513 // the type of the entity being initialized) is a better
2514 // conversion sequence than the standard conversion sequence
2515 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00002516 if (Cand1.Function && Cand2.Function &&
2517 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002518 isa<CXXConversionDecl>(Cand2.Function)) {
2519 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
2520 Cand2.FinalConversion)) {
2521 case ImplicitConversionSequence::Better:
2522 // Cand1 has a better conversion sequence.
2523 return true;
2524
2525 case ImplicitConversionSequence::Worse:
2526 // Cand1 can't be better than Cand2.
2527 return false;
2528
2529 case ImplicitConversionSequence::Indistinguishable:
2530 // Do nothing
2531 break;
2532 }
2533 }
2534
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002535 return false;
2536}
2537
2538/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
2539/// within an overload candidate set. If overloading is successful,
2540/// the result will be OR_Success and Best will be set to point to the
2541/// best viable function within the candidate set. Otherwise, one of
2542/// several kinds of errors will be returned; see
2543/// Sema::OverloadingResult.
2544Sema::OverloadingResult
2545Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
2546 OverloadCandidateSet::iterator& Best)
2547{
2548 // Find the best viable function.
2549 Best = CandidateSet.end();
2550 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2551 Cand != CandidateSet.end(); ++Cand) {
2552 if (Cand->Viable) {
2553 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
2554 Best = Cand;
2555 }
2556 }
2557
2558 // If we didn't find any viable functions, abort.
2559 if (Best == CandidateSet.end())
2560 return OR_No_Viable_Function;
2561
2562 // Make sure that this function is better than every other viable
2563 // function. If not, we have an ambiguity.
2564 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2565 Cand != CandidateSet.end(); ++Cand) {
2566 if (Cand->Viable &&
2567 Cand != Best &&
2568 !isBetterOverloadCandidate(*Best, *Cand))
2569 return OR_Ambiguous;
2570 }
2571
2572 // Best is the best viable function.
2573 return OR_Success;
2574}
2575
2576/// PrintOverloadCandidates - When overload resolution fails, prints
2577/// diagnostic messages containing the candidates in the candidate
2578/// set. If OnlyViable is true, only viable candidates will be printed.
2579void
2580Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
2581 bool OnlyViable)
2582{
2583 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2584 LastCand = CandidateSet.end();
2585 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002586 if (Cand->Viable || !OnlyViable) {
2587 if (Cand->Function) {
2588 // Normal function
2589 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
2590 } else {
2591 // FIXME: We need to get the identifier in here
2592 // FIXME: Do we want the error message to point at the
2593 // operator? (built-ins won't have a location)
2594 QualType FnType
2595 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
2596 Cand->BuiltinTypes.ParamTypes,
2597 Cand->Conversions.size(),
2598 false, 0);
2599
2600 Diag(SourceLocation(), diag::err_ovl_builtin_candidate,
2601 FnType.getAsString());
2602 }
2603 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002604 }
2605}
2606
Douglas Gregor904eed32008-11-10 20:40:00 +00002607/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
2608/// an overloaded function (C++ [over.over]), where @p From is an
2609/// expression with overloaded function type and @p ToType is the type
2610/// we're trying to resolve to. For example:
2611///
2612/// @code
2613/// int f(double);
2614/// int f(int);
2615///
2616/// int (*pfd)(double) = f; // selects f(double)
2617/// @endcode
2618///
2619/// This routine returns the resulting FunctionDecl if it could be
2620/// resolved, and NULL otherwise. When @p Complain is true, this
2621/// routine will emit diagnostics if there is an error.
2622FunctionDecl *
2623Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
2624 bool Complain) {
2625 QualType FunctionType = ToType;
2626 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
2627 FunctionType = ToTypePtr->getPointeeType();
2628
2629 // We only look at pointers or references to functions.
2630 if (!FunctionType->isFunctionType())
2631 return 0;
2632
2633 // Find the actual overloaded function declaration.
2634 OverloadedFunctionDecl *Ovl = 0;
2635
2636 // C++ [over.over]p1:
2637 // [...] [Note: any redundant set of parentheses surrounding the
2638 // overloaded function name is ignored (5.1). ]
2639 Expr *OvlExpr = From->IgnoreParens();
2640
2641 // C++ [over.over]p1:
2642 // [...] The overloaded function name can be preceded by the &
2643 // operator.
2644 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
2645 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2646 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
2647 }
2648
2649 // Try to dig out the overloaded function.
2650 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
2651 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
2652
2653 // If there's no overloaded function declaration, we're done.
2654 if (!Ovl)
2655 return 0;
2656
2657 // Look through all of the overloaded functions, searching for one
2658 // whose type matches exactly.
2659 // FIXME: When templates or using declarations come along, we'll actually
2660 // have to deal with duplicates, partial ordering, etc. For now, we
2661 // can just do a simple search.
2662 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
2663 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
2664 Fun != Ovl->function_end(); ++Fun) {
2665 // C++ [over.over]p3:
2666 // Non-member functions and static member functions match
2667 // targets of type “pointer-to-function”or
2668 // “reference-to-function.”
2669 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
2670 if (!Method->isStatic())
2671 continue;
2672
2673 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
2674 return *Fun;
2675 }
2676
2677 return 0;
2678}
2679
2680/// FixOverloadedFunctionReference - E is an expression that refers to
2681/// a C++ overloaded function (possibly with some parentheses and
2682/// perhaps a '&' around it). We have resolved the overloaded function
2683/// to the function declaration Fn, so patch up the expression E to
2684/// refer (possibly indirectly) to Fn.
2685void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
2686 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2687 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
2688 E->setType(PE->getSubExpr()->getType());
2689 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
2690 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
2691 "Can only take the address of an overloaded function");
2692 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
2693 E->setType(Context.getPointerType(E->getType()));
2694 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
2695 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
2696 "Expected overloaded function");
2697 DR->setDecl(Fn);
2698 E->setType(Fn->getType());
2699 } else {
2700 assert(false && "Invalid reference to overloaded function");
2701 }
2702}
2703
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002704} // end namespace clang