blob: eb38eee8d5c6b65f4142292b07607b7428f0c2ff [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 Gregorf9eb9052008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000023#include "llvm/Support/Compiler.h"
24#include <algorithm>
25
26namespace clang {
27
28/// GetConversionCategory - Retrieve the implicit conversion
29/// category corresponding to the given implicit conversion kind.
30ImplicitConversionCategory
31GetConversionCategory(ImplicitConversionKind Kind) {
32 static const ImplicitConversionCategory
33 Category[(int)ICK_Num_Conversion_Kinds] = {
34 ICC_Identity,
35 ICC_Lvalue_Transformation,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Qualification_Adjustment,
39 ICC_Promotion,
40 ICC_Promotion,
41 ICC_Conversion,
42 ICC_Conversion,
43 ICC_Conversion,
44 ICC_Conversion,
45 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000046 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000047 ICC_Conversion
48 };
49 return Category[(int)Kind];
50}
51
52/// GetConversionRank - Retrieve the implicit conversion rank
53/// corresponding to the given implicit conversion kind.
54ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
55 static const ImplicitConversionRank
56 Rank[(int)ICK_Num_Conversion_Kinds] = {
57 ICR_Exact_Match,
58 ICR_Exact_Match,
59 ICR_Exact_Match,
60 ICR_Exact_Match,
61 ICR_Exact_Match,
62 ICR_Promotion,
63 ICR_Promotion,
64 ICR_Conversion,
65 ICR_Conversion,
66 ICR_Conversion,
67 ICR_Conversion,
68 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000069 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000070 ICR_Conversion
71 };
72 return Rank[(int)Kind];
73}
74
75/// GetImplicitConversionName - Return the name of this kind of
76/// implicit conversion.
77const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
78 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
79 "No conversion",
80 "Lvalue-to-rvalue",
81 "Array-to-pointer",
82 "Function-to-pointer",
83 "Qualification",
84 "Integral promotion",
85 "Floating point promotion",
86 "Integral conversion",
87 "Floating conversion",
88 "Floating-integral conversion",
89 "Pointer conversion",
90 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +000091 "Boolean conversion",
92 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000093 };
94 return Name[Kind];
95}
96
Douglas Gregor60d62c22008-10-31 16:23:19 +000097/// StandardConversionSequence - Set the standard conversion
98/// sequence to the identity conversion.
99void StandardConversionSequence::setAsIdentityConversion() {
100 First = ICK_Identity;
101 Second = ICK_Identity;
102 Third = ICK_Identity;
103 Deprecated = false;
104 ReferenceBinding = false;
105 DirectBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000106 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000107}
108
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000109/// getRank - Retrieve the rank of this standard conversion sequence
110/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
111/// implicit conversions.
112ImplicitConversionRank StandardConversionSequence::getRank() const {
113 ImplicitConversionRank Rank = ICR_Exact_Match;
114 if (GetConversionRank(First) > Rank)
115 Rank = GetConversionRank(First);
116 if (GetConversionRank(Second) > Rank)
117 Rank = GetConversionRank(Second);
118 if (GetConversionRank(Third) > Rank)
119 Rank = GetConversionRank(Third);
120 return Rank;
121}
122
123/// isPointerConversionToBool - Determines whether this conversion is
124/// a conversion of a pointer or pointer-to-member to bool. This is
125/// used as part of the ranking of standard conversion sequences
126/// (C++ 13.3.3.2p4).
127bool StandardConversionSequence::isPointerConversionToBool() const
128{
129 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
130 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
131
132 // Note that FromType has not necessarily been transformed by the
133 // array-to-pointer or function-to-pointer implicit conversions, so
134 // check for their presence as well as checking whether FromType is
135 // a pointer.
136 if (ToType->isBooleanType() &&
137 (FromType->isPointerType() ||
138 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
139 return true;
140
141 return false;
142}
143
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000144/// isPointerConversionToVoidPointer - Determines whether this
145/// conversion is a conversion of a pointer to a void pointer. This is
146/// used as part of the ranking of standard conversion sequences (C++
147/// 13.3.3.2p4).
148bool
149StandardConversionSequence::
150isPointerConversionToVoidPointer(ASTContext& Context) const
151{
152 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
153 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
154
155 // Note that FromType has not necessarily been transformed by the
156 // array-to-pointer implicit conversion, so check for its presence
157 // and redo the conversion to get a pointer.
158 if (First == ICK_Array_To_Pointer)
159 FromType = Context.getArrayDecayedType(FromType);
160
161 if (Second == ICK_Pointer_Conversion)
162 if (const PointerType* ToPtrType = ToType->getAsPointerType())
163 return ToPtrType->getPointeeType()->isVoidType();
164
165 return false;
166}
167
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000168/// DebugPrint - Print this standard conversion sequence to standard
169/// error. Useful for debugging overloading issues.
170void StandardConversionSequence::DebugPrint() const {
171 bool PrintedSomething = false;
172 if (First != ICK_Identity) {
173 fprintf(stderr, "%s", GetImplicitConversionName(First));
174 PrintedSomething = true;
175 }
176
177 if (Second != ICK_Identity) {
178 if (PrintedSomething) {
179 fprintf(stderr, " -> ");
180 }
181 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000182
183 if (CopyConstructor) {
184 fprintf(stderr, " (by copy constructor)");
185 } else if (DirectBinding) {
186 fprintf(stderr, " (direct reference binding)");
187 } else if (ReferenceBinding) {
188 fprintf(stderr, " (reference binding)");
189 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190 PrintedSomething = true;
191 }
192
193 if (Third != ICK_Identity) {
194 if (PrintedSomething) {
195 fprintf(stderr, " -> ");
196 }
197 fprintf(stderr, "%s", GetImplicitConversionName(Third));
198 PrintedSomething = true;
199 }
200
201 if (!PrintedSomething) {
202 fprintf(stderr, "No conversions required");
203 }
204}
205
206/// DebugPrint - Print this user-defined conversion sequence to standard
207/// error. Useful for debugging overloading issues.
208void UserDefinedConversionSequence::DebugPrint() const {
209 if (Before.First || Before.Second || Before.Third) {
210 Before.DebugPrint();
211 fprintf(stderr, " -> ");
212 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000213 fprintf(stderr, "'%s'", ConversionFunction->getName().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000214 if (After.First || After.Second || After.Third) {
215 fprintf(stderr, " -> ");
216 After.DebugPrint();
217 }
218}
219
220/// DebugPrint - Print this implicit conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void ImplicitConversionSequence::DebugPrint() const {
223 switch (ConversionKind) {
224 case StandardConversion:
225 fprintf(stderr, "Standard conversion: ");
226 Standard.DebugPrint();
227 break;
228 case UserDefinedConversion:
229 fprintf(stderr, "User-defined conversion: ");
230 UserDefined.DebugPrint();
231 break;
232 case EllipsisConversion:
233 fprintf(stderr, "Ellipsis conversion");
234 break;
235 case BadConversion:
236 fprintf(stderr, "Bad conversion");
237 break;
238 }
239
240 fprintf(stderr, "\n");
241}
242
243// IsOverload - Determine whether the given New declaration is an
244// overload of the Old declaration. This routine returns false if New
245// and Old cannot be overloaded, e.g., if they are functions with the
246// same signature (C++ 1.3.10) or if the Old declaration isn't a
247// function (or overload set). When it does return false and Old is an
248// OverloadedFunctionDecl, MatchedDecl will be set to point to the
249// FunctionDecl that New cannot be overloaded with.
250//
251// Example: Given the following input:
252//
253// void f(int, float); // #1
254// void f(int, int); // #2
255// int f(int, int); // #3
256//
257// When we process #1, there is no previous declaration of "f",
258// so IsOverload will not be used.
259//
260// When we process #2, Old is a FunctionDecl for #1. By comparing the
261// parameter types, we see that #1 and #2 are overloaded (since they
262// have different signatures), so this routine returns false;
263// MatchedDecl is unchanged.
264//
265// When we process #3, Old is an OverloadedFunctionDecl containing #1
266// and #2. We compare the signatures of #3 to #1 (they're overloaded,
267// so we do nothing) and then #3 to #2. Since the signatures of #3 and
268// #2 are identical (return types of functions are not part of the
269// signature), IsOverload returns false and MatchedDecl will be set to
270// point to the FunctionDecl for #2.
271bool
272Sema::IsOverload(FunctionDecl *New, Decl* OldD,
273 OverloadedFunctionDecl::function_iterator& MatchedDecl)
274{
275 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
276 // Is this new function an overload of every function in the
277 // overload set?
278 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
279 FuncEnd = Ovl->function_end();
280 for (; Func != FuncEnd; ++Func) {
281 if (!IsOverload(New, *Func, MatchedDecl)) {
282 MatchedDecl = Func;
283 return false;
284 }
285 }
286
287 // This function overloads every function in the overload set.
288 return true;
289 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
290 // Is the function New an overload of the function Old?
291 QualType OldQType = Context.getCanonicalType(Old->getType());
292 QualType NewQType = Context.getCanonicalType(New->getType());
293
294 // Compare the signatures (C++ 1.3.10) of the two functions to
295 // determine whether they are overloads. If we find any mismatch
296 // in the signature, they are overloads.
297
298 // If either of these functions is a K&R-style function (no
299 // prototype), then we consider them to have matching signatures.
300 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
301 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
302 return false;
303
304 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
305 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
306
307 // The signature of a function includes the types of its
308 // parameters (C++ 1.3.10), which includes the presence or absence
309 // of the ellipsis; see C++ DR 357).
310 if (OldQType != NewQType &&
311 (OldType->getNumArgs() != NewType->getNumArgs() ||
312 OldType->isVariadic() != NewType->isVariadic() ||
313 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
314 NewType->arg_type_begin())))
315 return true;
316
317 // If the function is a class member, its signature includes the
318 // cv-qualifiers (if any) on the function itself.
319 //
320 // As part of this, also check whether one of the member functions
321 // is static, in which case they are not overloads (C++
322 // 13.1p2). While not part of the definition of the signature,
323 // this check is important to determine whether these functions
324 // can be overloaded.
325 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
326 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
327 if (OldMethod && NewMethod &&
328 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000329 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000330 return true;
331
332 // The signatures match; this is not an overload.
333 return false;
334 } else {
335 // (C++ 13p1):
336 // Only function declarations can be overloaded; object and type
337 // declarations cannot be overloaded.
338 return false;
339 }
340}
341
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000342/// TryImplicitConversion - Attempt to perform an implicit conversion
343/// from the given expression (Expr) to the given type (ToType). This
344/// function returns an implicit conversion sequence that can be used
345/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000346///
347/// void f(float f);
348/// void g(int i) { f(i); }
349///
350/// this routine would produce an implicit conversion sequence to
351/// describe the initialization of f from i, which will be a standard
352/// conversion sequence containing an lvalue-to-rvalue conversion (C++
353/// 4.1) followed by a floating-integral conversion (C++ 4.9).
354//
355/// Note that this routine only determines how the conversion can be
356/// performed; it does not actually perform the conversion. As such,
357/// it will not produce any diagnostics if no conversion is available,
358/// but will instead return an implicit conversion sequence of kind
359/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000360///
361/// If @p SuppressUserConversions, then user-defined conversions are
362/// not permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000363ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000364Sema::TryImplicitConversion(Expr* From, QualType ToType,
365 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000366{
367 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000368 if (IsStandardConversion(From, ToType, ICS.Standard))
369 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000370 else if (!SuppressUserConversions &&
371 IsUserDefinedConversion(From, ToType, ICS.UserDefined)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000372 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000373 // C++ [over.ics.user]p4:
374 // A conversion of an expression of class type to the same class
375 // type is given Exact Match rank, and a conversion of an
376 // expression of class type to a base class of that type is
377 // given Conversion rank, in spite of the fact that a copy
378 // constructor (i.e., a user-defined conversion function) is
379 // called for those cases.
380 if (CXXConstructorDecl *Constructor
381 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
382 if (Constructor->isCopyConstructor(Context)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000383 // Turn this into a "standard" conversion sequence, so that it
384 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000385 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
386 ICS.Standard.setAsIdentityConversion();
387 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
388 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000389 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000390 if (IsDerivedFrom(From->getType().getUnqualifiedType(),
391 ToType.getUnqualifiedType()))
392 ICS.Standard.Second = ICK_Derived_To_Base;
393 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000394 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000395 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000396 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000397
398 return ICS;
399}
400
401/// IsStandardConversion - Determines whether there is a standard
402/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
403/// expression From to the type ToType. Standard conversion sequences
404/// only consider non-class types; for conversions that involve class
405/// types, use TryImplicitConversion. If a conversion exists, SCS will
406/// contain the standard conversion sequence required to perform this
407/// conversion and this routine will return true. Otherwise, this
408/// routine will return false and the value of SCS is unspecified.
409bool
410Sema::IsStandardConversion(Expr* From, QualType ToType,
411 StandardConversionSequence &SCS)
412{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000413 QualType FromType = From->getType();
414
Douglas Gregor60d62c22008-10-31 16:23:19 +0000415 // There are no standard conversions for class types, so abort early.
416 if (FromType->isRecordType() || ToType->isRecordType())
417 return false;
418
419 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000420 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000421 SCS.Deprecated = false;
422 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000423 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000424
425 // The first conversion can be an lvalue-to-rvalue conversion,
426 // array-to-pointer conversion, or function-to-pointer conversion
427 // (C++ 4p1).
428
429 // Lvalue-to-rvalue conversion (C++ 4.1):
430 // An lvalue (3.10) of a non-function, non-array type T can be
431 // converted to an rvalue.
432 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
433 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000434 !FromType->isFunctionType() && !FromType->isArrayType() &&
435 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000436 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000437
438 // If T is a non-class type, the type of the rvalue is the
439 // cv-unqualified version of T. Otherwise, the type of the rvalue
440 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000441 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442 }
443 // Array-to-pointer conversion (C++ 4.2)
444 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000445 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000446
447 // An lvalue or rvalue of type "array of N T" or "array of unknown
448 // bound of T" can be converted to an rvalue of type "pointer to
449 // T" (C++ 4.2p1).
450 FromType = Context.getArrayDecayedType(FromType);
451
452 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
453 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000454 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455
456 // For the purpose of ranking in overload resolution
457 // (13.3.3.1.1), this conversion is considered an
458 // array-to-pointer conversion followed by a qualification
459 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000460 SCS.Second = ICK_Identity;
461 SCS.Third = ICK_Qualification;
462 SCS.ToTypePtr = ToType.getAsOpaquePtr();
463 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000464 }
465 }
466 // Function-to-pointer conversion (C++ 4.3).
467 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000468 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000469
470 // An lvalue of function type T can be converted to an rvalue of
471 // type "pointer to T." The result is a pointer to the
472 // function. (C++ 4.3p1).
473 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000475 // Address of overloaded function (C++ [over.over]).
476 else if (FunctionDecl *Fn
477 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
478 SCS.First = ICK_Function_To_Pointer;
479
480 // We were able to resolve the address of the overloaded function,
481 // so we can convert to the type of that function.
482 FromType = Fn->getType();
483 if (ToType->isReferenceType())
484 FromType = Context.getReferenceType(FromType);
485 else
486 FromType = Context.getPointerType(FromType);
487 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 // We don't require any conversions for the first step.
489 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000490 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 }
492
493 // The second conversion can be an integral promotion, floating
494 // point promotion, integral conversion, floating point conversion,
495 // floating-integral conversion, pointer conversion,
496 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
497 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
498 Context.getCanonicalType(ToType).getUnqualifiedType()) {
499 // The unqualified versions of the types are the same: there's no
500 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000501 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 }
503 // Integral promotion (C++ 4.5).
504 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000505 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 FromType = ToType.getUnqualifiedType();
507 }
508 // Floating point promotion (C++ 4.6).
509 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000510 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000511 FromType = ToType.getUnqualifiedType();
512 }
513 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000514 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000516 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000517 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000518 FromType = ToType.getUnqualifiedType();
519 }
520 // Floating point conversions (C++ 4.8).
521 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000522 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523 FromType = ToType.getUnqualifiedType();
524 }
525 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000526 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000528 ToType->isIntegralType() && !ToType->isBooleanType() &&
529 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000530 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
531 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000532 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533 FromType = ToType.getUnqualifiedType();
534 }
535 // Pointer conversions (C++ 4.10).
Sebastian Redl07779722008-10-31 14:43:28 +0000536 else if (IsPointerConversion(From, FromType, ToType, FromType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000537 SCS.Second = ICK_Pointer_Conversion;
Sebastian Redl07779722008-10-31 14:43:28 +0000538 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000539 // FIXME: Pointer to member conversions (4.11).
540 // Boolean conversions (C++ 4.12).
541 // FIXME: pointer-to-member type
542 else if (ToType->isBooleanType() &&
543 (FromType->isArithmeticType() ||
544 FromType->isEnumeralType() ||
545 FromType->isPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000546 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000547 FromType = Context.BoolTy;
548 } else {
549 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000550 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551 }
552
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000553 QualType CanonFrom;
554 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000555 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000556 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000557 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000558 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000559 CanonFrom = Context.getCanonicalType(FromType);
560 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000561 } else {
562 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000563 SCS.Third = ICK_Identity;
564
565 // C++ [over.best.ics]p6:
566 // [...] Any difference in top-level cv-qualification is
567 // subsumed by the initialization itself and does not constitute
568 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000569 CanonFrom = Context.getCanonicalType(FromType);
570 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000571 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000572 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
573 FromType = ToType;
574 CanonFrom = CanonTo;
575 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000576 }
577
578 // If we have not converted the argument type to the parameter type,
579 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000580 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000581 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000582
Douglas Gregor60d62c22008-10-31 16:23:19 +0000583 SCS.ToTypePtr = FromType.getAsOpaquePtr();
584 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000585}
586
587/// IsIntegralPromotion - Determines whether the conversion from the
588/// expression From (whose potentially-adjusted type is FromType) to
589/// ToType is an integral promotion (C++ 4.5). If so, returns true and
590/// sets PromotedType to the promoted type.
591bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
592{
593 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000594 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000595 if (!To) {
596 return false;
597 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000598
599 // An rvalue of type char, signed char, unsigned char, short int, or
600 // unsigned short int can be converted to an rvalue of type int if
601 // int can represent all the values of the source type; otherwise,
602 // the source rvalue can be converted to an rvalue of type unsigned
603 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000604 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000605 if (// We can promote any signed, promotable integer type to an int
606 (FromType->isSignedIntegerType() ||
607 // We can promote any unsigned integer type whose size is
608 // less than int to an int.
609 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000610 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000611 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000612 }
613
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000614 return To->getKind() == BuiltinType::UInt;
615 }
616
617 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
618 // can be converted to an rvalue of the first of the following types
619 // that can represent all the values of its underlying type: int,
620 // unsigned int, long, or unsigned long (C++ 4.5p2).
621 if ((FromType->isEnumeralType() || FromType->isWideCharType())
622 && ToType->isIntegerType()) {
623 // Determine whether the type we're converting from is signed or
624 // unsigned.
625 bool FromIsSigned;
626 uint64_t FromSize = Context.getTypeSize(FromType);
627 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
628 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
629 FromIsSigned = UnderlyingType->isSignedIntegerType();
630 } else {
631 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
632 FromIsSigned = true;
633 }
634
635 // The types we'll try to promote to, in the appropriate
636 // order. Try each of these types.
637 QualType PromoteTypes[4] = {
638 Context.IntTy, Context.UnsignedIntTy,
639 Context.LongTy, Context.UnsignedLongTy
640 };
Douglas Gregor447b69e2008-11-19 03:25:36 +0000641 for (int Idx = 0; Idx < 4; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000642 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
643 if (FromSize < ToSize ||
644 (FromSize == ToSize &&
645 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
646 // We found the type that we can promote to. If this is the
647 // type we wanted, we have a promotion. Otherwise, no
648 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000649 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000650 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
651 }
652 }
653 }
654
655 // An rvalue for an integral bit-field (9.6) can be converted to an
656 // rvalue of type int if int can represent all the values of the
657 // bit-field; otherwise, it can be converted to unsigned int if
658 // unsigned int can represent all the values of the bit-field. If
659 // the bit-field is larger yet, no integral promotion applies to
660 // it. If the bit-field has an enumerated type, it is treated as any
661 // other value of that type for promotion purposes (C++ 4.5p3).
662 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
663 using llvm::APSInt;
664 FieldDecl *MemberDecl = MemRef->getMemberDecl();
665 APSInt BitWidth;
666 if (MemberDecl->isBitField() &&
667 FromType->isIntegralType() && !FromType->isEnumeralType() &&
668 From->isIntegerConstantExpr(BitWidth, Context)) {
669 APSInt ToSize(Context.getTypeSize(ToType));
670
671 // Are we promoting to an int from a bitfield that fits in an int?
672 if (BitWidth < ToSize ||
Sebastian Redl07779722008-10-31 14:43:28 +0000673 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000674 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000675 }
676
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000677 // Are we promoting to an unsigned int from an unsigned bitfield
678 // that fits into an unsigned int?
Sebastian Redl07779722008-10-31 14:43:28 +0000679 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000680 return To->getKind() == BuiltinType::UInt;
Sebastian Redl07779722008-10-31 14:43:28 +0000681 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000682
683 return false;
684 }
685 }
686
687 // An rvalue of type bool can be converted to an rvalue of type int,
688 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000689 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000690 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000691 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000692
693 return false;
694}
695
696/// IsFloatingPointPromotion - Determines whether the conversion from
697/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
698/// returns true and sets PromotedType to the promoted type.
699bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
700{
701 /// An rvalue of type float can be converted to an rvalue of type
702 /// double. (C++ 4.6p1).
703 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
704 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
705 if (FromBuiltin->getKind() == BuiltinType::Float &&
706 ToBuiltin->getKind() == BuiltinType::Double)
707 return true;
708
709 return false;
710}
711
712/// IsPointerConversion - Determines whether the conversion of the
713/// expression From, which has the (possibly adjusted) type FromType,
714/// can be converted to the type ToType via a pointer conversion (C++
715/// 4.10). If so, returns true and places the converted type (that
716/// might differ from ToType in its cv-qualifiers at some level) into
717/// ConvertedType.
718bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
719 QualType& ConvertedType)
720{
721 const PointerType* ToTypePtr = ToType->getAsPointerType();
722 if (!ToTypePtr)
723 return false;
724
725 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
726 if (From->isNullPointerConstant(Context)) {
727 ConvertedType = ToType;
728 return true;
729 }
Sebastian Redl07779722008-10-31 14:43:28 +0000730
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000731 // An rvalue of type "pointer to cv T," where T is an object type,
732 // can be converted to an rvalue of type "pointer to cv void" (C++
733 // 4.10p2).
734 if (FromType->isPointerType() &&
735 FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
736 ToTypePtr->getPointeeType()->isVoidType()) {
737 // We need to produce a pointer to cv void, where cv is the same
738 // set of cv-qualifiers as we had on the incoming pointee type.
739 QualType toPointee = ToTypePtr->getPointeeType();
740 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
741 ->getPointeeType().getCVRQualifiers();
742
743 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
744 == Quals) {
745 // ToType is exactly the type we want. Use it.
746 ConvertedType = ToType;
747 } else {
748 // Build a new type with the right qualifiers.
749 ConvertedType
750 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
751 }
752 return true;
753 }
754
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000755 // C++ [conv.ptr]p3:
756 //
757 // An rvalue of type "pointer to cv D," where D is a class type,
758 // can be converted to an rvalue of type "pointer to cv B," where
759 // B is a base class (clause 10) of D. If B is an inaccessible
760 // (clause 11) or ambiguous (10.2) base class of D, a program that
761 // necessitates this conversion is ill-formed. The result of the
762 // conversion is a pointer to the base class sub-object of the
763 // derived class object. The null pointer value is converted to
764 // the null pointer value of the destination type.
765 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000766 // Note that we do not check for ambiguity or inaccessibility
767 // here. That is handled by CheckPointerConversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000768 if (const PointerType *FromPtrType = FromType->getAsPointerType())
769 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
770 if (FromPtrType->getPointeeType()->isRecordType() &&
771 ToPtrType->getPointeeType()->isRecordType() &&
772 IsDerivedFrom(FromPtrType->getPointeeType(),
773 ToPtrType->getPointeeType())) {
774 // The conversion is okay. Now, we need to produce the type
775 // that results from this conversion, which will have the same
776 // qualifiers as the incoming type.
777 QualType CanonFromPointee
778 = Context.getCanonicalType(FromPtrType->getPointeeType());
779 QualType ToPointee = ToPtrType->getPointeeType();
780 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
781 unsigned Quals = CanonFromPointee.getCVRQualifiers();
782
783 if (CanonToPointee.getCVRQualifiers() == Quals) {
784 // ToType is exactly the type we want. Use it.
785 ConvertedType = ToType;
786 } else {
787 // Build a new type with the right qualifiers.
788 ConvertedType
789 = Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
790 }
791 return true;
792 }
793 }
794
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000795 return false;
796}
797
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000798/// CheckPointerConversion - Check the pointer conversion from the
799/// expression From to the type ToType. This routine checks for
800/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
801/// conversions for which IsPointerConversion has already returned
802/// true. It returns true and produces a diagnostic if there was an
803/// error, or returns false otherwise.
804bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
805 QualType FromType = From->getType();
806
807 if (const PointerType *FromPtrType = FromType->getAsPointerType())
808 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl07779722008-10-31 14:43:28 +0000809 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
810 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000811 QualType FromPointeeType = FromPtrType->getPointeeType(),
812 ToPointeeType = ToPtrType->getPointeeType();
813 if (FromPointeeType->isRecordType() &&
814 ToPointeeType->isRecordType()) {
815 // We must have a derived-to-base conversion. Check an
816 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000817 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
818 From->getExprLoc(),
819 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000820 }
821 }
822
823 return false;
824}
825
Douglas Gregor98cd5992008-10-21 23:43:52 +0000826/// IsQualificationConversion - Determines whether the conversion from
827/// an rvalue of type FromType to ToType is a qualification conversion
828/// (C++ 4.4).
829bool
830Sema::IsQualificationConversion(QualType FromType, QualType ToType)
831{
832 FromType = Context.getCanonicalType(FromType);
833 ToType = Context.getCanonicalType(ToType);
834
835 // If FromType and ToType are the same type, this is not a
836 // qualification conversion.
837 if (FromType == ToType)
838 return false;
839
840 // (C++ 4.4p4):
841 // A conversion can add cv-qualifiers at levels other than the first
842 // in multi-level pointers, subject to the following rules: [...]
843 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000844 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +0000845 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +0000846 // Within each iteration of the loop, we check the qualifiers to
847 // determine if this still looks like a qualification
848 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000849 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +0000850 // until there are no more pointers or pointers-to-members left to
851 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +0000852 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000853
854 // -- for every j > 0, if const is in cv 1,j then const is in cv
855 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +0000856 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +0000857 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000858
Douglas Gregor98cd5992008-10-21 23:43:52 +0000859 // -- if the cv 1,j and cv 2,j are different, then const is in
860 // every cv for 0 < k < j.
861 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +0000862 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +0000863 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000864
Douglas Gregor98cd5992008-10-21 23:43:52 +0000865 // Keep track of whether all prior cv-qualifiers in the "to" type
866 // include const.
867 PreviousToQualsIncludeConst
868 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +0000869 }
Douglas Gregor98cd5992008-10-21 23:43:52 +0000870
871 // We are left with FromType and ToType being the pointee types
872 // after unwrapping the original FromType and ToType the same number
873 // of types. If we unwrapped any pointers, and if FromType and
874 // ToType have the same unqualified type (since we checked
875 // qualifiers above), then this is a qualification conversion.
876 return UnwrappedAnyPointer &&
877 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
878}
879
Douglas Gregor60d62c22008-10-31 16:23:19 +0000880/// IsUserDefinedConversion - Determines whether there is a
881/// user-defined conversion sequence (C++ [over.ics.user]) that
882/// converts expression From to the type ToType. If such a conversion
883/// exists, User will contain the user-defined conversion sequence
884/// that performs such a conversion and this routine will return
885/// true. Otherwise, this routine returns false and User is
886/// unspecified.
887bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
888 UserDefinedConversionSequence& User)
889{
890 OverloadCandidateSet CandidateSet;
891 if (const CXXRecordType *ToRecordType
892 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
893 // C++ [over.match.ctor]p1:
894 // When objects of class type are direct-initialized (8.5), or
895 // copy-initialized from an expression of the same or a
896 // derived class type (8.5), overload resolution selects the
897 // constructor. [...] For copy-initialization, the candidate
898 // functions are all the converting constructors (12.3.1) of
899 // that class. The argument list is the expression-list within
900 // the parentheses of the initializer.
901 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
902 const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors();
903 for (OverloadedFunctionDecl::function_const_iterator func
904 = Constructors->function_begin();
905 func != Constructors->function_end(); ++func) {
906 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
907 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +0000908 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
909 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000910 }
911 }
912
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000913 if (const CXXRecordType *FromRecordType
914 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
915 // Add all of the conversion functions as candidates.
916 // FIXME: Look for conversions in base classes!
917 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
918 OverloadedFunctionDecl *Conversions
919 = FromRecordDecl->getConversionFunctions();
920 for (OverloadedFunctionDecl::function_iterator Func
921 = Conversions->function_begin();
922 Func != Conversions->function_end(); ++Func) {
923 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
924 AddConversionCandidate(Conv, From, ToType, CandidateSet);
925 }
926 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000927
928 OverloadCandidateSet::iterator Best;
929 switch (BestViableFunction(CandidateSet, Best)) {
930 case OR_Success:
931 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000932 if (CXXConstructorDecl *Constructor
933 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
934 // C++ [over.ics.user]p1:
935 // If the user-defined conversion is specified by a
936 // constructor (12.3.1), the initial standard conversion
937 // sequence converts the source type to the type required by
938 // the argument of the constructor.
939 //
940 // FIXME: What about ellipsis conversions?
941 QualType ThisType = Constructor->getThisType(Context);
942 User.Before = Best->Conversions[0].Standard;
943 User.ConversionFunction = Constructor;
944 User.After.setAsIdentityConversion();
945 User.After.FromTypePtr
946 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
947 User.After.ToTypePtr = ToType.getAsOpaquePtr();
948 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000949 } else if (CXXConversionDecl *Conversion
950 = dyn_cast<CXXConversionDecl>(Best->Function)) {
951 // C++ [over.ics.user]p1:
952 //
953 // [...] If the user-defined conversion is specified by a
954 // conversion function (12.3.2), the initial standard
955 // conversion sequence converts the source type to the
956 // implicit object parameter of the conversion function.
957 User.Before = Best->Conversions[0].Standard;
958 User.ConversionFunction = Conversion;
959
960 // C++ [over.ics.user]p2:
961 // The second standard conversion sequence converts the
962 // result of the user-defined conversion to the target type
963 // for the sequence. Since an implicit conversion sequence
964 // is an initialization, the special rules for
965 // initialization by user-defined conversion apply when
966 // selecting the best user-defined conversion for a
967 // user-defined conversion sequence (see 13.3.3 and
968 // 13.3.3.1).
969 User.After = Best->FinalConversion;
970 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000971 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000972 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000973 return false;
974 }
975
976 case OR_No_Viable_Function:
977 // No conversion here! We're done.
978 return false;
979
980 case OR_Ambiguous:
981 // FIXME: See C++ [over.best.ics]p10 for the handling of
982 // ambiguous conversion sequences.
983 return false;
984 }
985
986 return false;
987}
988
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000989/// CompareImplicitConversionSequences - Compare two implicit
990/// conversion sequences to determine whether one is better than the
991/// other or if they are indistinguishable (C++ 13.3.3.2).
992ImplicitConversionSequence::CompareKind
993Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
994 const ImplicitConversionSequence& ICS2)
995{
996 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
997 // conversion sequences (as defined in 13.3.3.1)
998 // -- a standard conversion sequence (13.3.3.1.1) is a better
999 // conversion sequence than a user-defined conversion sequence or
1000 // an ellipsis conversion sequence, and
1001 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1002 // conversion sequence than an ellipsis conversion sequence
1003 // (13.3.3.1.3).
1004 //
1005 if (ICS1.ConversionKind < ICS2.ConversionKind)
1006 return ImplicitConversionSequence::Better;
1007 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1008 return ImplicitConversionSequence::Worse;
1009
1010 // Two implicit conversion sequences of the same form are
1011 // indistinguishable conversion sequences unless one of the
1012 // following rules apply: (C++ 13.3.3.2p3):
1013 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1014 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1015 else if (ICS1.ConversionKind ==
1016 ImplicitConversionSequence::UserDefinedConversion) {
1017 // User-defined conversion sequence U1 is a better conversion
1018 // sequence than another user-defined conversion sequence U2 if
1019 // they contain the same user-defined conversion function or
1020 // constructor and if the second standard conversion sequence of
1021 // U1 is better than the second standard conversion sequence of
1022 // U2 (C++ 13.3.3.2p3).
1023 if (ICS1.UserDefined.ConversionFunction ==
1024 ICS2.UserDefined.ConversionFunction)
1025 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1026 ICS2.UserDefined.After);
1027 }
1028
1029 return ImplicitConversionSequence::Indistinguishable;
1030}
1031
1032/// CompareStandardConversionSequences - Compare two standard
1033/// conversion sequences to determine whether one is better than the
1034/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1035ImplicitConversionSequence::CompareKind
1036Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1037 const StandardConversionSequence& SCS2)
1038{
1039 // Standard conversion sequence S1 is a better conversion sequence
1040 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1041
1042 // -- S1 is a proper subsequence of S2 (comparing the conversion
1043 // sequences in the canonical form defined by 13.3.3.1.1,
1044 // excluding any Lvalue Transformation; the identity conversion
1045 // sequence is considered to be a subsequence of any
1046 // non-identity conversion sequence) or, if not that,
1047 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1048 // Neither is a proper subsequence of the other. Do nothing.
1049 ;
1050 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1051 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1052 (SCS1.Second == ICK_Identity &&
1053 SCS1.Third == ICK_Identity))
1054 // SCS1 is a proper subsequence of SCS2.
1055 return ImplicitConversionSequence::Better;
1056 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1057 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1058 (SCS2.Second == ICK_Identity &&
1059 SCS2.Third == ICK_Identity))
1060 // SCS2 is a proper subsequence of SCS1.
1061 return ImplicitConversionSequence::Worse;
1062
1063 // -- the rank of S1 is better than the rank of S2 (by the rules
1064 // defined below), or, if not that,
1065 ImplicitConversionRank Rank1 = SCS1.getRank();
1066 ImplicitConversionRank Rank2 = SCS2.getRank();
1067 if (Rank1 < Rank2)
1068 return ImplicitConversionSequence::Better;
1069 else if (Rank2 < Rank1)
1070 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001071
Douglas Gregor57373262008-10-22 14:17:15 +00001072 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1073 // are indistinguishable unless one of the following rules
1074 // applies:
1075
1076 // A conversion that is not a conversion of a pointer, or
1077 // pointer to member, to bool is better than another conversion
1078 // that is such a conversion.
1079 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1080 return SCS2.isPointerConversionToBool()
1081 ? ImplicitConversionSequence::Better
1082 : ImplicitConversionSequence::Worse;
1083
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001084 // C++ [over.ics.rank]p4b2:
1085 //
1086 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001087 // conversion of B* to A* is better than conversion of B* to
1088 // void*, and conversion of A* to void* is better than conversion
1089 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001090 bool SCS1ConvertsToVoid
1091 = SCS1.isPointerConversionToVoidPointer(Context);
1092 bool SCS2ConvertsToVoid
1093 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001094 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1095 // Exactly one of the conversion sequences is a conversion to
1096 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001097 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1098 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001099 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1100 // Neither conversion sequence converts to a void pointer; compare
1101 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001102 if (ImplicitConversionSequence::CompareKind DerivedCK
1103 = CompareDerivedToBaseConversions(SCS1, SCS2))
1104 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001105 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1106 // Both conversion sequences are conversions to void
1107 // pointers. Compare the source types to determine if there's an
1108 // inheritance relationship in their sources.
1109 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1110 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1111
1112 // Adjust the types we're converting from via the array-to-pointer
1113 // conversion, if we need to.
1114 if (SCS1.First == ICK_Array_To_Pointer)
1115 FromType1 = Context.getArrayDecayedType(FromType1);
1116 if (SCS2.First == ICK_Array_To_Pointer)
1117 FromType2 = Context.getArrayDecayedType(FromType2);
1118
1119 QualType FromPointee1
1120 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1121 QualType FromPointee2
1122 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1123
1124 if (IsDerivedFrom(FromPointee2, FromPointee1))
1125 return ImplicitConversionSequence::Better;
1126 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1127 return ImplicitConversionSequence::Worse;
1128 }
Douglas Gregor57373262008-10-22 14:17:15 +00001129
1130 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1131 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001132 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001133 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001134 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001135
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001136 // C++ [over.ics.rank]p3b4:
1137 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1138 // which the references refer are the same type except for
1139 // top-level cv-qualifiers, and the type to which the reference
1140 // initialized by S2 refers is more cv-qualified than the type
1141 // to which the reference initialized by S1 refers.
1142 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1143 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1144 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1145 T1 = Context.getCanonicalType(T1);
1146 T2 = Context.getCanonicalType(T2);
1147 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1148 if (T2.isMoreQualifiedThan(T1))
1149 return ImplicitConversionSequence::Better;
1150 else if (T1.isMoreQualifiedThan(T2))
1151 return ImplicitConversionSequence::Worse;
1152 }
1153 }
Douglas Gregor57373262008-10-22 14:17:15 +00001154
1155 return ImplicitConversionSequence::Indistinguishable;
1156}
1157
1158/// CompareQualificationConversions - Compares two standard conversion
1159/// sequences to determine whether they can be ranked based on their
1160/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1161ImplicitConversionSequence::CompareKind
1162Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1163 const StandardConversionSequence& SCS2)
1164{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001165 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001166 // -- S1 and S2 differ only in their qualification conversion and
1167 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1168 // cv-qualification signature of type T1 is a proper subset of
1169 // the cv-qualification signature of type T2, and S1 is not the
1170 // deprecated string literal array-to-pointer conversion (4.2).
1171 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1172 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1173 return ImplicitConversionSequence::Indistinguishable;
1174
1175 // FIXME: the example in the standard doesn't use a qualification
1176 // conversion (!)
1177 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1178 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1179 T1 = Context.getCanonicalType(T1);
1180 T2 = Context.getCanonicalType(T2);
1181
1182 // If the types are the same, we won't learn anything by unwrapped
1183 // them.
1184 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1185 return ImplicitConversionSequence::Indistinguishable;
1186
1187 ImplicitConversionSequence::CompareKind Result
1188 = ImplicitConversionSequence::Indistinguishable;
1189 while (UnwrapSimilarPointerTypes(T1, T2)) {
1190 // Within each iteration of the loop, we check the qualifiers to
1191 // determine if this still looks like a qualification
1192 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001193 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001194 // until there are no more pointers or pointers-to-members left
1195 // to unwrap. This essentially mimics what
1196 // IsQualificationConversion does, but here we're checking for a
1197 // strict subset of qualifiers.
1198 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1199 // The qualifiers are the same, so this doesn't tell us anything
1200 // about how the sequences rank.
1201 ;
1202 else if (T2.isMoreQualifiedThan(T1)) {
1203 // T1 has fewer qualifiers, so it could be the better sequence.
1204 if (Result == ImplicitConversionSequence::Worse)
1205 // Neither has qualifiers that are a subset of the other's
1206 // qualifiers.
1207 return ImplicitConversionSequence::Indistinguishable;
1208
1209 Result = ImplicitConversionSequence::Better;
1210 } else if (T1.isMoreQualifiedThan(T2)) {
1211 // T2 has fewer qualifiers, so it could be the better sequence.
1212 if (Result == ImplicitConversionSequence::Better)
1213 // Neither has qualifiers that are a subset of the other's
1214 // qualifiers.
1215 return ImplicitConversionSequence::Indistinguishable;
1216
1217 Result = ImplicitConversionSequence::Worse;
1218 } else {
1219 // Qualifiers are disjoint.
1220 return ImplicitConversionSequence::Indistinguishable;
1221 }
1222
1223 // If the types after this point are equivalent, we're done.
1224 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1225 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001226 }
1227
Douglas Gregor57373262008-10-22 14:17:15 +00001228 // Check that the winning standard conversion sequence isn't using
1229 // the deprecated string literal array to pointer conversion.
1230 switch (Result) {
1231 case ImplicitConversionSequence::Better:
1232 if (SCS1.Deprecated)
1233 Result = ImplicitConversionSequence::Indistinguishable;
1234 break;
1235
1236 case ImplicitConversionSequence::Indistinguishable:
1237 break;
1238
1239 case ImplicitConversionSequence::Worse:
1240 if (SCS2.Deprecated)
1241 Result = ImplicitConversionSequence::Indistinguishable;
1242 break;
1243 }
1244
1245 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001246}
1247
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001248/// CompareDerivedToBaseConversions - Compares two standard conversion
1249/// sequences to determine whether they can be ranked based on their
1250/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3).
1251ImplicitConversionSequence::CompareKind
1252Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1253 const StandardConversionSequence& SCS2) {
1254 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1255 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1256 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1257 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1258
1259 // Adjust the types we're converting from via the array-to-pointer
1260 // conversion, if we need to.
1261 if (SCS1.First == ICK_Array_To_Pointer)
1262 FromType1 = Context.getArrayDecayedType(FromType1);
1263 if (SCS2.First == ICK_Array_To_Pointer)
1264 FromType2 = Context.getArrayDecayedType(FromType2);
1265
1266 // Canonicalize all of the types.
1267 FromType1 = Context.getCanonicalType(FromType1);
1268 ToType1 = Context.getCanonicalType(ToType1);
1269 FromType2 = Context.getCanonicalType(FromType2);
1270 ToType2 = Context.getCanonicalType(ToType2);
1271
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001272 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001273 //
1274 // If class B is derived directly or indirectly from class A and
1275 // class C is derived directly or indirectly from B,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001276
1277 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001278 if (SCS1.Second == ICK_Pointer_Conversion &&
1279 SCS2.Second == ICK_Pointer_Conversion) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001280 QualType FromPointee1
1281 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1282 QualType ToPointee1
1283 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1284 QualType FromPointee2
1285 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1286 QualType ToPointee2
1287 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001288 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001289 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1290 if (IsDerivedFrom(ToPointee1, ToPointee2))
1291 return ImplicitConversionSequence::Better;
1292 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1293 return ImplicitConversionSequence::Worse;
1294 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001295
1296 // -- conversion of B* to A* is better than conversion of C* to A*,
1297 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1298 if (IsDerivedFrom(FromPointee2, FromPointee1))
1299 return ImplicitConversionSequence::Better;
1300 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1301 return ImplicitConversionSequence::Worse;
1302 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001303 }
1304
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001305 // Compare based on reference bindings.
1306 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1307 SCS1.Second == ICK_Derived_To_Base) {
1308 // -- binding of an expression of type C to a reference of type
1309 // B& is better than binding an expression of type C to a
1310 // reference of type A&,
1311 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1312 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1313 if (IsDerivedFrom(ToType1, ToType2))
1314 return ImplicitConversionSequence::Better;
1315 else if (IsDerivedFrom(ToType2, ToType1))
1316 return ImplicitConversionSequence::Worse;
1317 }
1318
Douglas Gregor225c41e2008-11-03 19:09:14 +00001319 // -- binding of an expression of type B to a reference of type
1320 // A& is better than binding an expression of type C to a
1321 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001322 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1323 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1324 if (IsDerivedFrom(FromType2, FromType1))
1325 return ImplicitConversionSequence::Better;
1326 else if (IsDerivedFrom(FromType1, FromType2))
1327 return ImplicitConversionSequence::Worse;
1328 }
1329 }
1330
1331
1332 // FIXME: conversion of A::* to B::* is better than conversion of
1333 // A::* to C::*,
1334
1335 // FIXME: conversion of B::* to C::* is better than conversion of
1336 // A::* to C::*, and
1337
Douglas Gregor225c41e2008-11-03 19:09:14 +00001338 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1339 SCS1.Second == ICK_Derived_To_Base) {
1340 // -- conversion of C to B is better than conversion of C to A,
1341 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1342 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1343 if (IsDerivedFrom(ToType1, ToType2))
1344 return ImplicitConversionSequence::Better;
1345 else if (IsDerivedFrom(ToType2, ToType1))
1346 return ImplicitConversionSequence::Worse;
1347 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001348
Douglas Gregor225c41e2008-11-03 19:09:14 +00001349 // -- conversion of B to A is better than conversion of C to A.
1350 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1351 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1352 if (IsDerivedFrom(FromType2, FromType1))
1353 return ImplicitConversionSequence::Better;
1354 else if (IsDerivedFrom(FromType1, FromType2))
1355 return ImplicitConversionSequence::Worse;
1356 }
1357 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001358
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001359 return ImplicitConversionSequence::Indistinguishable;
1360}
1361
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001362/// TryCopyInitialization - Try to copy-initialize a value of type
1363/// ToType from the expression From. Return the implicit conversion
1364/// sequence required to pass this argument, which may be a bad
1365/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001366/// a parameter of this type). If @p SuppressUserConversions, then we
1367/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001368ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001369Sema::TryCopyInitialization(Expr *From, QualType ToType,
1370 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001371 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001372 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001373 AssignConvertType ConvTy =
1374 CheckSingleAssignmentConstraints(ToType, From);
1375 ImplicitConversionSequence ICS;
1376 if (getLangOptions().NoExtensions? ConvTy != Compatible
1377 : ConvTy == Incompatible)
1378 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1379 else
1380 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1381 return ICS;
1382 } else if (ToType->isReferenceType()) {
1383 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001384 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001385 return ICS;
1386 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001387 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001388 }
1389}
1390
1391/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1392/// type ToType. Returns true (and emits a diagnostic) if there was
1393/// an error, returns false if the initialization succeeded.
1394bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1395 const char* Flavor) {
1396 if (!getLangOptions().CPlusPlus) {
1397 // In C, argument passing is the same as performing an assignment.
1398 QualType FromType = From->getType();
1399 AssignConvertType ConvTy =
1400 CheckSingleAssignmentConstraints(ToType, From);
1401
1402 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1403 FromType, From, Flavor);
1404 } else if (ToType->isReferenceType()) {
1405 return CheckReferenceInit(From, ToType);
1406 } else {
1407 if (PerformImplicitConversion(From, ToType))
1408 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001409 diag::err_typecheck_convert_incompatible)
1410 << ToType.getAsString() << From->getType().getAsString()
1411 << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001412 else
1413 return false;
1414 }
1415}
1416
Douglas Gregor96176b32008-11-18 23:14:02 +00001417/// TryObjectArgumentInitialization - Try to initialize the object
1418/// parameter of the given member function (@c Method) from the
1419/// expression @p From.
1420ImplicitConversionSequence
1421Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1422 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1423 unsigned MethodQuals = Method->getTypeQualifiers();
1424 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1425
1426 // Set up the conversion sequence as a "bad" conversion, to allow us
1427 // to exit early.
1428 ImplicitConversionSequence ICS;
1429 ICS.Standard.setAsIdentityConversion();
1430 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1431
1432 // We need to have an object of class type.
1433 QualType FromType = From->getType();
1434 if (!FromType->isRecordType())
1435 return ICS;
1436
1437 // The implicit object parmeter is has the type "reference to cv X",
1438 // where X is the class of which the function is a member
1439 // (C++ [over.match.funcs]p4). However, when finding an implicit
1440 // conversion sequence for the argument, we are not allowed to
1441 // create temporaries or perform user-defined conversions
1442 // (C++ [over.match.funcs]p5). We perform a simplified version of
1443 // reference binding here, that allows class rvalues to bind to
1444 // non-constant references.
1445
1446 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1447 // with the implicit object parameter (C++ [over.match.funcs]p5).
1448 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1449 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1450 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1451 return ICS;
1452
1453 // Check that we have either the same type or a derived type. It
1454 // affects the conversion rank.
1455 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1456 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1457 ICS.Standard.Second = ICK_Identity;
1458 else if (IsDerivedFrom(FromType, ClassType))
1459 ICS.Standard.Second = ICK_Derived_To_Base;
1460 else
1461 return ICS;
1462
1463 // Success. Mark this as a reference binding.
1464 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1465 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1466 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1467 ICS.Standard.ReferenceBinding = true;
1468 ICS.Standard.DirectBinding = true;
1469 return ICS;
1470}
1471
1472/// PerformObjectArgumentInitialization - Perform initialization of
1473/// the implicit object parameter for the given Method with the given
1474/// expression.
1475bool
1476Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1477 QualType ImplicitParamType
1478 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1479 ImplicitConversionSequence ICS
1480 = TryObjectArgumentInitialization(From, Method);
1481 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1482 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001483 diag::err_implicit_object_parameter_init)
1484 << ImplicitParamType.getAsString() << From->getType().getAsString()
1485 << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001486
1487 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1488 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1489 From->getSourceRange().getBegin(),
1490 From->getSourceRange()))
1491 return true;
1492
1493 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1494 return false;
1495}
1496
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001497/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001498/// candidate functions, using the given function call arguments. If
1499/// @p SuppressUserConversions, then don't allow user-defined
1500/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001501void
1502Sema::AddOverloadCandidate(FunctionDecl *Function,
1503 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001504 OverloadCandidateSet& CandidateSet,
1505 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001506{
1507 const FunctionTypeProto* Proto
1508 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1509 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001510 assert(!isa<CXXConversionDecl>(Function) &&
1511 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001512
1513 // Add this candidate
1514 CandidateSet.push_back(OverloadCandidate());
1515 OverloadCandidate& Candidate = CandidateSet.back();
1516 Candidate.Function = Function;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001517 Candidate.IsSurrogate = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001518
1519 unsigned NumArgsInProto = Proto->getNumArgs();
1520
1521 // (C++ 13.3.2p2): A candidate function having fewer than m
1522 // parameters is viable only if it has an ellipsis in its parameter
1523 // list (8.3.5).
1524 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1525 Candidate.Viable = false;
1526 return;
1527 }
1528
1529 // (C++ 13.3.2p2): A candidate function having more than m parameters
1530 // is viable only if the (m+1)st parameter has a default argument
1531 // (8.3.6). For the purposes of overload resolution, the
1532 // parameter list is truncated on the right, so that there are
1533 // exactly m parameters.
1534 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1535 if (NumArgs < MinRequiredArgs) {
1536 // Not enough arguments.
1537 Candidate.Viable = false;
1538 return;
1539 }
1540
1541 // Determine the implicit conversion sequences for each of the
1542 // arguments.
1543 Candidate.Viable = true;
1544 Candidate.Conversions.resize(NumArgs);
1545 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1546 if (ArgIdx < NumArgsInProto) {
1547 // (C++ 13.3.2p3): for F to be a viable function, there shall
1548 // exist for each argument an implicit conversion sequence
1549 // (13.3.3.1) that converts that argument to the corresponding
1550 // parameter of F.
1551 QualType ParamType = Proto->getArgType(ArgIdx);
1552 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001553 = TryCopyInitialization(Args[ArgIdx], ParamType,
1554 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001555 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001556 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001557 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001558 break;
1559 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001560 } else {
1561 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1562 // argument for which there is no corresponding parameter is
1563 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1564 Candidate.Conversions[ArgIdx].ConversionKind
1565 = ImplicitConversionSequence::EllipsisConversion;
1566 }
1567 }
1568}
1569
Douglas Gregor96176b32008-11-18 23:14:02 +00001570/// AddMethodCandidate - Adds the given C++ member function to the set
1571/// of candidate functions, using the given function call arguments
1572/// and the object argument (@c Object). For example, in a call
1573/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1574/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1575/// allow user-defined conversions via constructors or conversion
1576/// operators.
1577void
1578Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1579 Expr **Args, unsigned NumArgs,
1580 OverloadCandidateSet& CandidateSet,
1581 bool SuppressUserConversions)
1582{
1583 const FunctionTypeProto* Proto
1584 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1585 assert(Proto && "Methods without a prototype cannot be overloaded");
1586 assert(!isa<CXXConversionDecl>(Method) &&
1587 "Use AddConversionCandidate for conversion functions");
1588
1589 // Add this candidate
1590 CandidateSet.push_back(OverloadCandidate());
1591 OverloadCandidate& Candidate = CandidateSet.back();
1592 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001593 Candidate.IsSurrogate = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001594
1595 unsigned NumArgsInProto = Proto->getNumArgs();
1596
1597 // (C++ 13.3.2p2): A candidate function having fewer than m
1598 // parameters is viable only if it has an ellipsis in its parameter
1599 // list (8.3.5).
1600 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1601 Candidate.Viable = false;
1602 return;
1603 }
1604
1605 // (C++ 13.3.2p2): A candidate function having more than m parameters
1606 // is viable only if the (m+1)st parameter has a default argument
1607 // (8.3.6). For the purposes of overload resolution, the
1608 // parameter list is truncated on the right, so that there are
1609 // exactly m parameters.
1610 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1611 if (NumArgs < MinRequiredArgs) {
1612 // Not enough arguments.
1613 Candidate.Viable = false;
1614 return;
1615 }
1616
1617 Candidate.Viable = true;
1618 Candidate.Conversions.resize(NumArgs + 1);
1619
1620 // Determine the implicit conversion sequence for the object
1621 // parameter.
1622 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1623 if (Candidate.Conversions[0].ConversionKind
1624 == ImplicitConversionSequence::BadConversion) {
1625 Candidate.Viable = false;
1626 return;
1627 }
1628
1629 // Determine the implicit conversion sequences for each of the
1630 // arguments.
1631 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1632 if (ArgIdx < NumArgsInProto) {
1633 // (C++ 13.3.2p3): for F to be a viable function, there shall
1634 // exist for each argument an implicit conversion sequence
1635 // (13.3.3.1) that converts that argument to the corresponding
1636 // parameter of F.
1637 QualType ParamType = Proto->getArgType(ArgIdx);
1638 Candidate.Conversions[ArgIdx + 1]
1639 = TryCopyInitialization(Args[ArgIdx], ParamType,
1640 SuppressUserConversions);
1641 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1642 == ImplicitConversionSequence::BadConversion) {
1643 Candidate.Viable = false;
1644 break;
1645 }
1646 } else {
1647 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1648 // argument for which there is no corresponding parameter is
1649 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1650 Candidate.Conversions[ArgIdx + 1].ConversionKind
1651 = ImplicitConversionSequence::EllipsisConversion;
1652 }
1653 }
1654}
1655
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001656/// AddConversionCandidate - Add a C++ conversion function as a
1657/// candidate in the candidate set (C++ [over.match.conv],
1658/// C++ [over.match.copy]). From is the expression we're converting from,
1659/// and ToType is the type that we're eventually trying to convert to
1660/// (which may or may not be the same type as the type that the
1661/// conversion function produces).
1662void
1663Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1664 Expr *From, QualType ToType,
1665 OverloadCandidateSet& CandidateSet) {
1666 // Add this candidate
1667 CandidateSet.push_back(OverloadCandidate());
1668 OverloadCandidate& Candidate = CandidateSet.back();
1669 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001670 Candidate.IsSurrogate = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001671 Candidate.FinalConversion.setAsIdentityConversion();
1672 Candidate.FinalConversion.FromTypePtr
1673 = Conversion->getConversionType().getAsOpaquePtr();
1674 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1675
Douglas Gregor96176b32008-11-18 23:14:02 +00001676 // Determine the implicit conversion sequence for the implicit
1677 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001678 Candidate.Viable = true;
1679 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00001680 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001681
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001682 if (Candidate.Conversions[0].ConversionKind
1683 == ImplicitConversionSequence::BadConversion) {
1684 Candidate.Viable = false;
1685 return;
1686 }
1687
1688 // To determine what the conversion from the result of calling the
1689 // conversion function to the type we're eventually trying to
1690 // convert to (ToType), we need to synthesize a call to the
1691 // conversion function and attempt copy initialization from it. This
1692 // makes sure that we get the right semantics with respect to
1693 // lvalues/rvalues and the type. Fortunately, we can allocate this
1694 // call on the stack and we don't need its arguments to be
1695 // well-formed.
1696 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1697 SourceLocation());
1698 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001699 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001700 CallExpr Call(&ConversionFn, 0, 0,
1701 Conversion->getConversionType().getNonReferenceType(),
1702 SourceLocation());
1703 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1704 switch (ICS.ConversionKind) {
1705 case ImplicitConversionSequence::StandardConversion:
1706 Candidate.FinalConversion = ICS.Standard;
1707 break;
1708
1709 case ImplicitConversionSequence::BadConversion:
1710 Candidate.Viable = false;
1711 break;
1712
1713 default:
1714 assert(false &&
1715 "Can only end up with a standard conversion sequence or failure");
1716 }
1717}
1718
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001719/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
1720/// converts the given @c Object to a function pointer via the
1721/// conversion function @c Conversion, and then attempts to call it
1722/// with the given arguments (C++ [over.call.object]p2-4). Proto is
1723/// the type of function that we'll eventually be calling.
1724void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
1725 const FunctionTypeProto *Proto,
1726 Expr *Object, Expr **Args, unsigned NumArgs,
1727 OverloadCandidateSet& CandidateSet) {
1728 CandidateSet.push_back(OverloadCandidate());
1729 OverloadCandidate& Candidate = CandidateSet.back();
1730 Candidate.Function = 0;
1731 Candidate.Surrogate = Conversion;
1732 Candidate.Viable = true;
1733 Candidate.IsSurrogate = true;
1734 Candidate.Conversions.resize(NumArgs + 1);
1735
1736 // Determine the implicit conversion sequence for the implicit
1737 // object parameter.
1738 ImplicitConversionSequence ObjectInit
1739 = TryObjectArgumentInitialization(Object, Conversion);
1740 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
1741 Candidate.Viable = false;
1742 return;
1743 }
1744
1745 // The first conversion is actually a user-defined conversion whose
1746 // first conversion is ObjectInit's standard conversion (which is
1747 // effectively a reference binding). Record it as such.
1748 Candidate.Conversions[0].ConversionKind
1749 = ImplicitConversionSequence::UserDefinedConversion;
1750 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
1751 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
1752 Candidate.Conversions[0].UserDefined.After
1753 = Candidate.Conversions[0].UserDefined.Before;
1754 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
1755
1756 // Find the
1757 unsigned NumArgsInProto = Proto->getNumArgs();
1758
1759 // (C++ 13.3.2p2): A candidate function having fewer than m
1760 // parameters is viable only if it has an ellipsis in its parameter
1761 // list (8.3.5).
1762 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1763 Candidate.Viable = false;
1764 return;
1765 }
1766
1767 // Function types don't have any default arguments, so just check if
1768 // we have enough arguments.
1769 if (NumArgs < NumArgsInProto) {
1770 // Not enough arguments.
1771 Candidate.Viable = false;
1772 return;
1773 }
1774
1775 // Determine the implicit conversion sequences for each of the
1776 // arguments.
1777 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1778 if (ArgIdx < NumArgsInProto) {
1779 // (C++ 13.3.2p3): for F to be a viable function, there shall
1780 // exist for each argument an implicit conversion sequence
1781 // (13.3.3.1) that converts that argument to the corresponding
1782 // parameter of F.
1783 QualType ParamType = Proto->getArgType(ArgIdx);
1784 Candidate.Conversions[ArgIdx + 1]
1785 = TryCopyInitialization(Args[ArgIdx], ParamType,
1786 /*SuppressUserConversions=*/false);
1787 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1788 == ImplicitConversionSequence::BadConversion) {
1789 Candidate.Viable = false;
1790 break;
1791 }
1792 } else {
1793 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1794 // argument for which there is no corresponding parameter is
1795 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1796 Candidate.Conversions[ArgIdx + 1].ConversionKind
1797 = ImplicitConversionSequence::EllipsisConversion;
1798 }
1799 }
1800}
1801
Douglas Gregor447b69e2008-11-19 03:25:36 +00001802/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1803/// an acceptable non-member overloaded operator for a call whose
1804/// arguments have types T1 (and, if non-empty, T2). This routine
1805/// implements the check in C++ [over.match.oper]p3b2 concerning
1806/// enumeration types.
1807static bool
1808IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1809 QualType T1, QualType T2,
1810 ASTContext &Context) {
1811 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1812 return true;
1813
1814 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
1815 if (Proto->getNumArgs() < 1)
1816 return false;
1817
1818 if (T1->isEnumeralType()) {
1819 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1820 if (Context.getCanonicalType(T1).getUnqualifiedType()
1821 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1822 return true;
1823 }
1824
1825 if (Proto->getNumArgs() < 2)
1826 return false;
1827
1828 if (!T2.isNull() && T2->isEnumeralType()) {
1829 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1830 if (Context.getCanonicalType(T2).getUnqualifiedType()
1831 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1832 return true;
1833 }
1834
1835 return false;
1836}
1837
Douglas Gregor96176b32008-11-18 23:14:02 +00001838/// AddOperatorCandidates - Add the overloaded operator candidates for
1839/// the operator Op that was used in an operator expression such as "x
1840/// Op y". S is the scope in which the expression occurred (used for
1841/// name lookup of the operator), Args/NumArgs provides the operator
1842/// arguments, and CandidateSet will store the added overload
1843/// candidates. (C++ [over.match.oper]).
1844void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
1845 Expr **Args, unsigned NumArgs,
1846 OverloadCandidateSet& CandidateSet) {
1847 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1848
1849 // C++ [over.match.oper]p3:
1850 // For a unary operator @ with an operand of a type whose
1851 // cv-unqualified version is T1, and for a binary operator @ with
1852 // a left operand of a type whose cv-unqualified version is T1 and
1853 // a right operand of a type whose cv-unqualified version is T2,
1854 // three sets of candidate functions, designated member
1855 // candidates, non-member candidates and built-in candidates, are
1856 // constructed as follows:
1857 QualType T1 = Args[0]->getType();
1858 QualType T2;
1859 if (NumArgs > 1)
1860 T2 = Args[1]->getType();
1861
1862 // -- If T1 is a class type, the set of member candidates is the
1863 // result of the qualified lookup of T1::operator@
1864 // (13.3.1.1.1); otherwise, the set of member candidates is
1865 // empty.
1866 if (const RecordType *T1Rec = T1->getAsRecordType()) {
1867 IdentifierResolver::iterator I
1868 = IdResolver.begin(OpName, cast<CXXRecordType>(T1Rec)->getDecl(),
1869 /*LookInParentCtx=*/false);
1870 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
1871 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
1872 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1873 /*SuppressUserConversions=*/false);
1874 else if (OverloadedFunctionDecl *Ovl
1875 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
1876 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1877 FEnd = Ovl->function_end();
1878 F != FEnd; ++F) {
1879 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
1880 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1881 /*SuppressUserConversions=*/false);
1882 }
1883 }
1884 }
1885
1886 // -- The set of non-member candidates is the result of the
1887 // unqualified lookup of operator@ in the context of the
1888 // expression according to the usual rules for name lookup in
1889 // unqualified function calls (3.4.2) except that all member
1890 // functions are ignored. However, if no operand has a class
1891 // type, only those non-member functions in the lookup set
1892 // that have a first parameter of type T1 or “reference to
1893 // (possibly cv-qualified) T1”, when T1 is an enumeration
1894 // type, or (if there is a right operand) a second parameter
1895 // of type T2 or “reference to (possibly cv-qualified) T2”,
1896 // when T2 is an enumeration type, are candidate functions.
1897 {
1898 NamedDecl *NonMemberOps = 0;
1899 for (IdentifierResolver::iterator I
1900 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
1901 I != IdResolver.end(); ++I) {
1902 // We don't need to check the identifier namespace, because
1903 // operator names can only be ordinary identifiers.
1904
1905 // Ignore member functions.
1906 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
1907 if (SD->getDeclContext()->isCXXRecord())
1908 continue;
1909 }
1910
1911 // We found something with this name. We're done.
1912 NonMemberOps = *I;
1913 break;
1914 }
1915
Douglas Gregor447b69e2008-11-19 03:25:36 +00001916 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) {
1917 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1918 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
1919 /*SuppressUserConversions=*/false);
1920 } else if (OverloadedFunctionDecl *Ovl
1921 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
Douglas Gregor96176b32008-11-18 23:14:02 +00001922 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1923 FEnd = Ovl->function_end();
Douglas Gregor447b69e2008-11-19 03:25:36 +00001924 F != FEnd; ++F) {
1925 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context))
1926 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
1927 /*SuppressUserConversions=*/false);
1928 }
Douglas Gregor96176b32008-11-18 23:14:02 +00001929 }
1930 }
1931
1932 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00001933 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor96176b32008-11-18 23:14:02 +00001934}
1935
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001936/// AddBuiltinCandidate - Add a candidate for a built-in
1937/// operator. ResultTy and ParamTys are the result and parameter types
1938/// of the built-in candidate, respectively. Args and NumArgs are the
1939/// arguments being passed to the candidate.
1940void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1941 Expr **Args, unsigned NumArgs,
1942 OverloadCandidateSet& CandidateSet) {
1943 // Add this candidate
1944 CandidateSet.push_back(OverloadCandidate());
1945 OverloadCandidate& Candidate = CandidateSet.back();
1946 Candidate.Function = 0;
1947 Candidate.BuiltinTypes.ResultTy = ResultTy;
1948 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
1949 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
1950
1951 // Determine the implicit conversion sequences for each of the
1952 // arguments.
1953 Candidate.Viable = true;
1954 Candidate.Conversions.resize(NumArgs);
1955 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1956 Candidate.Conversions[ArgIdx]
1957 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
1958 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001959 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001960 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001961 break;
1962 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001963 }
1964}
1965
1966/// BuiltinCandidateTypeSet - A set of types that will be used for the
1967/// candidate operator functions for built-in operators (C++
1968/// [over.built]). The types are separated into pointer types and
1969/// enumeration types.
1970class BuiltinCandidateTypeSet {
1971 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001972 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001973
1974 /// PointerTypes - The set of pointer types that will be used in the
1975 /// built-in candidates.
1976 TypeSet PointerTypes;
1977
1978 /// EnumerationTypes - The set of enumeration types that will be
1979 /// used in the built-in candidates.
1980 TypeSet EnumerationTypes;
1981
1982 /// Context - The AST context in which we will build the type sets.
1983 ASTContext &Context;
1984
1985 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
1986
1987public:
1988 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001989 class iterator {
1990 TypeSet::iterator Base;
1991
1992 public:
1993 typedef QualType value_type;
1994 typedef QualType reference;
1995 typedef QualType pointer;
1996 typedef std::ptrdiff_t difference_type;
1997 typedef std::input_iterator_tag iterator_category;
1998
1999 iterator(TypeSet::iterator B) : Base(B) { }
2000
2001 iterator& operator++() {
2002 ++Base;
2003 return *this;
2004 }
2005
2006 iterator operator++(int) {
2007 iterator tmp(*this);
2008 ++(*this);
2009 return tmp;
2010 }
2011
2012 reference operator*() const {
2013 return QualType::getFromOpaquePtr(*Base);
2014 }
2015
2016 pointer operator->() const {
2017 return **this;
2018 }
2019
2020 friend bool operator==(iterator LHS, iterator RHS) {
2021 return LHS.Base == RHS.Base;
2022 }
2023
2024 friend bool operator!=(iterator LHS, iterator RHS) {
2025 return LHS.Base != RHS.Base;
2026 }
2027 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002028
2029 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2030
2031 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
2032
2033 /// pointer_begin - First pointer type found;
2034 iterator pointer_begin() { return PointerTypes.begin(); }
2035
2036 /// pointer_end - Last pointer type found;
2037 iterator pointer_end() { return PointerTypes.end(); }
2038
2039 /// enumeration_begin - First enumeration type found;
2040 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2041
2042 /// enumeration_end - Last enumeration type found;
2043 iterator enumeration_end() { return EnumerationTypes.end(); }
2044};
2045
2046/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2047/// the set of pointer types along with any more-qualified variants of
2048/// that type. For example, if @p Ty is "int const *", this routine
2049/// will add "int const *", "int const volatile *", "int const
2050/// restrict *", and "int const volatile restrict *" to the set of
2051/// pointer types. Returns true if the add of @p Ty itself succeeded,
2052/// false otherwise.
2053bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2054 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002055 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002056 return false;
2057
2058 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2059 QualType PointeeTy = PointerTy->getPointeeType();
2060 // FIXME: Optimize this so that we don't keep trying to add the same types.
2061
2062 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2063 // with all pointer conversions that don't cast away constness?
2064 if (!PointeeTy.isConstQualified())
2065 AddWithMoreQualifiedTypeVariants
2066 (Context.getPointerType(PointeeTy.withConst()));
2067 if (!PointeeTy.isVolatileQualified())
2068 AddWithMoreQualifiedTypeVariants
2069 (Context.getPointerType(PointeeTy.withVolatile()));
2070 if (!PointeeTy.isRestrictQualified())
2071 AddWithMoreQualifiedTypeVariants
2072 (Context.getPointerType(PointeeTy.withRestrict()));
2073 }
2074
2075 return true;
2076}
2077
2078/// AddTypesConvertedFrom - Add each of the types to which the type @p
2079/// Ty can be implicit converted to the given set of @p Types. We're
2080/// primarily interested in pointer types, enumeration types,
2081void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2082 bool AllowUserConversions) {
2083 // Only deal with canonical types.
2084 Ty = Context.getCanonicalType(Ty);
2085
2086 // Look through reference types; they aren't part of the type of an
2087 // expression for the purposes of conversions.
2088 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2089 Ty = RefTy->getPointeeType();
2090
2091 // We don't care about qualifiers on the type.
2092 Ty = Ty.getUnqualifiedType();
2093
2094 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2095 QualType PointeeTy = PointerTy->getPointeeType();
2096
2097 // Insert our type, and its more-qualified variants, into the set
2098 // of types.
2099 if (!AddWithMoreQualifiedTypeVariants(Ty))
2100 return;
2101
2102 // Add 'cv void*' to our set of types.
2103 if (!Ty->isVoidType()) {
2104 QualType QualVoid
2105 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2106 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2107 }
2108
2109 // If this is a pointer to a class type, add pointers to its bases
2110 // (with the same level of cv-qualification as the original
2111 // derived class, of course).
2112 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2113 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2114 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2115 Base != ClassDecl->bases_end(); ++Base) {
2116 QualType BaseTy = Context.getCanonicalType(Base->getType());
2117 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2118
2119 // Add the pointer type, recursively, so that we get all of
2120 // the indirect base classes, too.
2121 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
2122 }
2123 }
2124 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002125 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002126 } else if (AllowUserConversions) {
2127 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2128 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2129 // FIXME: Visit conversion functions in the base classes, too.
2130 OverloadedFunctionDecl *Conversions
2131 = ClassDecl->getConversionFunctions();
2132 for (OverloadedFunctionDecl::function_iterator Func
2133 = Conversions->function_begin();
2134 Func != Conversions->function_end(); ++Func) {
2135 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2136 AddTypesConvertedFrom(Conv->getConversionType(), false);
2137 }
2138 }
2139 }
2140}
2141
Douglas Gregor74253732008-11-19 15:42:04 +00002142/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2143/// operator overloads to the candidate set (C++ [over.built]), based
2144/// on the operator @p Op and the arguments given. For example, if the
2145/// operator is a binary '+', this routine might add "int
2146/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002147void
Douglas Gregor74253732008-11-19 15:42:04 +00002148Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2149 Expr **Args, unsigned NumArgs,
2150 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002151 // The set of "promoted arithmetic types", which are the arithmetic
2152 // types are that preserved by promotion (C++ [over.built]p2). Note
2153 // that the first few of these types are the promoted integral
2154 // types; these types need to be first.
2155 // FIXME: What about complex?
2156 const unsigned FirstIntegralType = 0;
2157 const unsigned LastIntegralType = 13;
2158 const unsigned FirstPromotedIntegralType = 7,
2159 LastPromotedIntegralType = 13;
2160 const unsigned FirstPromotedArithmeticType = 7,
2161 LastPromotedArithmeticType = 16;
2162 const unsigned NumArithmeticTypes = 16;
2163 QualType ArithmeticTypes[NumArithmeticTypes] = {
2164 Context.BoolTy, Context.CharTy, Context.WCharTy,
2165 Context.SignedCharTy, Context.ShortTy,
2166 Context.UnsignedCharTy, Context.UnsignedShortTy,
2167 Context.IntTy, Context.LongTy, Context.LongLongTy,
2168 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2169 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2170 };
2171
2172 // Find all of the types that the arguments can convert to, but only
2173 // if the operator we're looking at has built-in operator candidates
2174 // that make use of these types.
2175 BuiltinCandidateTypeSet CandidateTypes(Context);
2176 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2177 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002178 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002179 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002180 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2181 (Op == OO_Star && NumArgs == 1)) {
2182 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002183 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2184 }
2185
2186 bool isComparison = false;
2187 switch (Op) {
2188 case OO_None:
2189 case NUM_OVERLOADED_OPERATORS:
2190 assert(false && "Expected an overloaded operator");
2191 break;
2192
Douglas Gregor74253732008-11-19 15:42:04 +00002193 case OO_Star: // '*' is either unary or binary
2194 if (NumArgs == 1)
2195 goto UnaryStar;
2196 else
2197 goto BinaryStar;
2198 break;
2199
2200 case OO_Plus: // '+' is either unary or binary
2201 if (NumArgs == 1)
2202 goto UnaryPlus;
2203 else
2204 goto BinaryPlus;
2205 break;
2206
2207 case OO_Minus: // '-' is either unary or binary
2208 if (NumArgs == 1)
2209 goto UnaryMinus;
2210 else
2211 goto BinaryMinus;
2212 break;
2213
2214 case OO_Amp: // '&' is either unary or binary
2215 if (NumArgs == 1)
2216 goto UnaryAmp;
2217 else
2218 goto BinaryAmp;
2219
2220 case OO_PlusPlus:
2221 case OO_MinusMinus:
2222 // C++ [over.built]p3:
2223 //
2224 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2225 // is either volatile or empty, there exist candidate operator
2226 // functions of the form
2227 //
2228 // VQ T& operator++(VQ T&);
2229 // T operator++(VQ T&, int);
2230 //
2231 // C++ [over.built]p4:
2232 //
2233 // For every pair (T, VQ), where T is an arithmetic type other
2234 // than bool, and VQ is either volatile or empty, there exist
2235 // candidate operator functions of the form
2236 //
2237 // VQ T& operator--(VQ T&);
2238 // T operator--(VQ T&, int);
2239 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2240 Arith < NumArithmeticTypes; ++Arith) {
2241 QualType ArithTy = ArithmeticTypes[Arith];
2242 QualType ParamTypes[2]
2243 = { Context.getReferenceType(ArithTy), Context.IntTy };
2244
2245 // Non-volatile version.
2246 if (NumArgs == 1)
2247 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2248 else
2249 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2250
2251 // Volatile version
2252 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2253 if (NumArgs == 1)
2254 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2255 else
2256 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2257 }
2258
2259 // C++ [over.built]p5:
2260 //
2261 // For every pair (T, VQ), where T is a cv-qualified or
2262 // cv-unqualified object type, and VQ is either volatile or
2263 // empty, there exist candidate operator functions of the form
2264 //
2265 // T*VQ& operator++(T*VQ&);
2266 // T*VQ& operator--(T*VQ&);
2267 // T* operator++(T*VQ&, int);
2268 // T* operator--(T*VQ&, int);
2269 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2270 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2271 // Skip pointer types that aren't pointers to object types.
2272 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
2273 continue;
2274
2275 QualType ParamTypes[2] = {
2276 Context.getReferenceType(*Ptr), Context.IntTy
2277 };
2278
2279 // Without volatile
2280 if (NumArgs == 1)
2281 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2282 else
2283 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2284
2285 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2286 // With volatile
2287 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2288 if (NumArgs == 1)
2289 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2290 else
2291 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2292 }
2293 }
2294 break;
2295
2296 UnaryStar:
2297 // C++ [over.built]p6:
2298 // For every cv-qualified or cv-unqualified object type T, there
2299 // exist candidate operator functions of the form
2300 //
2301 // T& operator*(T*);
2302 //
2303 // C++ [over.built]p7:
2304 // For every function type T, there exist candidate operator
2305 // functions of the form
2306 // T& operator*(T*);
2307 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2308 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2309 QualType ParamTy = *Ptr;
2310 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2311 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2312 &ParamTy, Args, 1, CandidateSet);
2313 }
2314 break;
2315
2316 UnaryPlus:
2317 // C++ [over.built]p8:
2318 // For every type T, there exist candidate operator functions of
2319 // the form
2320 //
2321 // T* operator+(T*);
2322 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2323 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2324 QualType ParamTy = *Ptr;
2325 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2326 }
2327
2328 // Fall through
2329
2330 UnaryMinus:
2331 // C++ [over.built]p9:
2332 // For every promoted arithmetic type T, there exist candidate
2333 // operator functions of the form
2334 //
2335 // T operator+(T);
2336 // T operator-(T);
2337 for (unsigned Arith = FirstPromotedArithmeticType;
2338 Arith < LastPromotedArithmeticType; ++Arith) {
2339 QualType ArithTy = ArithmeticTypes[Arith];
2340 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2341 }
2342 break;
2343
2344 case OO_Tilde:
2345 // C++ [over.built]p10:
2346 // For every promoted integral type T, there exist candidate
2347 // operator functions of the form
2348 //
2349 // T operator~(T);
2350 for (unsigned Int = FirstPromotedIntegralType;
2351 Int < LastPromotedIntegralType; ++Int) {
2352 QualType IntTy = ArithmeticTypes[Int];
2353 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2354 }
2355 break;
2356
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002357 case OO_New:
2358 case OO_Delete:
2359 case OO_Array_New:
2360 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002361 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002362 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002363 break;
2364
2365 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002366 UnaryAmp:
2367 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002368 // C++ [over.match.oper]p3:
2369 // -- For the operator ',', the unary operator '&', or the
2370 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002371 break;
2372
2373 case OO_Less:
2374 case OO_Greater:
2375 case OO_LessEqual:
2376 case OO_GreaterEqual:
2377 case OO_EqualEqual:
2378 case OO_ExclaimEqual:
2379 // C++ [over.built]p15:
2380 //
2381 // For every pointer or enumeration type T, there exist
2382 // candidate operator functions of the form
2383 //
2384 // bool operator<(T, T);
2385 // bool operator>(T, T);
2386 // bool operator<=(T, T);
2387 // bool operator>=(T, T);
2388 // bool operator==(T, T);
2389 // bool operator!=(T, T);
2390 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2391 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2392 QualType ParamTypes[2] = { *Ptr, *Ptr };
2393 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2394 }
2395 for (BuiltinCandidateTypeSet::iterator Enum
2396 = CandidateTypes.enumeration_begin();
2397 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2398 QualType ParamTypes[2] = { *Enum, *Enum };
2399 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2400 }
2401
2402 // Fall through.
2403 isComparison = true;
2404
Douglas Gregor74253732008-11-19 15:42:04 +00002405 BinaryPlus:
2406 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002407 if (!isComparison) {
2408 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2409
2410 // C++ [over.built]p13:
2411 //
2412 // For every cv-qualified or cv-unqualified object type T
2413 // there exist candidate operator functions of the form
2414 //
2415 // T* operator+(T*, ptrdiff_t);
2416 // T& operator[](T*, ptrdiff_t); [BELOW]
2417 // T* operator-(T*, ptrdiff_t);
2418 // T* operator+(ptrdiff_t, T*);
2419 // T& operator[](ptrdiff_t, T*); [BELOW]
2420 //
2421 // C++ [over.built]p14:
2422 //
2423 // For every T, where T is a pointer to object type, there
2424 // exist candidate operator functions of the form
2425 //
2426 // ptrdiff_t operator-(T, T);
2427 for (BuiltinCandidateTypeSet::iterator Ptr
2428 = CandidateTypes.pointer_begin();
2429 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2430 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2431
2432 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2433 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2434
2435 if (Op == OO_Plus) {
2436 // T* operator+(ptrdiff_t, T*);
2437 ParamTypes[0] = ParamTypes[1];
2438 ParamTypes[1] = *Ptr;
2439 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2440 } else {
2441 // ptrdiff_t operator-(T, T);
2442 ParamTypes[1] = *Ptr;
2443 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2444 Args, 2, CandidateSet);
2445 }
2446 }
2447 }
2448 // Fall through
2449
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002450 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002451 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002452 // C++ [over.built]p12:
2453 //
2454 // For every pair of promoted arithmetic types L and R, there
2455 // exist candidate operator functions of the form
2456 //
2457 // LR operator*(L, R);
2458 // LR operator/(L, R);
2459 // LR operator+(L, R);
2460 // LR operator-(L, R);
2461 // bool operator<(L, R);
2462 // bool operator>(L, R);
2463 // bool operator<=(L, R);
2464 // bool operator>=(L, R);
2465 // bool operator==(L, R);
2466 // bool operator!=(L, R);
2467 //
2468 // where LR is the result of the usual arithmetic conversions
2469 // between types L and R.
2470 for (unsigned Left = FirstPromotedArithmeticType;
2471 Left < LastPromotedArithmeticType; ++Left) {
2472 for (unsigned Right = FirstPromotedArithmeticType;
2473 Right < LastPromotedArithmeticType; ++Right) {
2474 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2475 QualType Result
2476 = isComparison? Context.BoolTy
2477 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2478 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2479 }
2480 }
2481 break;
2482
2483 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002484 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002485 case OO_Caret:
2486 case OO_Pipe:
2487 case OO_LessLess:
2488 case OO_GreaterGreater:
2489 // C++ [over.built]p17:
2490 //
2491 // For every pair of promoted integral types L and R, there
2492 // exist candidate operator functions of the form
2493 //
2494 // LR operator%(L, R);
2495 // LR operator&(L, R);
2496 // LR operator^(L, R);
2497 // LR operator|(L, R);
2498 // L operator<<(L, R);
2499 // L operator>>(L, R);
2500 //
2501 // where LR is the result of the usual arithmetic conversions
2502 // between types L and R.
2503 for (unsigned Left = FirstPromotedIntegralType;
2504 Left < LastPromotedIntegralType; ++Left) {
2505 for (unsigned Right = FirstPromotedIntegralType;
2506 Right < LastPromotedIntegralType; ++Right) {
2507 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2508 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2509 ? LandR[0]
2510 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2511 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2512 }
2513 }
2514 break;
2515
2516 case OO_Equal:
2517 // C++ [over.built]p20:
2518 //
2519 // For every pair (T, VQ), where T is an enumeration or
2520 // (FIXME:) pointer to member type and VQ is either volatile or
2521 // empty, there exist candidate operator functions of the form
2522 //
2523 // VQ T& operator=(VQ T&, T);
2524 for (BuiltinCandidateTypeSet::iterator Enum
2525 = CandidateTypes.enumeration_begin();
2526 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2527 QualType ParamTypes[2];
2528
2529 // T& operator=(T&, T)
2530 ParamTypes[0] = Context.getReferenceType(*Enum);
2531 ParamTypes[1] = *Enum;
2532 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2533
Douglas Gregor74253732008-11-19 15:42:04 +00002534 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2535 // volatile T& operator=(volatile T&, T)
2536 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2537 ParamTypes[1] = *Enum;
2538 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2539 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002540 }
2541 // Fall through.
2542
2543 case OO_PlusEqual:
2544 case OO_MinusEqual:
2545 // C++ [over.built]p19:
2546 //
2547 // For every pair (T, VQ), where T is any type and VQ is either
2548 // volatile or empty, there exist candidate operator functions
2549 // of the form
2550 //
2551 // T*VQ& operator=(T*VQ&, T*);
2552 //
2553 // C++ [over.built]p21:
2554 //
2555 // For every pair (T, VQ), where T is a cv-qualified or
2556 // cv-unqualified object type and VQ is either volatile or
2557 // empty, there exist candidate operator functions of the form
2558 //
2559 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2560 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2561 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2562 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2563 QualType ParamTypes[2];
2564 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2565
2566 // non-volatile version
2567 ParamTypes[0] = Context.getReferenceType(*Ptr);
2568 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2569
Douglas Gregor74253732008-11-19 15:42:04 +00002570 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2571 // volatile version
2572 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2573 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2574 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002575 }
2576 // Fall through.
2577
2578 case OO_StarEqual:
2579 case OO_SlashEqual:
2580 // C++ [over.built]p18:
2581 //
2582 // For every triple (L, VQ, R), where L is an arithmetic type,
2583 // VQ is either volatile or empty, and R is a promoted
2584 // arithmetic type, there exist candidate operator functions of
2585 // the form
2586 //
2587 // VQ L& operator=(VQ L&, R);
2588 // VQ L& operator*=(VQ L&, R);
2589 // VQ L& operator/=(VQ L&, R);
2590 // VQ L& operator+=(VQ L&, R);
2591 // VQ L& operator-=(VQ L&, R);
2592 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2593 for (unsigned Right = FirstPromotedArithmeticType;
2594 Right < LastPromotedArithmeticType; ++Right) {
2595 QualType ParamTypes[2];
2596 ParamTypes[1] = ArithmeticTypes[Right];
2597
2598 // Add this built-in operator as a candidate (VQ is empty).
2599 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2600 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2601
2602 // Add this built-in operator as a candidate (VQ is 'volatile').
2603 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2604 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2605 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2606 }
2607 }
2608 break;
2609
2610 case OO_PercentEqual:
2611 case OO_LessLessEqual:
2612 case OO_GreaterGreaterEqual:
2613 case OO_AmpEqual:
2614 case OO_CaretEqual:
2615 case OO_PipeEqual:
2616 // C++ [over.built]p22:
2617 //
2618 // For every triple (L, VQ, R), where L is an integral type, VQ
2619 // is either volatile or empty, and R is a promoted integral
2620 // type, there exist candidate operator functions of the form
2621 //
2622 // VQ L& operator%=(VQ L&, R);
2623 // VQ L& operator<<=(VQ L&, R);
2624 // VQ L& operator>>=(VQ L&, R);
2625 // VQ L& operator&=(VQ L&, R);
2626 // VQ L& operator^=(VQ L&, R);
2627 // VQ L& operator|=(VQ L&, R);
2628 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2629 for (unsigned Right = FirstPromotedIntegralType;
2630 Right < LastPromotedIntegralType; ++Right) {
2631 QualType ParamTypes[2];
2632 ParamTypes[1] = ArithmeticTypes[Right];
2633
2634 // Add this built-in operator as a candidate (VQ is empty).
2635 // FIXME: We should be caching these declarations somewhere,
2636 // rather than re-building them every time.
2637 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2638 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2639
2640 // Add this built-in operator as a candidate (VQ is 'volatile').
2641 ParamTypes[0] = ArithmeticTypes[Left];
2642 ParamTypes[0].addVolatile();
2643 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2644 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2645 }
2646 }
2647 break;
2648
Douglas Gregor74253732008-11-19 15:42:04 +00002649 case OO_Exclaim: {
2650 // C++ [over.operator]p23:
2651 //
2652 // There also exist candidate operator functions of the form
2653 //
2654 // bool operator!(bool);
2655 // bool operator&&(bool, bool); [BELOW]
2656 // bool operator||(bool, bool); [BELOW]
2657 QualType ParamTy = Context.BoolTy;
2658 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2659 break;
2660 }
2661
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002662 case OO_AmpAmp:
2663 case OO_PipePipe: {
2664 // C++ [over.operator]p23:
2665 //
2666 // There also exist candidate operator functions of the form
2667 //
Douglas Gregor74253732008-11-19 15:42:04 +00002668 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002669 // bool operator&&(bool, bool);
2670 // bool operator||(bool, bool);
2671 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2672 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2673 break;
2674 }
2675
2676 case OO_Subscript:
2677 // C++ [over.built]p13:
2678 //
2679 // For every cv-qualified or cv-unqualified object type T there
2680 // exist candidate operator functions of the form
2681 //
2682 // T* operator+(T*, ptrdiff_t); [ABOVE]
2683 // T& operator[](T*, ptrdiff_t);
2684 // T* operator-(T*, ptrdiff_t); [ABOVE]
2685 // T* operator+(ptrdiff_t, T*); [ABOVE]
2686 // T& operator[](ptrdiff_t, T*);
2687 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2688 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2689 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2690 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2691 QualType ResultTy = Context.getReferenceType(PointeeType);
2692
2693 // T& operator[](T*, ptrdiff_t)
2694 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2695
2696 // T& operator[](ptrdiff_t, T*);
2697 ParamTypes[0] = ParamTypes[1];
2698 ParamTypes[1] = *Ptr;
2699 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2700 }
2701 break;
2702
2703 case OO_ArrowStar:
2704 // FIXME: No support for pointer-to-members yet.
2705 break;
2706 }
2707}
2708
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002709/// AddOverloadCandidates - Add all of the function overloads in Ovl
2710/// to the candidate set.
2711void
Douglas Gregor18fe5682008-11-03 20:45:27 +00002712Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002713 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002714 OverloadCandidateSet& CandidateSet,
2715 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002716{
Douglas Gregor18fe5682008-11-03 20:45:27 +00002717 for (OverloadedFunctionDecl::function_const_iterator Func
2718 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002719 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00002720 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2721 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002722}
2723
2724/// isBetterOverloadCandidate - Determines whether the first overload
2725/// candidate is a better candidate than the second (C++ 13.3.3p1).
2726bool
2727Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2728 const OverloadCandidate& Cand2)
2729{
2730 // Define viable functions to be better candidates than non-viable
2731 // functions.
2732 if (!Cand2.Viable)
2733 return Cand1.Viable;
2734 else if (!Cand1.Viable)
2735 return false;
2736
2737 // FIXME: Deal with the implicit object parameter for static member
2738 // functions. (C++ 13.3.3p1).
2739
2740 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
2741 // function than another viable function F2 if for all arguments i,
2742 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
2743 // then...
2744 unsigned NumArgs = Cand1.Conversions.size();
2745 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
2746 bool HasBetterConversion = false;
2747 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2748 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
2749 Cand2.Conversions[ArgIdx])) {
2750 case ImplicitConversionSequence::Better:
2751 // Cand1 has a better conversion sequence.
2752 HasBetterConversion = true;
2753 break;
2754
2755 case ImplicitConversionSequence::Worse:
2756 // Cand1 can't be better than Cand2.
2757 return false;
2758
2759 case ImplicitConversionSequence::Indistinguishable:
2760 // Do nothing.
2761 break;
2762 }
2763 }
2764
2765 if (HasBetterConversion)
2766 return true;
2767
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002768 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
2769 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002770
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002771 // C++ [over.match.best]p1b4:
2772 //
2773 // -- the context is an initialization by user-defined conversion
2774 // (see 8.5, 13.3.1.5) and the standard conversion sequence
2775 // from the return type of F1 to the destination type (i.e.,
2776 // the type of the entity being initialized) is a better
2777 // conversion sequence than the standard conversion sequence
2778 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00002779 if (Cand1.Function && Cand2.Function &&
2780 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002781 isa<CXXConversionDecl>(Cand2.Function)) {
2782 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
2783 Cand2.FinalConversion)) {
2784 case ImplicitConversionSequence::Better:
2785 // Cand1 has a better conversion sequence.
2786 return true;
2787
2788 case ImplicitConversionSequence::Worse:
2789 // Cand1 can't be better than Cand2.
2790 return false;
2791
2792 case ImplicitConversionSequence::Indistinguishable:
2793 // Do nothing
2794 break;
2795 }
2796 }
2797
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002798 return false;
2799}
2800
2801/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
2802/// within an overload candidate set. If overloading is successful,
2803/// the result will be OR_Success and Best will be set to point to the
2804/// best viable function within the candidate set. Otherwise, one of
2805/// several kinds of errors will be returned; see
2806/// Sema::OverloadingResult.
2807Sema::OverloadingResult
2808Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
2809 OverloadCandidateSet::iterator& Best)
2810{
2811 // Find the best viable function.
2812 Best = CandidateSet.end();
2813 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2814 Cand != CandidateSet.end(); ++Cand) {
2815 if (Cand->Viable) {
2816 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
2817 Best = Cand;
2818 }
2819 }
2820
2821 // If we didn't find any viable functions, abort.
2822 if (Best == CandidateSet.end())
2823 return OR_No_Viable_Function;
2824
2825 // Make sure that this function is better than every other viable
2826 // function. If not, we have an ambiguity.
2827 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2828 Cand != CandidateSet.end(); ++Cand) {
2829 if (Cand->Viable &&
2830 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002831 !isBetterOverloadCandidate(*Best, *Cand)) {
2832 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002833 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002834 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002835 }
2836
2837 // Best is the best viable function.
2838 return OR_Success;
2839}
2840
2841/// PrintOverloadCandidates - When overload resolution fails, prints
2842/// diagnostic messages containing the candidates in the candidate
2843/// set. If OnlyViable is true, only viable candidates will be printed.
2844void
2845Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
2846 bool OnlyViable)
2847{
2848 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2849 LastCand = CandidateSet.end();
2850 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002851 if (Cand->Viable || !OnlyViable) {
2852 if (Cand->Function) {
2853 // Normal function
2854 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002855 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00002856 // Desugar the type of the surrogate down to a function type,
2857 // retaining as many typedefs as possible while still showing
2858 // the function type (and, therefore, its parameter types).
2859 QualType FnType = Cand->Surrogate->getConversionType();
2860 bool isReference = false;
2861 bool isPointer = false;
2862 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
2863 FnType = FnTypeRef->getPointeeType();
2864 isReference = true;
2865 }
2866 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
2867 FnType = FnTypePtr->getPointeeType();
2868 isPointer = true;
2869 }
2870 // Desugar down to a function type.
2871 FnType = QualType(FnType->getAsFunctionType(), 0);
2872 // Reconstruct the pointer/reference as appropriate.
2873 if (isPointer) FnType = Context.getPointerType(FnType);
2874 if (isReference) FnType = Context.getReferenceType(FnType);
2875
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002876 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Douglas Gregor621b3932008-11-21 02:54:28 +00002877 << FnType.getAsString();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002878 } else {
2879 // FIXME: We need to get the identifier in here
2880 // FIXME: Do we want the error message to point at the
2881 // operator? (built-ins won't have a location)
2882 QualType FnType
2883 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
2884 Cand->BuiltinTypes.ParamTypes,
2885 Cand->Conversions.size(),
2886 false, 0);
2887
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002888 Diag(SourceLocation(), diag::err_ovl_builtin_candidate)
2889 << FnType.getAsString();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002890 }
2891 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002892 }
2893}
2894
Douglas Gregor904eed32008-11-10 20:40:00 +00002895/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
2896/// an overloaded function (C++ [over.over]), where @p From is an
2897/// expression with overloaded function type and @p ToType is the type
2898/// we're trying to resolve to. For example:
2899///
2900/// @code
2901/// int f(double);
2902/// int f(int);
2903///
2904/// int (*pfd)(double) = f; // selects f(double)
2905/// @endcode
2906///
2907/// This routine returns the resulting FunctionDecl if it could be
2908/// resolved, and NULL otherwise. When @p Complain is true, this
2909/// routine will emit diagnostics if there is an error.
2910FunctionDecl *
2911Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
2912 bool Complain) {
2913 QualType FunctionType = ToType;
2914 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
2915 FunctionType = ToTypePtr->getPointeeType();
2916
2917 // We only look at pointers or references to functions.
2918 if (!FunctionType->isFunctionType())
2919 return 0;
2920
2921 // Find the actual overloaded function declaration.
2922 OverloadedFunctionDecl *Ovl = 0;
2923
2924 // C++ [over.over]p1:
2925 // [...] [Note: any redundant set of parentheses surrounding the
2926 // overloaded function name is ignored (5.1). ]
2927 Expr *OvlExpr = From->IgnoreParens();
2928
2929 // C++ [over.over]p1:
2930 // [...] The overloaded function name can be preceded by the &
2931 // operator.
2932 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
2933 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2934 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
2935 }
2936
2937 // Try to dig out the overloaded function.
2938 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
2939 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
2940
2941 // If there's no overloaded function declaration, we're done.
2942 if (!Ovl)
2943 return 0;
2944
2945 // Look through all of the overloaded functions, searching for one
2946 // whose type matches exactly.
2947 // FIXME: When templates or using declarations come along, we'll actually
2948 // have to deal with duplicates, partial ordering, etc. For now, we
2949 // can just do a simple search.
2950 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
2951 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
2952 Fun != Ovl->function_end(); ++Fun) {
2953 // C++ [over.over]p3:
2954 // Non-member functions and static member functions match
2955 // targets of type “pointer-to-function”or
2956 // “reference-to-function.”
2957 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
2958 if (!Method->isStatic())
2959 continue;
2960
2961 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
2962 return *Fun;
2963 }
2964
2965 return 0;
2966}
2967
Douglas Gregorf9eb9052008-11-19 21:05:33 +00002968/// BuildCallToObjectOfClassType - Build a call to an object of class
2969/// type (C++ [over.call.object]), which can end up invoking an
2970/// overloaded function call operator (@c operator()) or performing a
2971/// user-defined conversion on the object argument.
2972Action::ExprResult
2973Sema::BuildCallToObjectOfClassType(Expr *Object, SourceLocation LParenLoc,
2974 Expr **Args, unsigned NumArgs,
2975 SourceLocation *CommaLocs,
2976 SourceLocation RParenLoc) {
2977 assert(Object->getType()->isRecordType() && "Requires object type argument");
2978 const RecordType *Record = Object->getType()->getAsRecordType();
2979
2980 // C++ [over.call.object]p1:
2981 // If the primary-expression E in the function call syntax
2982 // evaluates to a class object of type “cv T”, then the set of
2983 // candidate functions includes at least the function call
2984 // operators of T. The function call operators of T are obtained by
2985 // ordinary lookup of the name operator() in the context of
2986 // (E).operator().
2987 OverloadCandidateSet CandidateSet;
2988 IdentifierResolver::iterator I
2989 = IdResolver.begin(Context.DeclarationNames.getCXXOperatorName(OO_Call),
2990 cast<CXXRecordType>(Record)->getDecl(),
2991 /*LookInParentCtx=*/false);
2992 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
2993 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
2994 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
2995 /*SuppressUserConversions=*/false);
2996 else if (OverloadedFunctionDecl *Ovl
2997 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
2998 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2999 FEnd = Ovl->function_end();
3000 F != FEnd; ++F) {
3001 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3002 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3003 /*SuppressUserConversions=*/false);
3004 }
3005 }
3006
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003007 // C++ [over.call.object]p2:
3008 // In addition, for each conversion function declared in T of the
3009 // form
3010 //
3011 // operator conversion-type-id () cv-qualifier;
3012 //
3013 // where cv-qualifier is the same cv-qualification as, or a
3014 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003015 // denotes the type "pointer to function of (P1,...,Pn) returning
3016 // R", or the type "reference to pointer to function of
3017 // (P1,...,Pn) returning R", or the type "reference to function
3018 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003019 // is also considered as a candidate function. Similarly,
3020 // surrogate call functions are added to the set of candidate
3021 // functions for each conversion function declared in an
3022 // accessible base class provided the function is not hidden
3023 // within T by another intervening declaration.
3024 //
3025 // FIXME: Look in base classes for more conversion operators!
3026 OverloadedFunctionDecl *Conversions
3027 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003028 for (OverloadedFunctionDecl::function_iterator
3029 Func = Conversions->function_begin(),
3030 FuncEnd = Conversions->function_end();
3031 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003032 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3033
3034 // Strip the reference type (if any) and then the pointer type (if
3035 // any) to get down to what might be a function type.
3036 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3037 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3038 ConvType = ConvPtrType->getPointeeType();
3039
3040 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3041 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3042 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003043
3044 // Perform overload resolution.
3045 OverloadCandidateSet::iterator Best;
3046 switch (BestViableFunction(CandidateSet, Best)) {
3047 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003048 // Overload resolution succeeded; we'll build the appropriate call
3049 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003050 break;
3051
3052 case OR_No_Viable_Function:
3053 if (CandidateSet.empty())
3054 Diag(Object->getSourceRange().getBegin(),
3055 diag::err_ovl_no_viable_object_call)
3056 << Object->getType().getAsString() << Object->getSourceRange();
3057 else {
3058 Diag(Object->getSourceRange().getBegin(),
3059 diag::err_ovl_no_viable_object_call_with_cands)
3060 << Object->getType().getAsString() << Object->getSourceRange();
3061 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3062 }
3063 break;
3064
3065 case OR_Ambiguous:
3066 Diag(Object->getSourceRange().getBegin(),
3067 diag::err_ovl_ambiguous_object_call)
3068 << Object->getType().getAsString() << Object->getSourceRange();
3069 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3070 break;
3071 }
3072
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003073 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003074 // We had an error; delete all of the subexpressions and return
3075 // the error.
3076 delete Object;
3077 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3078 delete Args[ArgIdx];
3079 return true;
3080 }
3081
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003082 if (Best->Function == 0) {
3083 // Since there is no function declaration, this is one of the
3084 // surrogate candidates. Dig out the conversion function.
3085 CXXConversionDecl *Conv
3086 = cast<CXXConversionDecl>(
3087 Best->Conversions[0].UserDefined.ConversionFunction);
3088
3089 // We selected one of the surrogate functions that converts the
3090 // object parameter to a function pointer. Perform the conversion
3091 // on the object argument, then let ActOnCallExpr finish the job.
3092 // FIXME: Represent the user-defined conversion in the AST!
3093 ImpCastExprToType(Object,
3094 Conv->getConversionType().getNonReferenceType(),
3095 Conv->getConversionType()->isReferenceType());
3096 return ActOnCallExpr((ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs,
3097 CommaLocs, RParenLoc);
3098 }
3099
3100 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3101 // that calls this method, using Object for the implicit object
3102 // parameter and passing along the remaining arguments.
3103 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003104 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3105
3106 unsigned NumArgsInProto = Proto->getNumArgs();
3107 unsigned NumArgsToCheck = NumArgs;
3108
3109 // Build the full argument list for the method call (the
3110 // implicit object parameter is placed at the beginning of the
3111 // list).
3112 Expr **MethodArgs;
3113 if (NumArgs < NumArgsInProto) {
3114 NumArgsToCheck = NumArgsInProto;
3115 MethodArgs = new Expr*[NumArgsInProto + 1];
3116 } else {
3117 MethodArgs = new Expr*[NumArgs + 1];
3118 }
3119 MethodArgs[0] = Object;
3120 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3121 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3122
3123 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3124 SourceLocation());
3125 UsualUnaryConversions(NewFn);
3126
3127 // Once we've built TheCall, all of the expressions are properly
3128 // owned.
3129 QualType ResultTy = Method->getResultType().getNonReferenceType();
3130 llvm::OwningPtr<CXXOperatorCallExpr>
3131 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3132 ResultTy, RParenLoc));
3133 delete [] MethodArgs;
3134
3135 // Initialize the implicit object parameter.
3136 if (!PerformObjectArgumentInitialization(Object, Method))
3137 return true;
3138 TheCall->setArg(0, Object);
3139
3140 // Check the argument types.
3141 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3142 QualType ProtoArgType = Proto->getArgType(i);
3143
3144 Expr *Arg;
3145 if (i < NumArgs)
3146 Arg = Args[i];
3147 else
3148 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
3149 QualType ArgType = Arg->getType();
3150
3151 // Pass the argument.
3152 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3153 return true;
3154
3155 TheCall->setArg(i + 1, Arg);
3156 }
3157
3158 // If this is a variadic call, handle args passed through "...".
3159 if (Proto->isVariadic()) {
3160 // Promote the arguments (C99 6.5.2.2p7).
3161 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3162 Expr *Arg = Args[i];
3163 DefaultArgumentPromotion(Arg);
3164 TheCall->setArg(i + 1, Arg);
3165 }
3166 }
3167
3168 return CheckFunctionCall(Method, TheCall.take());
3169}
3170
Douglas Gregor8ba10742008-11-20 16:27:02 +00003171/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3172/// (if one exists), where @c Base is an expression of class type and
3173/// @c Member is the name of the member we're trying to find.
3174Action::ExprResult
3175Sema::BuildOverloadedArrowExpr(Expr *Base, SourceLocation OpLoc,
3176 SourceLocation MemberLoc,
3177 IdentifierInfo &Member) {
3178 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3179
3180 // C++ [over.ref]p1:
3181 //
3182 // [...] An expression x->m is interpreted as (x.operator->())->m
3183 // for a class object x of type T if T::operator->() exists and if
3184 // the operator is selected as the best match function by the
3185 // overload resolution mechanism (13.3).
3186 // FIXME: look in base classes.
3187 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3188 OverloadCandidateSet CandidateSet;
3189 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
3190 IdentifierResolver::iterator I
3191 = IdResolver.begin(OpName, cast<CXXRecordType>(BaseRecord)->getDecl(),
3192 /*LookInParentCtx=*/false);
3193 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
3194 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3195 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3196 /*SuppressUserConversions=*/false);
3197 else if (OverloadedFunctionDecl *Ovl
3198 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3199 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3200 FEnd = Ovl->function_end();
3201 F != FEnd; ++F) {
3202 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3203 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3204 /*SuppressUserConversions=*/false);
3205 }
3206 }
3207
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003208 llvm::OwningPtr<Expr> BasePtr(Base);
3209
Douglas Gregor8ba10742008-11-20 16:27:02 +00003210 // Perform overload resolution.
3211 OverloadCandidateSet::iterator Best;
3212 switch (BestViableFunction(CandidateSet, Best)) {
3213 case OR_Success:
3214 // Overload resolution succeeded; we'll build the call below.
3215 break;
3216
3217 case OR_No_Viable_Function:
3218 if (CandidateSet.empty())
3219 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003220 << BasePtr->getType().getAsString() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003221 else
3222 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003223 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003224 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003225 return true;
3226
3227 case OR_Ambiguous:
3228 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3229 << "operator->"
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003230 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003231 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003232 return true;
3233 }
3234
3235 // Convert the object parameter.
3236 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003237 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003238 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003239
3240 // No concerns about early exits now.
3241 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003242
3243 // Build the operator call.
3244 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3245 UsualUnaryConversions(FnExpr);
3246 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3247 Method->getResultType().getNonReferenceType(),
3248 OpLoc);
3249 return ActOnMemberReferenceExpr(Base, OpLoc, tok::arrow, MemberLoc, Member);
3250}
3251
Douglas Gregor904eed32008-11-10 20:40:00 +00003252/// FixOverloadedFunctionReference - E is an expression that refers to
3253/// a C++ overloaded function (possibly with some parentheses and
3254/// perhaps a '&' around it). We have resolved the overloaded function
3255/// to the function declaration Fn, so patch up the expression E to
3256/// refer (possibly indirectly) to Fn.
3257void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3258 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3259 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3260 E->setType(PE->getSubExpr()->getType());
3261 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3262 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3263 "Can only take the address of an overloaded function");
3264 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3265 E->setType(Context.getPointerType(E->getType()));
3266 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3267 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3268 "Expected overloaded function");
3269 DR->setDecl(Fn);
3270 E->setType(Fn->getType());
3271 } else {
3272 assert(false && "Invalid reference to overloaded function");
3273 }
3274}
3275
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003276} // end namespace clang