blob: fe4b763502a1e23500bb21f684c781650c45984c [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 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000213 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().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;
Douglas Gregor45920e82008-12-19 17:40:08 +0000422 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000423 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000424 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000425
426 // The first conversion can be an lvalue-to-rvalue conversion,
427 // array-to-pointer conversion, or function-to-pointer conversion
428 // (C++ 4p1).
429
430 // Lvalue-to-rvalue conversion (C++ 4.1):
431 // An lvalue (3.10) of a non-function, non-array type T can be
432 // converted to an rvalue.
433 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
434 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000435 !FromType->isFunctionType() && !FromType->isArrayType() &&
436 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000437 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000438
439 // If T is a non-class type, the type of the rvalue is the
440 // cv-unqualified version of T. Otherwise, the type of the rvalue
441 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000442 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000443 }
444 // Array-to-pointer conversion (C++ 4.2)
445 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000446 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000447
448 // An lvalue or rvalue of type "array of N T" or "array of unknown
449 // bound of T" can be converted to an rvalue of type "pointer to
450 // T" (C++ 4.2p1).
451 FromType = Context.getArrayDecayedType(FromType);
452
453 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
454 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000455 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000456
457 // For the purpose of ranking in overload resolution
458 // (13.3.3.1.1), this conversion is considered an
459 // array-to-pointer conversion followed by a qualification
460 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000461 SCS.Second = ICK_Identity;
462 SCS.Third = ICK_Qualification;
463 SCS.ToTypePtr = ToType.getAsOpaquePtr();
464 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000465 }
466 }
467 // Function-to-pointer conversion (C++ 4.3).
468 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000469 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000470
471 // An lvalue of function type T can be converted to an rvalue of
472 // type "pointer to T." The result is a pointer to the
473 // function. (C++ 4.3p1).
474 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000475 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000476 // Address of overloaded function (C++ [over.over]).
477 else if (FunctionDecl *Fn
478 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
479 SCS.First = ICK_Function_To_Pointer;
480
481 // We were able to resolve the address of the overloaded function,
482 // so we can convert to the type of that function.
483 FromType = Fn->getType();
484 if (ToType->isReferenceType())
485 FromType = Context.getReferenceType(FromType);
486 else
487 FromType = Context.getPointerType(FromType);
488 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000489 // We don't require any conversions for the first step.
490 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000491 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000492 }
493
494 // The second conversion can be an integral promotion, floating
495 // point promotion, integral conversion, floating point conversion,
496 // floating-integral conversion, pointer conversion,
497 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor45920e82008-12-19 17:40:08 +0000498 bool IncompatibleObjC = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000499 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
500 Context.getCanonicalType(ToType).getUnqualifiedType()) {
501 // The unqualified versions of the types are the same: there's no
502 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000503 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 }
505 // Integral promotion (C++ 4.5).
506 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000507 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000508 FromType = ToType.getUnqualifiedType();
509 }
510 // Floating point promotion (C++ 4.6).
511 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000512 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000513 FromType = ToType.getUnqualifiedType();
514 }
515 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000516 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000517 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000518 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000519 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000520 FromType = ToType.getUnqualifiedType();
521 }
522 // Floating point conversions (C++ 4.8).
523 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000524 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000525 FromType = ToType.getUnqualifiedType();
526 }
527 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000528 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000530 ToType->isIntegralType() && !ToType->isBooleanType() &&
531 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000532 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
533 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000534 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000535 FromType = ToType.getUnqualifiedType();
536 }
537 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000538 else if (IsPointerConversion(From, FromType, ToType, FromType,
539 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000540 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000541 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000542 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000543 // FIXME: Pointer to member conversions (4.11).
544 // Boolean conversions (C++ 4.12).
545 // FIXME: pointer-to-member type
546 else if (ToType->isBooleanType() &&
547 (FromType->isArithmeticType() ||
548 FromType->isEnumeralType() ||
549 FromType->isPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000550 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551 FromType = Context.BoolTy;
552 } else {
553 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000554 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000555 }
556
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000557 QualType CanonFrom;
558 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000559 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000560 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000561 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000562 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000563 CanonFrom = Context.getCanonicalType(FromType);
564 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000565 } else {
566 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000567 SCS.Third = ICK_Identity;
568
569 // C++ [over.best.ics]p6:
570 // [...] Any difference in top-level cv-qualification is
571 // subsumed by the initialization itself and does not constitute
572 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000573 CanonFrom = Context.getCanonicalType(FromType);
574 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000575 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000576 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
577 FromType = ToType;
578 CanonFrom = CanonTo;
579 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000580 }
581
582 // If we have not converted the argument type to the parameter type,
583 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000584 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000585 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000586
Douglas Gregor60d62c22008-10-31 16:23:19 +0000587 SCS.ToTypePtr = FromType.getAsOpaquePtr();
588 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000589}
590
591/// IsIntegralPromotion - Determines whether the conversion from the
592/// expression From (whose potentially-adjusted type is FromType) to
593/// ToType is an integral promotion (C++ 4.5). If so, returns true and
594/// sets PromotedType to the promoted type.
595bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
596{
597 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000598 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000599 if (!To) {
600 return false;
601 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000602
603 // An rvalue of type char, signed char, unsigned char, short int, or
604 // unsigned short int can be converted to an rvalue of type int if
605 // int can represent all the values of the source type; otherwise,
606 // the source rvalue can be converted to an rvalue of type unsigned
607 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000608 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000609 if (// We can promote any signed, promotable integer type to an int
610 (FromType->isSignedIntegerType() ||
611 // We can promote any unsigned integer type whose size is
612 // less than int to an int.
613 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000614 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000615 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000616 }
617
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000618 return To->getKind() == BuiltinType::UInt;
619 }
620
621 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
622 // can be converted to an rvalue of the first of the following types
623 // that can represent all the values of its underlying type: int,
624 // unsigned int, long, or unsigned long (C++ 4.5p2).
625 if ((FromType->isEnumeralType() || FromType->isWideCharType())
626 && ToType->isIntegerType()) {
627 // Determine whether the type we're converting from is signed or
628 // unsigned.
629 bool FromIsSigned;
630 uint64_t FromSize = Context.getTypeSize(FromType);
631 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
632 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
633 FromIsSigned = UnderlyingType->isSignedIntegerType();
634 } else {
635 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
636 FromIsSigned = true;
637 }
638
639 // The types we'll try to promote to, in the appropriate
640 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000641 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000642 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000643 Context.LongTy, Context.UnsignedLongTy ,
644 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000645 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000646 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000647 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
648 if (FromSize < ToSize ||
649 (FromSize == ToSize &&
650 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
651 // We found the type that we can promote to. If this is the
652 // type we wanted, we have a promotion. Otherwise, no
653 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000654 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000655 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
656 }
657 }
658 }
659
660 // An rvalue for an integral bit-field (9.6) can be converted to an
661 // rvalue of type int if int can represent all the values of the
662 // bit-field; otherwise, it can be converted to unsigned int if
663 // unsigned int can represent all the values of the bit-field. If
664 // the bit-field is larger yet, no integral promotion applies to
665 // it. If the bit-field has an enumerated type, it is treated as any
666 // other value of that type for promotion purposes (C++ 4.5p3).
667 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
668 using llvm::APSInt;
Douglas Gregor86f19402008-12-20 23:49:58 +0000669 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
670 APSInt BitWidth;
671 if (MemberDecl->isBitField() &&
672 FromType->isIntegralType() && !FromType->isEnumeralType() &&
673 From->isIntegerConstantExpr(BitWidth, Context)) {
674 APSInt ToSize(Context.getTypeSize(ToType));
675
676 // Are we promoting to an int from a bitfield that fits in an int?
677 if (BitWidth < ToSize ||
678 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
679 return To->getKind() == BuiltinType::Int;
680 }
681
682 // Are we promoting to an unsigned int from an unsigned bitfield
683 // that fits into an unsigned int?
684 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
685 return To->getKind() == BuiltinType::UInt;
686 }
687
688 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000689 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000690 }
691 }
692
693 // An rvalue of type bool can be converted to an rvalue of type int,
694 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000695 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000696 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000697 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000698
699 return false;
700}
701
702/// IsFloatingPointPromotion - Determines whether the conversion from
703/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
704/// returns true and sets PromotedType to the promoted type.
705bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
706{
707 /// An rvalue of type float can be converted to an rvalue of type
708 /// double. (C++ 4.6p1).
709 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
710 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
711 if (FromBuiltin->getKind() == BuiltinType::Float &&
712 ToBuiltin->getKind() == BuiltinType::Double)
713 return true;
714
715 return false;
716}
717
Douglas Gregorcb7de522008-11-26 23:31:11 +0000718/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
719/// the pointer type FromPtr to a pointer to type ToPointee, with the
720/// same type qualifiers as FromPtr has on its pointee type. ToType,
721/// if non-empty, will be a pointer to ToType that may or may not have
722/// the right set of qualifiers on its pointee.
723static QualType
724BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
725 QualType ToPointee, QualType ToType,
726 ASTContext &Context) {
727 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
728 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
729 unsigned Quals = CanonFromPointee.getCVRQualifiers();
730
731 // Exact qualifier match -> return the pointer type we're converting to.
732 if (CanonToPointee.getCVRQualifiers() == Quals) {
733 // ToType is exactly what we need. Return it.
734 if (ToType.getTypePtr())
735 return ToType;
736
737 // Build a pointer to ToPointee. It has the right qualifiers
738 // already.
739 return Context.getPointerType(ToPointee);
740 }
741
742 // Just build a canonical type that has the right qualifiers.
743 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
744}
745
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000746/// IsPointerConversion - Determines whether the conversion of the
747/// expression From, which has the (possibly adjusted) type FromType,
748/// can be converted to the type ToType via a pointer conversion (C++
749/// 4.10). If so, returns true and places the converted type (that
750/// might differ from ToType in its cv-qualifiers at some level) into
751/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000752///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000753/// This routine also supports conversions to and from block pointers
754/// and conversions with Objective-C's 'id', 'id<protocols...>', and
755/// pointers to interfaces. FIXME: Once we've determined the
756/// appropriate overloading rules for Objective-C, we may want to
757/// split the Objective-C checks into a different routine; however,
758/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000759/// conversions, so for now they live here. IncompatibleObjC will be
760/// set if the conversion is an allowed Objective-C conversion that
761/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000762bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000763 QualType& ConvertedType,
764 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000765{
Douglas Gregor45920e82008-12-19 17:40:08 +0000766 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000767 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
768 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000769
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000770 // Blocks: Block pointers can be converted to void*.
771 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
772 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
773 ConvertedType = ToType;
774 return true;
775 }
776 // Blocks: A null pointer constant can be converted to a block
777 // pointer type.
778 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
779 ConvertedType = ToType;
780 return true;
781 }
782
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000783 const PointerType* ToTypePtr = ToType->getAsPointerType();
784 if (!ToTypePtr)
785 return false;
786
787 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
788 if (From->isNullPointerConstant(Context)) {
789 ConvertedType = ToType;
790 return true;
791 }
Sebastian Redl07779722008-10-31 14:43:28 +0000792
Douglas Gregorcb7de522008-11-26 23:31:11 +0000793 // Beyond this point, both types need to be pointers.
794 const PointerType *FromTypePtr = FromType->getAsPointerType();
795 if (!FromTypePtr)
796 return false;
797
798 QualType FromPointeeType = FromTypePtr->getPointeeType();
799 QualType ToPointeeType = ToTypePtr->getPointeeType();
800
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000801 // An rvalue of type "pointer to cv T," where T is an object type,
802 // can be converted to an rvalue of type "pointer to cv void" (C++
803 // 4.10p2).
Douglas Gregorc7887512008-12-19 19:13:09 +0000804 if (FromPointeeType->isIncompleteOrObjectType() &&
805 ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000806 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
807 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000808 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000809 return true;
810 }
811
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000812 // C++ [conv.ptr]p3:
813 //
814 // An rvalue of type "pointer to cv D," where D is a class type,
815 // can be converted to an rvalue of type "pointer to cv B," where
816 // B is a base class (clause 10) of D. If B is an inaccessible
817 // (clause 11) or ambiguous (10.2) base class of D, a program that
818 // necessitates this conversion is ill-formed. The result of the
819 // conversion is a pointer to the base class sub-object of the
820 // derived class object. The null pointer value is converted to
821 // the null pointer value of the destination type.
822 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000823 // Note that we do not check for ambiguity or inaccessibility
824 // here. That is handled by CheckPointerConversion.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000825 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
826 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000827 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
828 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000829 ToType, Context);
830 return true;
831 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000832
Douglas Gregorc7887512008-12-19 19:13:09 +0000833 return false;
834}
835
836/// isObjCPointerConversion - Determines whether this is an
837/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
838/// with the same arguments and return values.
839bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
840 QualType& ConvertedType,
841 bool &IncompatibleObjC) {
842 if (!getLangOptions().ObjC1)
843 return false;
844
845 // Conversions with Objective-C's id<...>.
846 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
847 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
848 ConvertedType = ToType;
849 return true;
850 }
851
852 const PointerType* ToTypePtr = ToType->getAsPointerType();
853 if (!ToTypePtr)
854 return false;
855
856 // Beyond this point, both types need to be pointers.
857 const PointerType *FromTypePtr = FromType->getAsPointerType();
858 if (!FromTypePtr)
859 return false;
860
861 QualType FromPointeeType = FromTypePtr->getPointeeType();
862 QualType ToPointeeType = ToTypePtr->getPointeeType();
863
Douglas Gregorcb7de522008-11-26 23:31:11 +0000864 // Objective C++: We're able to convert from a pointer to an
865 // interface to a pointer to a different interface.
866 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
867 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
868 if (FromIface && ToIface &&
869 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000870 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
871 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000872 ToType, Context);
873 return true;
874 }
875
Douglas Gregor45920e82008-12-19 17:40:08 +0000876 if (FromIface && ToIface &&
877 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
878 // Okay: this is some kind of implicit downcast of Objective-C
879 // interfaces, which is permitted. However, we're going to
880 // complain about it.
881 IncompatibleObjC = true;
882 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
883 ToPointeeType,
884 ToType, Context);
885 return true;
886 }
887
Douglas Gregorcb7de522008-11-26 23:31:11 +0000888 // Objective C++: We're able to convert between "id" and a pointer
889 // to any interface (in both directions).
890 if ((FromIface && Context.isObjCIdType(ToPointeeType))
891 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000892 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
893 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000894 ToType, Context);
895 return true;
896 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000897
Douglas Gregordda78892008-12-18 23:43:31 +0000898 // Objective C++: Allow conversions between the Objective-C "id" and
899 // "Class", in either direction.
900 if ((Context.isObjCIdType(FromPointeeType) &&
901 Context.isObjCClassType(ToPointeeType)) ||
902 (Context.isObjCClassType(FromPointeeType) &&
903 Context.isObjCIdType(ToPointeeType))) {
904 ConvertedType = ToType;
905 return true;
906 }
907
Douglas Gregorc7887512008-12-19 19:13:09 +0000908 // If we have pointers to pointers, recursively check whether this
909 // is an Objective-C conversion.
910 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
911 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
912 IncompatibleObjC)) {
913 // We always complain about this conversion.
914 IncompatibleObjC = true;
915 ConvertedType = ToType;
916 return true;
917 }
918
919 // If we have pointers to functions, check whether the only
920 // differences in the argument and result types are in Objective-C
921 // pointer conversions. If so, we permit the conversion (but
922 // complain about it).
923 const FunctionTypeProto *FromFunctionType
924 = FromPointeeType->getAsFunctionTypeProto();
925 const FunctionTypeProto *ToFunctionType
926 = ToPointeeType->getAsFunctionTypeProto();
927 if (FromFunctionType && ToFunctionType) {
928 // If the function types are exactly the same, this isn't an
929 // Objective-C pointer conversion.
930 if (Context.getCanonicalType(FromPointeeType)
931 == Context.getCanonicalType(ToPointeeType))
932 return false;
933
934 // Perform the quick checks that will tell us whether these
935 // function types are obviously different.
936 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
937 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
938 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
939 return false;
940
941 bool HasObjCConversion = false;
942 if (Context.getCanonicalType(FromFunctionType->getResultType())
943 == Context.getCanonicalType(ToFunctionType->getResultType())) {
944 // Okay, the types match exactly. Nothing to do.
945 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
946 ToFunctionType->getResultType(),
947 ConvertedType, IncompatibleObjC)) {
948 // Okay, we have an Objective-C pointer conversion.
949 HasObjCConversion = true;
950 } else {
951 // Function types are too different. Abort.
952 return false;
953 }
954
955 // Check argument types.
956 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
957 ArgIdx != NumArgs; ++ArgIdx) {
958 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
959 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
960 if (Context.getCanonicalType(FromArgType)
961 == Context.getCanonicalType(ToArgType)) {
962 // Okay, the types match exactly. Nothing to do.
963 } else if (isObjCPointerConversion(FromArgType, ToArgType,
964 ConvertedType, IncompatibleObjC)) {
965 // Okay, we have an Objective-C pointer conversion.
966 HasObjCConversion = true;
967 } else {
968 // Argument types are too different. Abort.
969 return false;
970 }
971 }
972
973 if (HasObjCConversion) {
974 // We had an Objective-C conversion. Allow this pointer
975 // conversion, but complain about it.
976 ConvertedType = ToType;
977 IncompatibleObjC = true;
978 return true;
979 }
980 }
981
982 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000983}
984
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000985/// CheckPointerConversion - Check the pointer conversion from the
986/// expression From to the type ToType. This routine checks for
987/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
988/// conversions for which IsPointerConversion has already returned
989/// true. It returns true and produces a diagnostic if there was an
990/// error, or returns false otherwise.
991bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
992 QualType FromType = From->getType();
993
994 if (const PointerType *FromPtrType = FromType->getAsPointerType())
995 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl07779722008-10-31 14:43:28 +0000996 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
997 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000998 QualType FromPointeeType = FromPtrType->getPointeeType(),
999 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001000
1001 // Objective-C++ conversions are always okay.
1002 // FIXME: We should have a different class of conversions for
1003 // the Objective-C++ implicit conversions.
1004 if (Context.isObjCIdType(FromPointeeType) ||
1005 Context.isObjCIdType(ToPointeeType) ||
1006 Context.isObjCClassType(FromPointeeType) ||
1007 Context.isObjCClassType(ToPointeeType))
1008 return false;
1009
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001010 if (FromPointeeType->isRecordType() &&
1011 ToPointeeType->isRecordType()) {
1012 // We must have a derived-to-base conversion. Check an
1013 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001014 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1015 From->getExprLoc(),
1016 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001017 }
1018 }
1019
1020 return false;
1021}
1022
Douglas Gregor98cd5992008-10-21 23:43:52 +00001023/// IsQualificationConversion - Determines whether the conversion from
1024/// an rvalue of type FromType to ToType is a qualification conversion
1025/// (C++ 4.4).
1026bool
1027Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1028{
1029 FromType = Context.getCanonicalType(FromType);
1030 ToType = Context.getCanonicalType(ToType);
1031
1032 // If FromType and ToType are the same type, this is not a
1033 // qualification conversion.
1034 if (FromType == ToType)
1035 return false;
1036
1037 // (C++ 4.4p4):
1038 // A conversion can add cv-qualifiers at levels other than the first
1039 // in multi-level pointers, subject to the following rules: [...]
1040 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001041 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001042 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001043 // Within each iteration of the loop, we check the qualifiers to
1044 // determine if this still looks like a qualification
1045 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001046 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001047 // until there are no more pointers or pointers-to-members left to
1048 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001049 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001050
1051 // -- for every j > 0, if const is in cv 1,j then const is in cv
1052 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001053 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001054 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001055
Douglas Gregor98cd5992008-10-21 23:43:52 +00001056 // -- if the cv 1,j and cv 2,j are different, then const is in
1057 // every cv for 0 < k < j.
1058 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001059 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001060 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001061
Douglas Gregor98cd5992008-10-21 23:43:52 +00001062 // Keep track of whether all prior cv-qualifiers in the "to" type
1063 // include const.
1064 PreviousToQualsIncludeConst
1065 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001066 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001067
1068 // We are left with FromType and ToType being the pointee types
1069 // after unwrapping the original FromType and ToType the same number
1070 // of types. If we unwrapped any pointers, and if FromType and
1071 // ToType have the same unqualified type (since we checked
1072 // qualifiers above), then this is a qualification conversion.
1073 return UnwrappedAnyPointer &&
1074 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1075}
1076
Douglas Gregor60d62c22008-10-31 16:23:19 +00001077/// IsUserDefinedConversion - Determines whether there is a
1078/// user-defined conversion sequence (C++ [over.ics.user]) that
1079/// converts expression From to the type ToType. If such a conversion
1080/// exists, User will contain the user-defined conversion sequence
1081/// that performs such a conversion and this routine will return
1082/// true. Otherwise, this routine returns false and User is
1083/// unspecified.
1084bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1085 UserDefinedConversionSequence& User)
1086{
1087 OverloadCandidateSet CandidateSet;
1088 if (const CXXRecordType *ToRecordType
1089 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
1090 // C++ [over.match.ctor]p1:
1091 // When objects of class type are direct-initialized (8.5), or
1092 // copy-initialized from an expression of the same or a
1093 // derived class type (8.5), overload resolution selects the
1094 // constructor. [...] For copy-initialization, the candidate
1095 // functions are all the converting constructors (12.3.1) of
1096 // that class. The argument list is the expression-list within
1097 // the parentheses of the initializer.
1098 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001099 DeclarationName ConstructorName
1100 = Context.DeclarationNames.getCXXConstructorName(
1101 Context.getCanonicalType(ToType));
1102 DeclContext::lookup_result Lookup
1103 = ToRecordDecl->lookup(Context, ConstructorName);
1104 if (Lookup.first == Lookup.second)
1105 /* No constructors. FIXME: Implicit copy constructor? */;
1106 else if (OverloadedFunctionDecl *Constructors
1107 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first)) {
1108 for (OverloadedFunctionDecl::function_const_iterator func
1109 = Constructors->function_begin();
1110 func != Constructors->function_end(); ++func) {
1111 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
1112 if (Constructor->isConvertingConstructor())
1113 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1114 /*SuppressUserConversions=*/true);
1115 }
1116 } else if (CXXConstructorDecl *Constructor
1117 = dyn_cast<CXXConstructorDecl>(*Lookup.first)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001118 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +00001119 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1120 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001121 }
1122 }
1123
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001124 if (const CXXRecordType *FromRecordType
1125 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
1126 // Add all of the conversion functions as candidates.
1127 // FIXME: Look for conversions in base classes!
1128 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
1129 OverloadedFunctionDecl *Conversions
1130 = FromRecordDecl->getConversionFunctions();
1131 for (OverloadedFunctionDecl::function_iterator Func
1132 = Conversions->function_begin();
1133 Func != Conversions->function_end(); ++Func) {
1134 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1135 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1136 }
1137 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001138
1139 OverloadCandidateSet::iterator Best;
1140 switch (BestViableFunction(CandidateSet, Best)) {
1141 case OR_Success:
1142 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001143 if (CXXConstructorDecl *Constructor
1144 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1145 // C++ [over.ics.user]p1:
1146 // If the user-defined conversion is specified by a
1147 // constructor (12.3.1), the initial standard conversion
1148 // sequence converts the source type to the type required by
1149 // the argument of the constructor.
1150 //
1151 // FIXME: What about ellipsis conversions?
1152 QualType ThisType = Constructor->getThisType(Context);
1153 User.Before = Best->Conversions[0].Standard;
1154 User.ConversionFunction = Constructor;
1155 User.After.setAsIdentityConversion();
1156 User.After.FromTypePtr
1157 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1158 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1159 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001160 } else if (CXXConversionDecl *Conversion
1161 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1162 // C++ [over.ics.user]p1:
1163 //
1164 // [...] If the user-defined conversion is specified by a
1165 // conversion function (12.3.2), the initial standard
1166 // conversion sequence converts the source type to the
1167 // implicit object parameter of the conversion function.
1168 User.Before = Best->Conversions[0].Standard;
1169 User.ConversionFunction = Conversion;
1170
1171 // C++ [over.ics.user]p2:
1172 // The second standard conversion sequence converts the
1173 // result of the user-defined conversion to the target type
1174 // for the sequence. Since an implicit conversion sequence
1175 // is an initialization, the special rules for
1176 // initialization by user-defined conversion apply when
1177 // selecting the best user-defined conversion for a
1178 // user-defined conversion sequence (see 13.3.3 and
1179 // 13.3.3.1).
1180 User.After = Best->FinalConversion;
1181 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001182 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001183 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001184 return false;
1185 }
1186
1187 case OR_No_Viable_Function:
1188 // No conversion here! We're done.
1189 return false;
1190
1191 case OR_Ambiguous:
1192 // FIXME: See C++ [over.best.ics]p10 for the handling of
1193 // ambiguous conversion sequences.
1194 return false;
1195 }
1196
1197 return false;
1198}
1199
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001200/// CompareImplicitConversionSequences - Compare two implicit
1201/// conversion sequences to determine whether one is better than the
1202/// other or if they are indistinguishable (C++ 13.3.3.2).
1203ImplicitConversionSequence::CompareKind
1204Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1205 const ImplicitConversionSequence& ICS2)
1206{
1207 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1208 // conversion sequences (as defined in 13.3.3.1)
1209 // -- a standard conversion sequence (13.3.3.1.1) is a better
1210 // conversion sequence than a user-defined conversion sequence or
1211 // an ellipsis conversion sequence, and
1212 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1213 // conversion sequence than an ellipsis conversion sequence
1214 // (13.3.3.1.3).
1215 //
1216 if (ICS1.ConversionKind < ICS2.ConversionKind)
1217 return ImplicitConversionSequence::Better;
1218 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1219 return ImplicitConversionSequence::Worse;
1220
1221 // Two implicit conversion sequences of the same form are
1222 // indistinguishable conversion sequences unless one of the
1223 // following rules apply: (C++ 13.3.3.2p3):
1224 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1225 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1226 else if (ICS1.ConversionKind ==
1227 ImplicitConversionSequence::UserDefinedConversion) {
1228 // User-defined conversion sequence U1 is a better conversion
1229 // sequence than another user-defined conversion sequence U2 if
1230 // they contain the same user-defined conversion function or
1231 // constructor and if the second standard conversion sequence of
1232 // U1 is better than the second standard conversion sequence of
1233 // U2 (C++ 13.3.3.2p3).
1234 if (ICS1.UserDefined.ConversionFunction ==
1235 ICS2.UserDefined.ConversionFunction)
1236 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1237 ICS2.UserDefined.After);
1238 }
1239
1240 return ImplicitConversionSequence::Indistinguishable;
1241}
1242
1243/// CompareStandardConversionSequences - Compare two standard
1244/// conversion sequences to determine whether one is better than the
1245/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1246ImplicitConversionSequence::CompareKind
1247Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1248 const StandardConversionSequence& SCS2)
1249{
1250 // Standard conversion sequence S1 is a better conversion sequence
1251 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1252
1253 // -- S1 is a proper subsequence of S2 (comparing the conversion
1254 // sequences in the canonical form defined by 13.3.3.1.1,
1255 // excluding any Lvalue Transformation; the identity conversion
1256 // sequence is considered to be a subsequence of any
1257 // non-identity conversion sequence) or, if not that,
1258 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1259 // Neither is a proper subsequence of the other. Do nothing.
1260 ;
1261 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1262 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1263 (SCS1.Second == ICK_Identity &&
1264 SCS1.Third == ICK_Identity))
1265 // SCS1 is a proper subsequence of SCS2.
1266 return ImplicitConversionSequence::Better;
1267 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1268 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1269 (SCS2.Second == ICK_Identity &&
1270 SCS2.Third == ICK_Identity))
1271 // SCS2 is a proper subsequence of SCS1.
1272 return ImplicitConversionSequence::Worse;
1273
1274 // -- the rank of S1 is better than the rank of S2 (by the rules
1275 // defined below), or, if not that,
1276 ImplicitConversionRank Rank1 = SCS1.getRank();
1277 ImplicitConversionRank Rank2 = SCS2.getRank();
1278 if (Rank1 < Rank2)
1279 return ImplicitConversionSequence::Better;
1280 else if (Rank2 < Rank1)
1281 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001282
Douglas Gregor57373262008-10-22 14:17:15 +00001283 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1284 // are indistinguishable unless one of the following rules
1285 // applies:
1286
1287 // A conversion that is not a conversion of a pointer, or
1288 // pointer to member, to bool is better than another conversion
1289 // that is such a conversion.
1290 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1291 return SCS2.isPointerConversionToBool()
1292 ? ImplicitConversionSequence::Better
1293 : ImplicitConversionSequence::Worse;
1294
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001295 // C++ [over.ics.rank]p4b2:
1296 //
1297 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001298 // conversion of B* to A* is better than conversion of B* to
1299 // void*, and conversion of A* to void* is better than conversion
1300 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001301 bool SCS1ConvertsToVoid
1302 = SCS1.isPointerConversionToVoidPointer(Context);
1303 bool SCS2ConvertsToVoid
1304 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001305 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1306 // Exactly one of the conversion sequences is a conversion to
1307 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001308 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1309 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001310 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1311 // Neither conversion sequence converts to a void pointer; compare
1312 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001313 if (ImplicitConversionSequence::CompareKind DerivedCK
1314 = CompareDerivedToBaseConversions(SCS1, SCS2))
1315 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001316 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1317 // Both conversion sequences are conversions to void
1318 // pointers. Compare the source types to determine if there's an
1319 // inheritance relationship in their sources.
1320 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1321 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1322
1323 // Adjust the types we're converting from via the array-to-pointer
1324 // conversion, if we need to.
1325 if (SCS1.First == ICK_Array_To_Pointer)
1326 FromType1 = Context.getArrayDecayedType(FromType1);
1327 if (SCS2.First == ICK_Array_To_Pointer)
1328 FromType2 = Context.getArrayDecayedType(FromType2);
1329
1330 QualType FromPointee1
1331 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1332 QualType FromPointee2
1333 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1334
1335 if (IsDerivedFrom(FromPointee2, FromPointee1))
1336 return ImplicitConversionSequence::Better;
1337 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1338 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001339
1340 // Objective-C++: If one interface is more specific than the
1341 // other, it is the better one.
1342 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1343 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1344 if (FromIface1 && FromIface1) {
1345 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1346 return ImplicitConversionSequence::Better;
1347 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1348 return ImplicitConversionSequence::Worse;
1349 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001350 }
Douglas Gregor57373262008-10-22 14:17:15 +00001351
1352 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1353 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001354 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001355 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001356 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001357
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001358 // C++ [over.ics.rank]p3b4:
1359 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1360 // which the references refer are the same type except for
1361 // top-level cv-qualifiers, and the type to which the reference
1362 // initialized by S2 refers is more cv-qualified than the type
1363 // to which the reference initialized by S1 refers.
1364 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1365 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1366 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1367 T1 = Context.getCanonicalType(T1);
1368 T2 = Context.getCanonicalType(T2);
1369 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1370 if (T2.isMoreQualifiedThan(T1))
1371 return ImplicitConversionSequence::Better;
1372 else if (T1.isMoreQualifiedThan(T2))
1373 return ImplicitConversionSequence::Worse;
1374 }
1375 }
Douglas Gregor57373262008-10-22 14:17:15 +00001376
1377 return ImplicitConversionSequence::Indistinguishable;
1378}
1379
1380/// CompareQualificationConversions - Compares two standard conversion
1381/// sequences to determine whether they can be ranked based on their
1382/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1383ImplicitConversionSequence::CompareKind
1384Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1385 const StandardConversionSequence& SCS2)
1386{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001387 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001388 // -- S1 and S2 differ only in their qualification conversion and
1389 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1390 // cv-qualification signature of type T1 is a proper subset of
1391 // the cv-qualification signature of type T2, and S1 is not the
1392 // deprecated string literal array-to-pointer conversion (4.2).
1393 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1394 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1395 return ImplicitConversionSequence::Indistinguishable;
1396
1397 // FIXME: the example in the standard doesn't use a qualification
1398 // conversion (!)
1399 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1400 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1401 T1 = Context.getCanonicalType(T1);
1402 T2 = Context.getCanonicalType(T2);
1403
1404 // If the types are the same, we won't learn anything by unwrapped
1405 // them.
1406 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1407 return ImplicitConversionSequence::Indistinguishable;
1408
1409 ImplicitConversionSequence::CompareKind Result
1410 = ImplicitConversionSequence::Indistinguishable;
1411 while (UnwrapSimilarPointerTypes(T1, T2)) {
1412 // Within each iteration of the loop, we check the qualifiers to
1413 // determine if this still looks like a qualification
1414 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001415 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001416 // until there are no more pointers or pointers-to-members left
1417 // to unwrap. This essentially mimics what
1418 // IsQualificationConversion does, but here we're checking for a
1419 // strict subset of qualifiers.
1420 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1421 // The qualifiers are the same, so this doesn't tell us anything
1422 // about how the sequences rank.
1423 ;
1424 else if (T2.isMoreQualifiedThan(T1)) {
1425 // T1 has fewer qualifiers, so it could be the better sequence.
1426 if (Result == ImplicitConversionSequence::Worse)
1427 // Neither has qualifiers that are a subset of the other's
1428 // qualifiers.
1429 return ImplicitConversionSequence::Indistinguishable;
1430
1431 Result = ImplicitConversionSequence::Better;
1432 } else if (T1.isMoreQualifiedThan(T2)) {
1433 // T2 has fewer qualifiers, so it could be the better sequence.
1434 if (Result == ImplicitConversionSequence::Better)
1435 // Neither has qualifiers that are a subset of the other's
1436 // qualifiers.
1437 return ImplicitConversionSequence::Indistinguishable;
1438
1439 Result = ImplicitConversionSequence::Worse;
1440 } else {
1441 // Qualifiers are disjoint.
1442 return ImplicitConversionSequence::Indistinguishable;
1443 }
1444
1445 // If the types after this point are equivalent, we're done.
1446 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1447 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001448 }
1449
Douglas Gregor57373262008-10-22 14:17:15 +00001450 // Check that the winning standard conversion sequence isn't using
1451 // the deprecated string literal array to pointer conversion.
1452 switch (Result) {
1453 case ImplicitConversionSequence::Better:
1454 if (SCS1.Deprecated)
1455 Result = ImplicitConversionSequence::Indistinguishable;
1456 break;
1457
1458 case ImplicitConversionSequence::Indistinguishable:
1459 break;
1460
1461 case ImplicitConversionSequence::Worse:
1462 if (SCS2.Deprecated)
1463 Result = ImplicitConversionSequence::Indistinguishable;
1464 break;
1465 }
1466
1467 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001468}
1469
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001470/// CompareDerivedToBaseConversions - Compares two standard conversion
1471/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001472/// various kinds of derived-to-base conversions (C++
1473/// [over.ics.rank]p4b3). As part of these checks, we also look at
1474/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001475ImplicitConversionSequence::CompareKind
1476Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1477 const StandardConversionSequence& SCS2) {
1478 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1479 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1480 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1481 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1482
1483 // Adjust the types we're converting from via the array-to-pointer
1484 // conversion, if we need to.
1485 if (SCS1.First == ICK_Array_To_Pointer)
1486 FromType1 = Context.getArrayDecayedType(FromType1);
1487 if (SCS2.First == ICK_Array_To_Pointer)
1488 FromType2 = Context.getArrayDecayedType(FromType2);
1489
1490 // Canonicalize all of the types.
1491 FromType1 = Context.getCanonicalType(FromType1);
1492 ToType1 = Context.getCanonicalType(ToType1);
1493 FromType2 = Context.getCanonicalType(FromType2);
1494 ToType2 = Context.getCanonicalType(ToType2);
1495
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001496 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001497 //
1498 // If class B is derived directly or indirectly from class A and
1499 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001500 //
1501 // For Objective-C, we let A, B, and C also be Objective-C
1502 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001503
1504 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001505 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001506 SCS2.Second == ICK_Pointer_Conversion &&
1507 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1508 FromType1->isPointerType() && FromType2->isPointerType() &&
1509 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001510 QualType FromPointee1
1511 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1512 QualType ToPointee1
1513 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1514 QualType FromPointee2
1515 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1516 QualType ToPointee2
1517 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001518
1519 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1520 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1521 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1522 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1523
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001524 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001525 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1526 if (IsDerivedFrom(ToPointee1, ToPointee2))
1527 return ImplicitConversionSequence::Better;
1528 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1529 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001530
1531 if (ToIface1 && ToIface2) {
1532 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1533 return ImplicitConversionSequence::Better;
1534 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1535 return ImplicitConversionSequence::Worse;
1536 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001537 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001538
1539 // -- conversion of B* to A* is better than conversion of C* to A*,
1540 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1541 if (IsDerivedFrom(FromPointee2, FromPointee1))
1542 return ImplicitConversionSequence::Better;
1543 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1544 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001545
1546 if (FromIface1 && FromIface2) {
1547 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1548 return ImplicitConversionSequence::Better;
1549 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1550 return ImplicitConversionSequence::Worse;
1551 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001552 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001553 }
1554
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001555 // Compare based on reference bindings.
1556 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1557 SCS1.Second == ICK_Derived_To_Base) {
1558 // -- binding of an expression of type C to a reference of type
1559 // B& is better than binding an expression of type C to a
1560 // reference of type A&,
1561 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1562 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1563 if (IsDerivedFrom(ToType1, ToType2))
1564 return ImplicitConversionSequence::Better;
1565 else if (IsDerivedFrom(ToType2, ToType1))
1566 return ImplicitConversionSequence::Worse;
1567 }
1568
Douglas Gregor225c41e2008-11-03 19:09:14 +00001569 // -- binding of an expression of type B to a reference of type
1570 // A& is better than binding an expression of type C to a
1571 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001572 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1573 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1574 if (IsDerivedFrom(FromType2, FromType1))
1575 return ImplicitConversionSequence::Better;
1576 else if (IsDerivedFrom(FromType1, FromType2))
1577 return ImplicitConversionSequence::Worse;
1578 }
1579 }
1580
1581
1582 // FIXME: conversion of A::* to B::* is better than conversion of
1583 // A::* to C::*,
1584
1585 // FIXME: conversion of B::* to C::* is better than conversion of
1586 // A::* to C::*, and
1587
Douglas Gregor225c41e2008-11-03 19:09:14 +00001588 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1589 SCS1.Second == ICK_Derived_To_Base) {
1590 // -- conversion of C to B is better than conversion of C to A,
1591 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1592 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1593 if (IsDerivedFrom(ToType1, ToType2))
1594 return ImplicitConversionSequence::Better;
1595 else if (IsDerivedFrom(ToType2, ToType1))
1596 return ImplicitConversionSequence::Worse;
1597 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001598
Douglas Gregor225c41e2008-11-03 19:09:14 +00001599 // -- conversion of B to A is better than conversion of C to A.
1600 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1601 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1602 if (IsDerivedFrom(FromType2, FromType1))
1603 return ImplicitConversionSequence::Better;
1604 else if (IsDerivedFrom(FromType1, FromType2))
1605 return ImplicitConversionSequence::Worse;
1606 }
1607 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001608
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001609 return ImplicitConversionSequence::Indistinguishable;
1610}
1611
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001612/// TryCopyInitialization - Try to copy-initialize a value of type
1613/// ToType from the expression From. Return the implicit conversion
1614/// sequence required to pass this argument, which may be a bad
1615/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001616/// a parameter of this type). If @p SuppressUserConversions, then we
1617/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001618ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001619Sema::TryCopyInitialization(Expr *From, QualType ToType,
1620 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001621 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001622 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001623 AssignConvertType ConvTy =
1624 CheckSingleAssignmentConstraints(ToType, From);
1625 ImplicitConversionSequence ICS;
1626 if (getLangOptions().NoExtensions? ConvTy != Compatible
1627 : ConvTy == Incompatible)
1628 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1629 else
1630 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1631 return ICS;
1632 } else if (ToType->isReferenceType()) {
1633 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001634 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001635 return ICS;
1636 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001637 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001638 }
1639}
1640
1641/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1642/// type ToType. Returns true (and emits a diagnostic) if there was
1643/// an error, returns false if the initialization succeeded.
1644bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1645 const char* Flavor) {
1646 if (!getLangOptions().CPlusPlus) {
1647 // In C, argument passing is the same as performing an assignment.
1648 QualType FromType = From->getType();
1649 AssignConvertType ConvTy =
1650 CheckSingleAssignmentConstraints(ToType, From);
1651
1652 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1653 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001654 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001655
1656 if (ToType->isReferenceType())
1657 return CheckReferenceInit(From, ToType);
1658
Douglas Gregor45920e82008-12-19 17:40:08 +00001659 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001660 return false;
1661
1662 return Diag(From->getSourceRange().getBegin(),
1663 diag::err_typecheck_convert_incompatible)
1664 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001665}
1666
Douglas Gregor96176b32008-11-18 23:14:02 +00001667/// TryObjectArgumentInitialization - Try to initialize the object
1668/// parameter of the given member function (@c Method) from the
1669/// expression @p From.
1670ImplicitConversionSequence
1671Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1672 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1673 unsigned MethodQuals = Method->getTypeQualifiers();
1674 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1675
1676 // Set up the conversion sequence as a "bad" conversion, to allow us
1677 // to exit early.
1678 ImplicitConversionSequence ICS;
1679 ICS.Standard.setAsIdentityConversion();
1680 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1681
1682 // We need to have an object of class type.
1683 QualType FromType = From->getType();
1684 if (!FromType->isRecordType())
1685 return ICS;
1686
1687 // The implicit object parmeter is has the type "reference to cv X",
1688 // where X is the class of which the function is a member
1689 // (C++ [over.match.funcs]p4). However, when finding an implicit
1690 // conversion sequence for the argument, we are not allowed to
1691 // create temporaries or perform user-defined conversions
1692 // (C++ [over.match.funcs]p5). We perform a simplified version of
1693 // reference binding here, that allows class rvalues to bind to
1694 // non-constant references.
1695
1696 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1697 // with the implicit object parameter (C++ [over.match.funcs]p5).
1698 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1699 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1700 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1701 return ICS;
1702
1703 // Check that we have either the same type or a derived type. It
1704 // affects the conversion rank.
1705 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1706 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1707 ICS.Standard.Second = ICK_Identity;
1708 else if (IsDerivedFrom(FromType, ClassType))
1709 ICS.Standard.Second = ICK_Derived_To_Base;
1710 else
1711 return ICS;
1712
1713 // Success. Mark this as a reference binding.
1714 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1715 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1716 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1717 ICS.Standard.ReferenceBinding = true;
1718 ICS.Standard.DirectBinding = true;
1719 return ICS;
1720}
1721
1722/// PerformObjectArgumentInitialization - Perform initialization of
1723/// the implicit object parameter for the given Method with the given
1724/// expression.
1725bool
1726Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1727 QualType ImplicitParamType
1728 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1729 ImplicitConversionSequence ICS
1730 = TryObjectArgumentInitialization(From, Method);
1731 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1732 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001733 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001734 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001735
1736 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1737 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1738 From->getSourceRange().getBegin(),
1739 From->getSourceRange()))
1740 return true;
1741
1742 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1743 return false;
1744}
1745
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001746/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001747/// candidate functions, using the given function call arguments. If
1748/// @p SuppressUserConversions, then don't allow user-defined
1749/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001750void
1751Sema::AddOverloadCandidate(FunctionDecl *Function,
1752 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001753 OverloadCandidateSet& CandidateSet,
1754 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001755{
1756 const FunctionTypeProto* Proto
1757 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1758 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001759 assert(!isa<CXXConversionDecl>(Function) &&
1760 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001761
1762 // Add this candidate
1763 CandidateSet.push_back(OverloadCandidate());
1764 OverloadCandidate& Candidate = CandidateSet.back();
1765 Candidate.Function = Function;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001766 Candidate.IsSurrogate = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001767
1768 unsigned NumArgsInProto = Proto->getNumArgs();
1769
1770 // (C++ 13.3.2p2): A candidate function having fewer than m
1771 // parameters is viable only if it has an ellipsis in its parameter
1772 // list (8.3.5).
1773 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1774 Candidate.Viable = false;
1775 return;
1776 }
1777
1778 // (C++ 13.3.2p2): A candidate function having more than m parameters
1779 // is viable only if the (m+1)st parameter has a default argument
1780 // (8.3.6). For the purposes of overload resolution, the
1781 // parameter list is truncated on the right, so that there are
1782 // exactly m parameters.
1783 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1784 if (NumArgs < MinRequiredArgs) {
1785 // Not enough arguments.
1786 Candidate.Viable = false;
1787 return;
1788 }
1789
1790 // Determine the implicit conversion sequences for each of the
1791 // arguments.
1792 Candidate.Viable = true;
1793 Candidate.Conversions.resize(NumArgs);
1794 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1795 if (ArgIdx < NumArgsInProto) {
1796 // (C++ 13.3.2p3): for F to be a viable function, there shall
1797 // exist for each argument an implicit conversion sequence
1798 // (13.3.3.1) that converts that argument to the corresponding
1799 // parameter of F.
1800 QualType ParamType = Proto->getArgType(ArgIdx);
1801 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001802 = TryCopyInitialization(Args[ArgIdx], ParamType,
1803 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001804 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001805 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001806 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001807 break;
1808 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001809 } else {
1810 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1811 // argument for which there is no corresponding parameter is
1812 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1813 Candidate.Conversions[ArgIdx].ConversionKind
1814 = ImplicitConversionSequence::EllipsisConversion;
1815 }
1816 }
1817}
1818
Douglas Gregor96176b32008-11-18 23:14:02 +00001819/// AddMethodCandidate - Adds the given C++ member function to the set
1820/// of candidate functions, using the given function call arguments
1821/// and the object argument (@c Object). For example, in a call
1822/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1823/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1824/// allow user-defined conversions via constructors or conversion
1825/// operators.
1826void
1827Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1828 Expr **Args, unsigned NumArgs,
1829 OverloadCandidateSet& CandidateSet,
1830 bool SuppressUserConversions)
1831{
1832 const FunctionTypeProto* Proto
1833 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1834 assert(Proto && "Methods without a prototype cannot be overloaded");
1835 assert(!isa<CXXConversionDecl>(Method) &&
1836 "Use AddConversionCandidate for conversion functions");
1837
1838 // Add this candidate
1839 CandidateSet.push_back(OverloadCandidate());
1840 OverloadCandidate& Candidate = CandidateSet.back();
1841 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001842 Candidate.IsSurrogate = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001843
1844 unsigned NumArgsInProto = Proto->getNumArgs();
1845
1846 // (C++ 13.3.2p2): A candidate function having fewer than m
1847 // parameters is viable only if it has an ellipsis in its parameter
1848 // list (8.3.5).
1849 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1850 Candidate.Viable = false;
1851 return;
1852 }
1853
1854 // (C++ 13.3.2p2): A candidate function having more than m parameters
1855 // is viable only if the (m+1)st parameter has a default argument
1856 // (8.3.6). For the purposes of overload resolution, the
1857 // parameter list is truncated on the right, so that there are
1858 // exactly m parameters.
1859 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1860 if (NumArgs < MinRequiredArgs) {
1861 // Not enough arguments.
1862 Candidate.Viable = false;
1863 return;
1864 }
1865
1866 Candidate.Viable = true;
1867 Candidate.Conversions.resize(NumArgs + 1);
1868
1869 // Determine the implicit conversion sequence for the object
1870 // parameter.
1871 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1872 if (Candidate.Conversions[0].ConversionKind
1873 == ImplicitConversionSequence::BadConversion) {
1874 Candidate.Viable = false;
1875 return;
1876 }
1877
1878 // Determine the implicit conversion sequences for each of the
1879 // arguments.
1880 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1881 if (ArgIdx < NumArgsInProto) {
1882 // (C++ 13.3.2p3): for F to be a viable function, there shall
1883 // exist for each argument an implicit conversion sequence
1884 // (13.3.3.1) that converts that argument to the corresponding
1885 // parameter of F.
1886 QualType ParamType = Proto->getArgType(ArgIdx);
1887 Candidate.Conversions[ArgIdx + 1]
1888 = TryCopyInitialization(Args[ArgIdx], ParamType,
1889 SuppressUserConversions);
1890 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1891 == ImplicitConversionSequence::BadConversion) {
1892 Candidate.Viable = false;
1893 break;
1894 }
1895 } else {
1896 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1897 // argument for which there is no corresponding parameter is
1898 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1899 Candidate.Conversions[ArgIdx + 1].ConversionKind
1900 = ImplicitConversionSequence::EllipsisConversion;
1901 }
1902 }
1903}
1904
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001905/// AddConversionCandidate - Add a C++ conversion function as a
1906/// candidate in the candidate set (C++ [over.match.conv],
1907/// C++ [over.match.copy]). From is the expression we're converting from,
1908/// and ToType is the type that we're eventually trying to convert to
1909/// (which may or may not be the same type as the type that the
1910/// conversion function produces).
1911void
1912Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1913 Expr *From, QualType ToType,
1914 OverloadCandidateSet& CandidateSet) {
1915 // Add this candidate
1916 CandidateSet.push_back(OverloadCandidate());
1917 OverloadCandidate& Candidate = CandidateSet.back();
1918 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001919 Candidate.IsSurrogate = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001920 Candidate.FinalConversion.setAsIdentityConversion();
1921 Candidate.FinalConversion.FromTypePtr
1922 = Conversion->getConversionType().getAsOpaquePtr();
1923 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1924
Douglas Gregor96176b32008-11-18 23:14:02 +00001925 // Determine the implicit conversion sequence for the implicit
1926 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001927 Candidate.Viable = true;
1928 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00001929 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001930
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001931 if (Candidate.Conversions[0].ConversionKind
1932 == ImplicitConversionSequence::BadConversion) {
1933 Candidate.Viable = false;
1934 return;
1935 }
1936
1937 // To determine what the conversion from the result of calling the
1938 // conversion function to the type we're eventually trying to
1939 // convert to (ToType), we need to synthesize a call to the
1940 // conversion function and attempt copy initialization from it. This
1941 // makes sure that we get the right semantics with respect to
1942 // lvalues/rvalues and the type. Fortunately, we can allocate this
1943 // call on the stack and we don't need its arguments to be
1944 // well-formed.
1945 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1946 SourceLocation());
1947 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001948 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001949 CallExpr Call(&ConversionFn, 0, 0,
1950 Conversion->getConversionType().getNonReferenceType(),
1951 SourceLocation());
1952 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1953 switch (ICS.ConversionKind) {
1954 case ImplicitConversionSequence::StandardConversion:
1955 Candidate.FinalConversion = ICS.Standard;
1956 break;
1957
1958 case ImplicitConversionSequence::BadConversion:
1959 Candidate.Viable = false;
1960 break;
1961
1962 default:
1963 assert(false &&
1964 "Can only end up with a standard conversion sequence or failure");
1965 }
1966}
1967
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001968/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
1969/// converts the given @c Object to a function pointer via the
1970/// conversion function @c Conversion, and then attempts to call it
1971/// with the given arguments (C++ [over.call.object]p2-4). Proto is
1972/// the type of function that we'll eventually be calling.
1973void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
1974 const FunctionTypeProto *Proto,
1975 Expr *Object, Expr **Args, unsigned NumArgs,
1976 OverloadCandidateSet& CandidateSet) {
1977 CandidateSet.push_back(OverloadCandidate());
1978 OverloadCandidate& Candidate = CandidateSet.back();
1979 Candidate.Function = 0;
1980 Candidate.Surrogate = Conversion;
1981 Candidate.Viable = true;
1982 Candidate.IsSurrogate = true;
1983 Candidate.Conversions.resize(NumArgs + 1);
1984
1985 // Determine the implicit conversion sequence for the implicit
1986 // object parameter.
1987 ImplicitConversionSequence ObjectInit
1988 = TryObjectArgumentInitialization(Object, Conversion);
1989 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
1990 Candidate.Viable = false;
1991 return;
1992 }
1993
1994 // The first conversion is actually a user-defined conversion whose
1995 // first conversion is ObjectInit's standard conversion (which is
1996 // effectively a reference binding). Record it as such.
1997 Candidate.Conversions[0].ConversionKind
1998 = ImplicitConversionSequence::UserDefinedConversion;
1999 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2000 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2001 Candidate.Conversions[0].UserDefined.After
2002 = Candidate.Conversions[0].UserDefined.Before;
2003 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2004
2005 // Find the
2006 unsigned NumArgsInProto = Proto->getNumArgs();
2007
2008 // (C++ 13.3.2p2): A candidate function having fewer than m
2009 // parameters is viable only if it has an ellipsis in its parameter
2010 // list (8.3.5).
2011 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2012 Candidate.Viable = false;
2013 return;
2014 }
2015
2016 // Function types don't have any default arguments, so just check if
2017 // we have enough arguments.
2018 if (NumArgs < NumArgsInProto) {
2019 // Not enough arguments.
2020 Candidate.Viable = false;
2021 return;
2022 }
2023
2024 // Determine the implicit conversion sequences for each of the
2025 // arguments.
2026 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2027 if (ArgIdx < NumArgsInProto) {
2028 // (C++ 13.3.2p3): for F to be a viable function, there shall
2029 // exist for each argument an implicit conversion sequence
2030 // (13.3.3.1) that converts that argument to the corresponding
2031 // parameter of F.
2032 QualType ParamType = Proto->getArgType(ArgIdx);
2033 Candidate.Conversions[ArgIdx + 1]
2034 = TryCopyInitialization(Args[ArgIdx], ParamType,
2035 /*SuppressUserConversions=*/false);
2036 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2037 == ImplicitConversionSequence::BadConversion) {
2038 Candidate.Viable = false;
2039 break;
2040 }
2041 } else {
2042 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2043 // argument for which there is no corresponding parameter is
2044 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2045 Candidate.Conversions[ArgIdx + 1].ConversionKind
2046 = ImplicitConversionSequence::EllipsisConversion;
2047 }
2048 }
2049}
2050
Douglas Gregor447b69e2008-11-19 03:25:36 +00002051/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2052/// an acceptable non-member overloaded operator for a call whose
2053/// arguments have types T1 (and, if non-empty, T2). This routine
2054/// implements the check in C++ [over.match.oper]p3b2 concerning
2055/// enumeration types.
2056static bool
2057IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2058 QualType T1, QualType T2,
2059 ASTContext &Context) {
2060 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2061 return true;
2062
2063 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
2064 if (Proto->getNumArgs() < 1)
2065 return false;
2066
2067 if (T1->isEnumeralType()) {
2068 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2069 if (Context.getCanonicalType(T1).getUnqualifiedType()
2070 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2071 return true;
2072 }
2073
2074 if (Proto->getNumArgs() < 2)
2075 return false;
2076
2077 if (!T2.isNull() && T2->isEnumeralType()) {
2078 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2079 if (Context.getCanonicalType(T2).getUnqualifiedType()
2080 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2081 return true;
2082 }
2083
2084 return false;
2085}
2086
Douglas Gregor96176b32008-11-18 23:14:02 +00002087/// AddOperatorCandidates - Add the overloaded operator candidates for
2088/// the operator Op that was used in an operator expression such as "x
2089/// Op y". S is the scope in which the expression occurred (used for
2090/// name lookup of the operator), Args/NumArgs provides the operator
2091/// arguments, and CandidateSet will store the added overload
2092/// candidates. (C++ [over.match.oper]).
2093void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2094 Expr **Args, unsigned NumArgs,
2095 OverloadCandidateSet& CandidateSet) {
2096 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2097
2098 // C++ [over.match.oper]p3:
2099 // For a unary operator @ with an operand of a type whose
2100 // cv-unqualified version is T1, and for a binary operator @ with
2101 // a left operand of a type whose cv-unqualified version is T1 and
2102 // a right operand of a type whose cv-unqualified version is T2,
2103 // three sets of candidate functions, designated member
2104 // candidates, non-member candidates and built-in candidates, are
2105 // constructed as follows:
2106 QualType T1 = Args[0]->getType();
2107 QualType T2;
2108 if (NumArgs > 1)
2109 T2 = Args[1]->getType();
2110
2111 // -- If T1 is a class type, the set of member candidates is the
2112 // result of the qualified lookup of T1::operator@
2113 // (13.3.1.1.1); otherwise, the set of member candidates is
2114 // empty.
2115 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002116 DeclContext::lookup_const_result Lookup
Douglas Gregore267ff32008-12-11 20:41:00 +00002117 = T1Rec->getDecl()->lookup(Context, OpName);
Douglas Gregor44b43212008-12-11 16:49:14 +00002118 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first;
Douglas Gregor96176b32008-11-18 23:14:02 +00002119 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
2120 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
2121 /*SuppressUserConversions=*/false);
2122 else if (OverloadedFunctionDecl *Ovl
2123 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
2124 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2125 FEnd = Ovl->function_end();
2126 F != FEnd; ++F) {
2127 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
2128 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
2129 /*SuppressUserConversions=*/false);
2130 }
2131 }
2132 }
2133
2134 // -- The set of non-member candidates is the result of the
2135 // unqualified lookup of operator@ in the context of the
2136 // expression according to the usual rules for name lookup in
2137 // unqualified function calls (3.4.2) except that all member
2138 // functions are ignored. However, if no operand has a class
2139 // type, only those non-member functions in the lookup set
2140 // that have a first parameter of type T1 or “reference to
2141 // (possibly cv-qualified) T1”, when T1 is an enumeration
2142 // type, or (if there is a right operand) a second parameter
2143 // of type T2 or “reference to (possibly cv-qualified) T2”,
2144 // when T2 is an enumeration type, are candidate functions.
2145 {
2146 NamedDecl *NonMemberOps = 0;
2147 for (IdentifierResolver::iterator I
2148 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
2149 I != IdResolver.end(); ++I) {
2150 // We don't need to check the identifier namespace, because
2151 // operator names can only be ordinary identifiers.
2152
2153 // Ignore member functions.
2154 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
2155 if (SD->getDeclContext()->isCXXRecord())
2156 continue;
2157 }
2158
2159 // We found something with this name. We're done.
2160 NonMemberOps = *I;
2161 break;
2162 }
2163
Douglas Gregor447b69e2008-11-19 03:25:36 +00002164 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) {
2165 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2166 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2167 /*SuppressUserConversions=*/false);
2168 } else if (OverloadedFunctionDecl *Ovl
2169 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002170 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2171 FEnd = Ovl->function_end();
Douglas Gregor447b69e2008-11-19 03:25:36 +00002172 F != FEnd; ++F) {
2173 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context))
2174 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2175 /*SuppressUserConversions=*/false);
2176 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002177 }
2178 }
2179
2180 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00002181 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor96176b32008-11-18 23:14:02 +00002182}
2183
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002184/// AddBuiltinCandidate - Add a candidate for a built-in
2185/// operator. ResultTy and ParamTys are the result and parameter types
2186/// of the built-in candidate, respectively. Args and NumArgs are the
2187/// arguments being passed to the candidate.
2188void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2189 Expr **Args, unsigned NumArgs,
2190 OverloadCandidateSet& CandidateSet) {
2191 // Add this candidate
2192 CandidateSet.push_back(OverloadCandidate());
2193 OverloadCandidate& Candidate = CandidateSet.back();
2194 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002195 Candidate.IsSurrogate = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002196 Candidate.BuiltinTypes.ResultTy = ResultTy;
2197 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2198 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2199
2200 // Determine the implicit conversion sequences for each of the
2201 // arguments.
2202 Candidate.Viable = true;
2203 Candidate.Conversions.resize(NumArgs);
2204 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2205 Candidate.Conversions[ArgIdx]
2206 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
2207 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002208 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002209 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002210 break;
2211 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002212 }
2213}
2214
2215/// BuiltinCandidateTypeSet - A set of types that will be used for the
2216/// candidate operator functions for built-in operators (C++
2217/// [over.built]). The types are separated into pointer types and
2218/// enumeration types.
2219class BuiltinCandidateTypeSet {
2220 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002221 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002222
2223 /// PointerTypes - The set of pointer types that will be used in the
2224 /// built-in candidates.
2225 TypeSet PointerTypes;
2226
2227 /// EnumerationTypes - The set of enumeration types that will be
2228 /// used in the built-in candidates.
2229 TypeSet EnumerationTypes;
2230
2231 /// Context - The AST context in which we will build the type sets.
2232 ASTContext &Context;
2233
2234 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2235
2236public:
2237 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002238 class iterator {
2239 TypeSet::iterator Base;
2240
2241 public:
2242 typedef QualType value_type;
2243 typedef QualType reference;
2244 typedef QualType pointer;
2245 typedef std::ptrdiff_t difference_type;
2246 typedef std::input_iterator_tag iterator_category;
2247
2248 iterator(TypeSet::iterator B) : Base(B) { }
2249
2250 iterator& operator++() {
2251 ++Base;
2252 return *this;
2253 }
2254
2255 iterator operator++(int) {
2256 iterator tmp(*this);
2257 ++(*this);
2258 return tmp;
2259 }
2260
2261 reference operator*() const {
2262 return QualType::getFromOpaquePtr(*Base);
2263 }
2264
2265 pointer operator->() const {
2266 return **this;
2267 }
2268
2269 friend bool operator==(iterator LHS, iterator RHS) {
2270 return LHS.Base == RHS.Base;
2271 }
2272
2273 friend bool operator!=(iterator LHS, iterator RHS) {
2274 return LHS.Base != RHS.Base;
2275 }
2276 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002277
2278 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2279
2280 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
2281
2282 /// pointer_begin - First pointer type found;
2283 iterator pointer_begin() { return PointerTypes.begin(); }
2284
2285 /// pointer_end - Last pointer type found;
2286 iterator pointer_end() { return PointerTypes.end(); }
2287
2288 /// enumeration_begin - First enumeration type found;
2289 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2290
2291 /// enumeration_end - Last enumeration type found;
2292 iterator enumeration_end() { return EnumerationTypes.end(); }
2293};
2294
2295/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2296/// the set of pointer types along with any more-qualified variants of
2297/// that type. For example, if @p Ty is "int const *", this routine
2298/// will add "int const *", "int const volatile *", "int const
2299/// restrict *", and "int const volatile restrict *" to the set of
2300/// pointer types. Returns true if the add of @p Ty itself succeeded,
2301/// false otherwise.
2302bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2303 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002304 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002305 return false;
2306
2307 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2308 QualType PointeeTy = PointerTy->getPointeeType();
2309 // FIXME: Optimize this so that we don't keep trying to add the same types.
2310
2311 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2312 // with all pointer conversions that don't cast away constness?
2313 if (!PointeeTy.isConstQualified())
2314 AddWithMoreQualifiedTypeVariants
2315 (Context.getPointerType(PointeeTy.withConst()));
2316 if (!PointeeTy.isVolatileQualified())
2317 AddWithMoreQualifiedTypeVariants
2318 (Context.getPointerType(PointeeTy.withVolatile()));
2319 if (!PointeeTy.isRestrictQualified())
2320 AddWithMoreQualifiedTypeVariants
2321 (Context.getPointerType(PointeeTy.withRestrict()));
2322 }
2323
2324 return true;
2325}
2326
2327/// AddTypesConvertedFrom - Add each of the types to which the type @p
2328/// Ty can be implicit converted to the given set of @p Types. We're
2329/// primarily interested in pointer types, enumeration types,
2330void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2331 bool AllowUserConversions) {
2332 // Only deal with canonical types.
2333 Ty = Context.getCanonicalType(Ty);
2334
2335 // Look through reference types; they aren't part of the type of an
2336 // expression for the purposes of conversions.
2337 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2338 Ty = RefTy->getPointeeType();
2339
2340 // We don't care about qualifiers on the type.
2341 Ty = Ty.getUnqualifiedType();
2342
2343 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2344 QualType PointeeTy = PointerTy->getPointeeType();
2345
2346 // Insert our type, and its more-qualified variants, into the set
2347 // of types.
2348 if (!AddWithMoreQualifiedTypeVariants(Ty))
2349 return;
2350
2351 // Add 'cv void*' to our set of types.
2352 if (!Ty->isVoidType()) {
2353 QualType QualVoid
2354 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2355 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2356 }
2357
2358 // If this is a pointer to a class type, add pointers to its bases
2359 // (with the same level of cv-qualification as the original
2360 // derived class, of course).
2361 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2362 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2363 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2364 Base != ClassDecl->bases_end(); ++Base) {
2365 QualType BaseTy = Context.getCanonicalType(Base->getType());
2366 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2367
2368 // Add the pointer type, recursively, so that we get all of
2369 // the indirect base classes, too.
2370 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
2371 }
2372 }
2373 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002374 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002375 } else if (AllowUserConversions) {
2376 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2377 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2378 // FIXME: Visit conversion functions in the base classes, too.
2379 OverloadedFunctionDecl *Conversions
2380 = ClassDecl->getConversionFunctions();
2381 for (OverloadedFunctionDecl::function_iterator Func
2382 = Conversions->function_begin();
2383 Func != Conversions->function_end(); ++Func) {
2384 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2385 AddTypesConvertedFrom(Conv->getConversionType(), false);
2386 }
2387 }
2388 }
2389}
2390
Douglas Gregor74253732008-11-19 15:42:04 +00002391/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2392/// operator overloads to the candidate set (C++ [over.built]), based
2393/// on the operator @p Op and the arguments given. For example, if the
2394/// operator is a binary '+', this routine might add "int
2395/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002396void
Douglas Gregor74253732008-11-19 15:42:04 +00002397Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2398 Expr **Args, unsigned NumArgs,
2399 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002400 // The set of "promoted arithmetic types", which are the arithmetic
2401 // types are that preserved by promotion (C++ [over.built]p2). Note
2402 // that the first few of these types are the promoted integral
2403 // types; these types need to be first.
2404 // FIXME: What about complex?
2405 const unsigned FirstIntegralType = 0;
2406 const unsigned LastIntegralType = 13;
2407 const unsigned FirstPromotedIntegralType = 7,
2408 LastPromotedIntegralType = 13;
2409 const unsigned FirstPromotedArithmeticType = 7,
2410 LastPromotedArithmeticType = 16;
2411 const unsigned NumArithmeticTypes = 16;
2412 QualType ArithmeticTypes[NumArithmeticTypes] = {
2413 Context.BoolTy, Context.CharTy, Context.WCharTy,
2414 Context.SignedCharTy, Context.ShortTy,
2415 Context.UnsignedCharTy, Context.UnsignedShortTy,
2416 Context.IntTy, Context.LongTy, Context.LongLongTy,
2417 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2418 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2419 };
2420
2421 // Find all of the types that the arguments can convert to, but only
2422 // if the operator we're looking at has built-in operator candidates
2423 // that make use of these types.
2424 BuiltinCandidateTypeSet CandidateTypes(Context);
2425 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2426 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002427 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002428 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002429 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2430 (Op == OO_Star && NumArgs == 1)) {
2431 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002432 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2433 }
2434
2435 bool isComparison = false;
2436 switch (Op) {
2437 case OO_None:
2438 case NUM_OVERLOADED_OPERATORS:
2439 assert(false && "Expected an overloaded operator");
2440 break;
2441
Douglas Gregor74253732008-11-19 15:42:04 +00002442 case OO_Star: // '*' is either unary or binary
2443 if (NumArgs == 1)
2444 goto UnaryStar;
2445 else
2446 goto BinaryStar;
2447 break;
2448
2449 case OO_Plus: // '+' is either unary or binary
2450 if (NumArgs == 1)
2451 goto UnaryPlus;
2452 else
2453 goto BinaryPlus;
2454 break;
2455
2456 case OO_Minus: // '-' is either unary or binary
2457 if (NumArgs == 1)
2458 goto UnaryMinus;
2459 else
2460 goto BinaryMinus;
2461 break;
2462
2463 case OO_Amp: // '&' is either unary or binary
2464 if (NumArgs == 1)
2465 goto UnaryAmp;
2466 else
2467 goto BinaryAmp;
2468
2469 case OO_PlusPlus:
2470 case OO_MinusMinus:
2471 // C++ [over.built]p3:
2472 //
2473 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2474 // is either volatile or empty, there exist candidate operator
2475 // functions of the form
2476 //
2477 // VQ T& operator++(VQ T&);
2478 // T operator++(VQ T&, int);
2479 //
2480 // C++ [over.built]p4:
2481 //
2482 // For every pair (T, VQ), where T is an arithmetic type other
2483 // than bool, and VQ is either volatile or empty, there exist
2484 // candidate operator functions of the form
2485 //
2486 // VQ T& operator--(VQ T&);
2487 // T operator--(VQ T&, int);
2488 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2489 Arith < NumArithmeticTypes; ++Arith) {
2490 QualType ArithTy = ArithmeticTypes[Arith];
2491 QualType ParamTypes[2]
2492 = { Context.getReferenceType(ArithTy), Context.IntTy };
2493
2494 // Non-volatile version.
2495 if (NumArgs == 1)
2496 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2497 else
2498 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2499
2500 // Volatile version
2501 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2502 if (NumArgs == 1)
2503 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2504 else
2505 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2506 }
2507
2508 // C++ [over.built]p5:
2509 //
2510 // For every pair (T, VQ), where T is a cv-qualified or
2511 // cv-unqualified object type, and VQ is either volatile or
2512 // empty, there exist candidate operator functions of the form
2513 //
2514 // T*VQ& operator++(T*VQ&);
2515 // T*VQ& operator--(T*VQ&);
2516 // T* operator++(T*VQ&, int);
2517 // T* operator--(T*VQ&, int);
2518 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2519 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2520 // Skip pointer types that aren't pointers to object types.
Douglas Gregorcb7de522008-11-26 23:31:11 +00002521 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002522 continue;
2523
2524 QualType ParamTypes[2] = {
2525 Context.getReferenceType(*Ptr), Context.IntTy
2526 };
2527
2528 // Without volatile
2529 if (NumArgs == 1)
2530 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2531 else
2532 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2533
2534 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2535 // With volatile
2536 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2537 if (NumArgs == 1)
2538 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2539 else
2540 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2541 }
2542 }
2543 break;
2544
2545 UnaryStar:
2546 // C++ [over.built]p6:
2547 // For every cv-qualified or cv-unqualified object type T, there
2548 // exist candidate operator functions of the form
2549 //
2550 // T& operator*(T*);
2551 //
2552 // C++ [over.built]p7:
2553 // For every function type T, there exist candidate operator
2554 // functions of the form
2555 // T& operator*(T*);
2556 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2557 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2558 QualType ParamTy = *Ptr;
2559 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2560 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2561 &ParamTy, Args, 1, CandidateSet);
2562 }
2563 break;
2564
2565 UnaryPlus:
2566 // C++ [over.built]p8:
2567 // For every type T, there exist candidate operator functions of
2568 // the form
2569 //
2570 // T* operator+(T*);
2571 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2572 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2573 QualType ParamTy = *Ptr;
2574 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2575 }
2576
2577 // Fall through
2578
2579 UnaryMinus:
2580 // C++ [over.built]p9:
2581 // For every promoted arithmetic type T, there exist candidate
2582 // operator functions of the form
2583 //
2584 // T operator+(T);
2585 // T operator-(T);
2586 for (unsigned Arith = FirstPromotedArithmeticType;
2587 Arith < LastPromotedArithmeticType; ++Arith) {
2588 QualType ArithTy = ArithmeticTypes[Arith];
2589 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2590 }
2591 break;
2592
2593 case OO_Tilde:
2594 // C++ [over.built]p10:
2595 // For every promoted integral type T, there exist candidate
2596 // operator functions of the form
2597 //
2598 // T operator~(T);
2599 for (unsigned Int = FirstPromotedIntegralType;
2600 Int < LastPromotedIntegralType; ++Int) {
2601 QualType IntTy = ArithmeticTypes[Int];
2602 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2603 }
2604 break;
2605
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002606 case OO_New:
2607 case OO_Delete:
2608 case OO_Array_New:
2609 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002610 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002611 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002612 break;
2613
2614 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002615 UnaryAmp:
2616 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002617 // C++ [over.match.oper]p3:
2618 // -- For the operator ',', the unary operator '&', or the
2619 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002620 break;
2621
2622 case OO_Less:
2623 case OO_Greater:
2624 case OO_LessEqual:
2625 case OO_GreaterEqual:
2626 case OO_EqualEqual:
2627 case OO_ExclaimEqual:
2628 // C++ [over.built]p15:
2629 //
2630 // For every pointer or enumeration type T, there exist
2631 // candidate operator functions of the form
2632 //
2633 // bool operator<(T, T);
2634 // bool operator>(T, T);
2635 // bool operator<=(T, T);
2636 // bool operator>=(T, T);
2637 // bool operator==(T, T);
2638 // bool operator!=(T, T);
2639 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2640 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2641 QualType ParamTypes[2] = { *Ptr, *Ptr };
2642 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2643 }
2644 for (BuiltinCandidateTypeSet::iterator Enum
2645 = CandidateTypes.enumeration_begin();
2646 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2647 QualType ParamTypes[2] = { *Enum, *Enum };
2648 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2649 }
2650
2651 // Fall through.
2652 isComparison = true;
2653
Douglas Gregor74253732008-11-19 15:42:04 +00002654 BinaryPlus:
2655 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002656 if (!isComparison) {
2657 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2658
2659 // C++ [over.built]p13:
2660 //
2661 // For every cv-qualified or cv-unqualified object type T
2662 // there exist candidate operator functions of the form
2663 //
2664 // T* operator+(T*, ptrdiff_t);
2665 // T& operator[](T*, ptrdiff_t); [BELOW]
2666 // T* operator-(T*, ptrdiff_t);
2667 // T* operator+(ptrdiff_t, T*);
2668 // T& operator[](ptrdiff_t, T*); [BELOW]
2669 //
2670 // C++ [over.built]p14:
2671 //
2672 // For every T, where T is a pointer to object type, there
2673 // exist candidate operator functions of the form
2674 //
2675 // ptrdiff_t operator-(T, T);
2676 for (BuiltinCandidateTypeSet::iterator Ptr
2677 = CandidateTypes.pointer_begin();
2678 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2679 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2680
2681 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2682 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2683
2684 if (Op == OO_Plus) {
2685 // T* operator+(ptrdiff_t, T*);
2686 ParamTypes[0] = ParamTypes[1];
2687 ParamTypes[1] = *Ptr;
2688 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2689 } else {
2690 // ptrdiff_t operator-(T, T);
2691 ParamTypes[1] = *Ptr;
2692 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2693 Args, 2, CandidateSet);
2694 }
2695 }
2696 }
2697 // Fall through
2698
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002699 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002700 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002701 // C++ [over.built]p12:
2702 //
2703 // For every pair of promoted arithmetic types L and R, there
2704 // exist candidate operator functions of the form
2705 //
2706 // LR operator*(L, R);
2707 // LR operator/(L, R);
2708 // LR operator+(L, R);
2709 // LR operator-(L, R);
2710 // bool operator<(L, R);
2711 // bool operator>(L, R);
2712 // bool operator<=(L, R);
2713 // bool operator>=(L, R);
2714 // bool operator==(L, R);
2715 // bool operator!=(L, R);
2716 //
2717 // where LR is the result of the usual arithmetic conversions
2718 // between types L and R.
2719 for (unsigned Left = FirstPromotedArithmeticType;
2720 Left < LastPromotedArithmeticType; ++Left) {
2721 for (unsigned Right = FirstPromotedArithmeticType;
2722 Right < LastPromotedArithmeticType; ++Right) {
2723 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2724 QualType Result
2725 = isComparison? Context.BoolTy
2726 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2727 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2728 }
2729 }
2730 break;
2731
2732 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002733 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002734 case OO_Caret:
2735 case OO_Pipe:
2736 case OO_LessLess:
2737 case OO_GreaterGreater:
2738 // C++ [over.built]p17:
2739 //
2740 // For every pair of promoted integral types L and R, there
2741 // exist candidate operator functions of the form
2742 //
2743 // LR operator%(L, R);
2744 // LR operator&(L, R);
2745 // LR operator^(L, R);
2746 // LR operator|(L, R);
2747 // L operator<<(L, R);
2748 // L operator>>(L, R);
2749 //
2750 // where LR is the result of the usual arithmetic conversions
2751 // between types L and R.
2752 for (unsigned Left = FirstPromotedIntegralType;
2753 Left < LastPromotedIntegralType; ++Left) {
2754 for (unsigned Right = FirstPromotedIntegralType;
2755 Right < LastPromotedIntegralType; ++Right) {
2756 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2757 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2758 ? LandR[0]
2759 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2760 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2761 }
2762 }
2763 break;
2764
2765 case OO_Equal:
2766 // C++ [over.built]p20:
2767 //
2768 // For every pair (T, VQ), where T is an enumeration or
2769 // (FIXME:) pointer to member type and VQ is either volatile or
2770 // empty, there exist candidate operator functions of the form
2771 //
2772 // VQ T& operator=(VQ T&, T);
2773 for (BuiltinCandidateTypeSet::iterator Enum
2774 = CandidateTypes.enumeration_begin();
2775 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2776 QualType ParamTypes[2];
2777
2778 // T& operator=(T&, T)
2779 ParamTypes[0] = Context.getReferenceType(*Enum);
2780 ParamTypes[1] = *Enum;
2781 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2782
Douglas Gregor74253732008-11-19 15:42:04 +00002783 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2784 // volatile T& operator=(volatile T&, T)
2785 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2786 ParamTypes[1] = *Enum;
2787 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2788 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002789 }
2790 // Fall through.
2791
2792 case OO_PlusEqual:
2793 case OO_MinusEqual:
2794 // C++ [over.built]p19:
2795 //
2796 // For every pair (T, VQ), where T is any type and VQ is either
2797 // volatile or empty, there exist candidate operator functions
2798 // of the form
2799 //
2800 // T*VQ& operator=(T*VQ&, T*);
2801 //
2802 // C++ [over.built]p21:
2803 //
2804 // For every pair (T, VQ), where T is a cv-qualified or
2805 // cv-unqualified object type and VQ is either volatile or
2806 // empty, there exist candidate operator functions of the form
2807 //
2808 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2809 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2810 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2811 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2812 QualType ParamTypes[2];
2813 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2814
2815 // non-volatile version
2816 ParamTypes[0] = Context.getReferenceType(*Ptr);
2817 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2818
Douglas Gregor74253732008-11-19 15:42:04 +00002819 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2820 // volatile version
2821 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2822 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2823 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002824 }
2825 // Fall through.
2826
2827 case OO_StarEqual:
2828 case OO_SlashEqual:
2829 // C++ [over.built]p18:
2830 //
2831 // For every triple (L, VQ, R), where L is an arithmetic type,
2832 // VQ is either volatile or empty, and R is a promoted
2833 // arithmetic type, there exist candidate operator functions of
2834 // the form
2835 //
2836 // VQ L& operator=(VQ L&, R);
2837 // VQ L& operator*=(VQ L&, R);
2838 // VQ L& operator/=(VQ L&, R);
2839 // VQ L& operator+=(VQ L&, R);
2840 // VQ L& operator-=(VQ L&, R);
2841 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2842 for (unsigned Right = FirstPromotedArithmeticType;
2843 Right < LastPromotedArithmeticType; ++Right) {
2844 QualType ParamTypes[2];
2845 ParamTypes[1] = ArithmeticTypes[Right];
2846
2847 // Add this built-in operator as a candidate (VQ is empty).
2848 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2849 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2850
2851 // Add this built-in operator as a candidate (VQ is 'volatile').
2852 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2853 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2854 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2855 }
2856 }
2857 break;
2858
2859 case OO_PercentEqual:
2860 case OO_LessLessEqual:
2861 case OO_GreaterGreaterEqual:
2862 case OO_AmpEqual:
2863 case OO_CaretEqual:
2864 case OO_PipeEqual:
2865 // C++ [over.built]p22:
2866 //
2867 // For every triple (L, VQ, R), where L is an integral type, VQ
2868 // is either volatile or empty, and R is a promoted integral
2869 // type, there exist candidate operator functions of the form
2870 //
2871 // VQ L& operator%=(VQ L&, R);
2872 // VQ L& operator<<=(VQ L&, R);
2873 // VQ L& operator>>=(VQ L&, R);
2874 // VQ L& operator&=(VQ L&, R);
2875 // VQ L& operator^=(VQ L&, R);
2876 // VQ L& operator|=(VQ L&, R);
2877 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2878 for (unsigned Right = FirstPromotedIntegralType;
2879 Right < LastPromotedIntegralType; ++Right) {
2880 QualType ParamTypes[2];
2881 ParamTypes[1] = ArithmeticTypes[Right];
2882
2883 // Add this built-in operator as a candidate (VQ is empty).
2884 // FIXME: We should be caching these declarations somewhere,
2885 // rather than re-building them every time.
2886 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2887 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2888
2889 // Add this built-in operator as a candidate (VQ is 'volatile').
2890 ParamTypes[0] = ArithmeticTypes[Left];
2891 ParamTypes[0].addVolatile();
2892 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2893 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2894 }
2895 }
2896 break;
2897
Douglas Gregor74253732008-11-19 15:42:04 +00002898 case OO_Exclaim: {
2899 // C++ [over.operator]p23:
2900 //
2901 // There also exist candidate operator functions of the form
2902 //
2903 // bool operator!(bool);
2904 // bool operator&&(bool, bool); [BELOW]
2905 // bool operator||(bool, bool); [BELOW]
2906 QualType ParamTy = Context.BoolTy;
2907 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2908 break;
2909 }
2910
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002911 case OO_AmpAmp:
2912 case OO_PipePipe: {
2913 // C++ [over.operator]p23:
2914 //
2915 // There also exist candidate operator functions of the form
2916 //
Douglas Gregor74253732008-11-19 15:42:04 +00002917 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002918 // bool operator&&(bool, bool);
2919 // bool operator||(bool, bool);
2920 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2921 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2922 break;
2923 }
2924
2925 case OO_Subscript:
2926 // C++ [over.built]p13:
2927 //
2928 // For every cv-qualified or cv-unqualified object type T there
2929 // exist candidate operator functions of the form
2930 //
2931 // T* operator+(T*, ptrdiff_t); [ABOVE]
2932 // T& operator[](T*, ptrdiff_t);
2933 // T* operator-(T*, ptrdiff_t); [ABOVE]
2934 // T* operator+(ptrdiff_t, T*); [ABOVE]
2935 // T& operator[](ptrdiff_t, T*);
2936 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2937 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2938 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2939 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2940 QualType ResultTy = Context.getReferenceType(PointeeType);
2941
2942 // T& operator[](T*, ptrdiff_t)
2943 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2944
2945 // T& operator[](ptrdiff_t, T*);
2946 ParamTypes[0] = ParamTypes[1];
2947 ParamTypes[1] = *Ptr;
2948 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2949 }
2950 break;
2951
2952 case OO_ArrowStar:
2953 // FIXME: No support for pointer-to-members yet.
2954 break;
2955 }
2956}
2957
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002958/// AddOverloadCandidates - Add all of the function overloads in Ovl
2959/// to the candidate set.
2960void
Douglas Gregor18fe5682008-11-03 20:45:27 +00002961Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002962 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002963 OverloadCandidateSet& CandidateSet,
2964 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002965{
Douglas Gregor18fe5682008-11-03 20:45:27 +00002966 for (OverloadedFunctionDecl::function_const_iterator Func
2967 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002968 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00002969 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2970 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002971}
2972
2973/// isBetterOverloadCandidate - Determines whether the first overload
2974/// candidate is a better candidate than the second (C++ 13.3.3p1).
2975bool
2976Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2977 const OverloadCandidate& Cand2)
2978{
2979 // Define viable functions to be better candidates than non-viable
2980 // functions.
2981 if (!Cand2.Viable)
2982 return Cand1.Viable;
2983 else if (!Cand1.Viable)
2984 return false;
2985
2986 // FIXME: Deal with the implicit object parameter for static member
2987 // functions. (C++ 13.3.3p1).
2988
2989 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
2990 // function than another viable function F2 if for all arguments i,
2991 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
2992 // then...
2993 unsigned NumArgs = Cand1.Conversions.size();
2994 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
2995 bool HasBetterConversion = false;
2996 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2997 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
2998 Cand2.Conversions[ArgIdx])) {
2999 case ImplicitConversionSequence::Better:
3000 // Cand1 has a better conversion sequence.
3001 HasBetterConversion = true;
3002 break;
3003
3004 case ImplicitConversionSequence::Worse:
3005 // Cand1 can't be better than Cand2.
3006 return false;
3007
3008 case ImplicitConversionSequence::Indistinguishable:
3009 // Do nothing.
3010 break;
3011 }
3012 }
3013
3014 if (HasBetterConversion)
3015 return true;
3016
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003017 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3018 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003019
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003020 // C++ [over.match.best]p1b4:
3021 //
3022 // -- the context is an initialization by user-defined conversion
3023 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3024 // from the return type of F1 to the destination type (i.e.,
3025 // the type of the entity being initialized) is a better
3026 // conversion sequence than the standard conversion sequence
3027 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003028 if (Cand1.Function && Cand2.Function &&
3029 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003030 isa<CXXConversionDecl>(Cand2.Function)) {
3031 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3032 Cand2.FinalConversion)) {
3033 case ImplicitConversionSequence::Better:
3034 // Cand1 has a better conversion sequence.
3035 return true;
3036
3037 case ImplicitConversionSequence::Worse:
3038 // Cand1 can't be better than Cand2.
3039 return false;
3040
3041 case ImplicitConversionSequence::Indistinguishable:
3042 // Do nothing
3043 break;
3044 }
3045 }
3046
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003047 return false;
3048}
3049
3050/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3051/// within an overload candidate set. If overloading is successful,
3052/// the result will be OR_Success and Best will be set to point to the
3053/// best viable function within the candidate set. Otherwise, one of
3054/// several kinds of errors will be returned; see
3055/// Sema::OverloadingResult.
3056Sema::OverloadingResult
3057Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3058 OverloadCandidateSet::iterator& Best)
3059{
3060 // Find the best viable function.
3061 Best = CandidateSet.end();
3062 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3063 Cand != CandidateSet.end(); ++Cand) {
3064 if (Cand->Viable) {
3065 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3066 Best = Cand;
3067 }
3068 }
3069
3070 // If we didn't find any viable functions, abort.
3071 if (Best == CandidateSet.end())
3072 return OR_No_Viable_Function;
3073
3074 // Make sure that this function is better than every other viable
3075 // function. If not, we have an ambiguity.
3076 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3077 Cand != CandidateSet.end(); ++Cand) {
3078 if (Cand->Viable &&
3079 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003080 !isBetterOverloadCandidate(*Best, *Cand)) {
3081 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003082 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003083 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003084 }
3085
3086 // Best is the best viable function.
3087 return OR_Success;
3088}
3089
3090/// PrintOverloadCandidates - When overload resolution fails, prints
3091/// diagnostic messages containing the candidates in the candidate
3092/// set. If OnlyViable is true, only viable candidates will be printed.
3093void
3094Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3095 bool OnlyViable)
3096{
3097 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3098 LastCand = CandidateSet.end();
3099 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003100 if (Cand->Viable || !OnlyViable) {
3101 if (Cand->Function) {
3102 // Normal function
3103 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003104 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003105 // Desugar the type of the surrogate down to a function type,
3106 // retaining as many typedefs as possible while still showing
3107 // the function type (and, therefore, its parameter types).
3108 QualType FnType = Cand->Surrogate->getConversionType();
3109 bool isReference = false;
3110 bool isPointer = false;
3111 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
3112 FnType = FnTypeRef->getPointeeType();
3113 isReference = true;
3114 }
3115 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3116 FnType = FnTypePtr->getPointeeType();
3117 isPointer = true;
3118 }
3119 // Desugar down to a function type.
3120 FnType = QualType(FnType->getAsFunctionType(), 0);
3121 // Reconstruct the pointer/reference as appropriate.
3122 if (isPointer) FnType = Context.getPointerType(FnType);
3123 if (isReference) FnType = Context.getReferenceType(FnType);
3124
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003125 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003126 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003127 } else {
3128 // FIXME: We need to get the identifier in here
3129 // FIXME: Do we want the error message to point at the
3130 // operator? (built-ins won't have a location)
3131 QualType FnType
3132 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3133 Cand->BuiltinTypes.ParamTypes,
3134 Cand->Conversions.size(),
3135 false, 0);
3136
Chris Lattnerd1625842008-11-24 06:25:27 +00003137 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003138 }
3139 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003140 }
3141}
3142
Douglas Gregor904eed32008-11-10 20:40:00 +00003143/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3144/// an overloaded function (C++ [over.over]), where @p From is an
3145/// expression with overloaded function type and @p ToType is the type
3146/// we're trying to resolve to. For example:
3147///
3148/// @code
3149/// int f(double);
3150/// int f(int);
3151///
3152/// int (*pfd)(double) = f; // selects f(double)
3153/// @endcode
3154///
3155/// This routine returns the resulting FunctionDecl if it could be
3156/// resolved, and NULL otherwise. When @p Complain is true, this
3157/// routine will emit diagnostics if there is an error.
3158FunctionDecl *
3159Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3160 bool Complain) {
3161 QualType FunctionType = ToType;
3162 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3163 FunctionType = ToTypePtr->getPointeeType();
3164
3165 // We only look at pointers or references to functions.
3166 if (!FunctionType->isFunctionType())
3167 return 0;
3168
3169 // Find the actual overloaded function declaration.
3170 OverloadedFunctionDecl *Ovl = 0;
3171
3172 // C++ [over.over]p1:
3173 // [...] [Note: any redundant set of parentheses surrounding the
3174 // overloaded function name is ignored (5.1). ]
3175 Expr *OvlExpr = From->IgnoreParens();
3176
3177 // C++ [over.over]p1:
3178 // [...] The overloaded function name can be preceded by the &
3179 // operator.
3180 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3181 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3182 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3183 }
3184
3185 // Try to dig out the overloaded function.
3186 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3187 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3188
3189 // If there's no overloaded function declaration, we're done.
3190 if (!Ovl)
3191 return 0;
3192
3193 // Look through all of the overloaded functions, searching for one
3194 // whose type matches exactly.
3195 // FIXME: When templates or using declarations come along, we'll actually
3196 // have to deal with duplicates, partial ordering, etc. For now, we
3197 // can just do a simple search.
3198 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3199 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3200 Fun != Ovl->function_end(); ++Fun) {
3201 // C++ [over.over]p3:
3202 // Non-member functions and static member functions match
3203 // targets of type “pointer-to-function”or
3204 // “reference-to-function.”
3205 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
3206 if (!Method->isStatic())
3207 continue;
3208
3209 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3210 return *Fun;
3211 }
3212
3213 return 0;
3214}
3215
Douglas Gregorf6b89692008-11-26 05:54:23 +00003216/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3217/// (which eventually refers to the set of overloaded functions in
3218/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the
3219/// function call down to a specific function. If overload resolution
Douglas Gregor0a396682008-11-26 06:01:48 +00003220/// succeeds, returns the function declaration produced by overload
3221/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003222/// arguments and Fn, and returns NULL.
Douglas Gregor0a396682008-11-26 06:01:48 +00003223FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl,
3224 SourceLocation LParenLoc,
3225 Expr **Args, unsigned NumArgs,
3226 SourceLocation *CommaLocs,
3227 SourceLocation RParenLoc) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003228 OverloadCandidateSet CandidateSet;
3229 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
3230 OverloadCandidateSet::iterator Best;
3231 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003232 case OR_Success:
3233 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003234
3235 case OR_No_Viable_Function:
3236 Diag(Fn->getSourceRange().getBegin(),
3237 diag::err_ovl_no_viable_function_in_call)
3238 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3239 << Fn->getSourceRange();
3240 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3241 break;
3242
3243 case OR_Ambiguous:
3244 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3245 << Ovl->getDeclName() << Fn->getSourceRange();
3246 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3247 break;
3248 }
3249
3250 // Overload resolution failed. Destroy all of the subexpressions and
3251 // return NULL.
3252 Fn->Destroy(Context);
3253 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3254 Args[Arg]->Destroy(Context);
3255 return 0;
3256}
3257
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003258/// BuildCallToObjectOfClassType - Build a call to an object of class
3259/// type (C++ [over.call.object]), which can end up invoking an
3260/// overloaded function call operator (@c operator()) or performing a
3261/// user-defined conversion on the object argument.
3262Action::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00003263Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3264 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003265 Expr **Args, unsigned NumArgs,
3266 SourceLocation *CommaLocs,
3267 SourceLocation RParenLoc) {
3268 assert(Object->getType()->isRecordType() && "Requires object type argument");
3269 const RecordType *Record = Object->getType()->getAsRecordType();
3270
3271 // C++ [over.call.object]p1:
3272 // If the primary-expression E in the function call syntax
3273 // evaluates to a class object of type “cv T”, then the set of
3274 // candidate functions includes at least the function call
3275 // operators of T. The function call operators of T are obtained by
3276 // ordinary lookup of the name operator() in the context of
3277 // (E).operator().
3278 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00003279 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
3280 DeclContext::lookup_const_result Lookup
Douglas Gregore267ff32008-12-11 20:41:00 +00003281 = Record->getDecl()->lookup(Context, OpName);
Douglas Gregor44b43212008-12-11 16:49:14 +00003282 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003283 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3284 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3285 /*SuppressUserConversions=*/false);
3286 else if (OverloadedFunctionDecl *Ovl
3287 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3288 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3289 FEnd = Ovl->function_end();
3290 F != FEnd; ++F) {
3291 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3292 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3293 /*SuppressUserConversions=*/false);
3294 }
3295 }
3296
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003297 // C++ [over.call.object]p2:
3298 // In addition, for each conversion function declared in T of the
3299 // form
3300 //
3301 // operator conversion-type-id () cv-qualifier;
3302 //
3303 // where cv-qualifier is the same cv-qualification as, or a
3304 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003305 // denotes the type "pointer to function of (P1,...,Pn) returning
3306 // R", or the type "reference to pointer to function of
3307 // (P1,...,Pn) returning R", or the type "reference to function
3308 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003309 // is also considered as a candidate function. Similarly,
3310 // surrogate call functions are added to the set of candidate
3311 // functions for each conversion function declared in an
3312 // accessible base class provided the function is not hidden
3313 // within T by another intervening declaration.
3314 //
3315 // FIXME: Look in base classes for more conversion operators!
3316 OverloadedFunctionDecl *Conversions
3317 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003318 for (OverloadedFunctionDecl::function_iterator
3319 Func = Conversions->function_begin(),
3320 FuncEnd = Conversions->function_end();
3321 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003322 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3323
3324 // Strip the reference type (if any) and then the pointer type (if
3325 // any) to get down to what might be a function type.
3326 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3327 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3328 ConvType = ConvPtrType->getPointeeType();
3329
3330 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3331 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3332 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003333
3334 // Perform overload resolution.
3335 OverloadCandidateSet::iterator Best;
3336 switch (BestViableFunction(CandidateSet, Best)) {
3337 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003338 // Overload resolution succeeded; we'll build the appropriate call
3339 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003340 break;
3341
3342 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003343 Diag(Object->getSourceRange().getBegin(),
3344 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003345 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003346 << Object->getSourceRange();
3347 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003348 break;
3349
3350 case OR_Ambiguous:
3351 Diag(Object->getSourceRange().getBegin(),
3352 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003353 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003354 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3355 break;
3356 }
3357
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003358 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003359 // We had an error; delete all of the subexpressions and return
3360 // the error.
3361 delete Object;
3362 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3363 delete Args[ArgIdx];
3364 return true;
3365 }
3366
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003367 if (Best->Function == 0) {
3368 // Since there is no function declaration, this is one of the
3369 // surrogate candidates. Dig out the conversion function.
3370 CXXConversionDecl *Conv
3371 = cast<CXXConversionDecl>(
3372 Best->Conversions[0].UserDefined.ConversionFunction);
3373
3374 // We selected one of the surrogate functions that converts the
3375 // object parameter to a function pointer. Perform the conversion
3376 // on the object argument, then let ActOnCallExpr finish the job.
3377 // FIXME: Represent the user-defined conversion in the AST!
3378 ImpCastExprToType(Object,
3379 Conv->getConversionType().getNonReferenceType(),
3380 Conv->getConversionType()->isReferenceType());
Douglas Gregor5c37de72008-12-06 00:22:45 +00003381 return ActOnCallExpr(S, (ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003382 CommaLocs, RParenLoc);
3383 }
3384
3385 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3386 // that calls this method, using Object for the implicit object
3387 // parameter and passing along the remaining arguments.
3388 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003389 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3390
3391 unsigned NumArgsInProto = Proto->getNumArgs();
3392 unsigned NumArgsToCheck = NumArgs;
3393
3394 // Build the full argument list for the method call (the
3395 // implicit object parameter is placed at the beginning of the
3396 // list).
3397 Expr **MethodArgs;
3398 if (NumArgs < NumArgsInProto) {
3399 NumArgsToCheck = NumArgsInProto;
3400 MethodArgs = new Expr*[NumArgsInProto + 1];
3401 } else {
3402 MethodArgs = new Expr*[NumArgs + 1];
3403 }
3404 MethodArgs[0] = Object;
3405 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3406 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3407
3408 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3409 SourceLocation());
3410 UsualUnaryConversions(NewFn);
3411
3412 // Once we've built TheCall, all of the expressions are properly
3413 // owned.
3414 QualType ResultTy = Method->getResultType().getNonReferenceType();
3415 llvm::OwningPtr<CXXOperatorCallExpr>
3416 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3417 ResultTy, RParenLoc));
3418 delete [] MethodArgs;
3419
3420 // Initialize the implicit object parameter.
3421 if (!PerformObjectArgumentInitialization(Object, Method))
3422 return true;
3423 TheCall->setArg(0, Object);
3424
3425 // Check the argument types.
3426 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3427 QualType ProtoArgType = Proto->getArgType(i);
3428
3429 Expr *Arg;
3430 if (i < NumArgs)
3431 Arg = Args[i];
3432 else
3433 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
3434 QualType ArgType = Arg->getType();
3435
3436 // Pass the argument.
3437 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3438 return true;
3439
3440 TheCall->setArg(i + 1, Arg);
3441 }
3442
3443 // If this is a variadic call, handle args passed through "...".
3444 if (Proto->isVariadic()) {
3445 // Promote the arguments (C99 6.5.2.2p7).
3446 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3447 Expr *Arg = Args[i];
3448 DefaultArgumentPromotion(Arg);
3449 TheCall->setArg(i + 1, Arg);
3450 }
3451 }
3452
3453 return CheckFunctionCall(Method, TheCall.take());
3454}
3455
Douglas Gregor8ba10742008-11-20 16:27:02 +00003456/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3457/// (if one exists), where @c Base is an expression of class type and
3458/// @c Member is the name of the member we're trying to find.
3459Action::ExprResult
3460Sema::BuildOverloadedArrowExpr(Expr *Base, SourceLocation OpLoc,
3461 SourceLocation MemberLoc,
3462 IdentifierInfo &Member) {
3463 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3464
3465 // C++ [over.ref]p1:
3466 //
3467 // [...] An expression x->m is interpreted as (x.operator->())->m
3468 // for a class object x of type T if T::operator->() exists and if
3469 // the operator is selected as the best match function by the
3470 // overload resolution mechanism (13.3).
3471 // FIXME: look in base classes.
3472 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3473 OverloadCandidateSet CandidateSet;
3474 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor44b43212008-12-11 16:49:14 +00003475 DeclContext::lookup_const_result Lookup
Douglas Gregore267ff32008-12-11 20:41:00 +00003476 = BaseRecord->getDecl()->lookup(Context, OpName);
Douglas Gregor44b43212008-12-11 16:49:14 +00003477 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first;
Douglas Gregor8ba10742008-11-20 16:27:02 +00003478 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3479 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3480 /*SuppressUserConversions=*/false);
3481 else if (OverloadedFunctionDecl *Ovl
3482 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3483 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3484 FEnd = Ovl->function_end();
3485 F != FEnd; ++F) {
3486 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3487 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3488 /*SuppressUserConversions=*/false);
3489 }
3490 }
3491
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003492 llvm::OwningPtr<Expr> BasePtr(Base);
3493
Douglas Gregor8ba10742008-11-20 16:27:02 +00003494 // Perform overload resolution.
3495 OverloadCandidateSet::iterator Best;
3496 switch (BestViableFunction(CandidateSet, Best)) {
3497 case OR_Success:
3498 // Overload resolution succeeded; we'll build the call below.
3499 break;
3500
3501 case OR_No_Viable_Function:
3502 if (CandidateSet.empty())
3503 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003504 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003505 else
3506 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003507 << "operator->" << (unsigned)CandidateSet.size()
3508 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003509 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003510 return true;
3511
3512 case OR_Ambiguous:
3513 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003514 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003515 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003516 return true;
3517 }
3518
3519 // Convert the object parameter.
3520 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003521 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003522 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003523
3524 // No concerns about early exits now.
3525 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003526
3527 // Build the operator call.
3528 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3529 UsualUnaryConversions(FnExpr);
3530 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3531 Method->getResultType().getNonReferenceType(),
3532 OpLoc);
3533 return ActOnMemberReferenceExpr(Base, OpLoc, tok::arrow, MemberLoc, Member);
3534}
3535
Douglas Gregor904eed32008-11-10 20:40:00 +00003536/// FixOverloadedFunctionReference - E is an expression that refers to
3537/// a C++ overloaded function (possibly with some parentheses and
3538/// perhaps a '&' around it). We have resolved the overloaded function
3539/// to the function declaration Fn, so patch up the expression E to
3540/// refer (possibly indirectly) to Fn.
3541void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3542 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3543 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3544 E->setType(PE->getSubExpr()->getType());
3545 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3546 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3547 "Can only take the address of an overloaded function");
3548 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3549 E->setType(Context.getPointerType(E->getType()));
3550 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3551 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3552 "Expected overloaded function");
3553 DR->setDecl(Fn);
3554 E->setType(Fn->getType());
3555 } else {
3556 assert(false && "Invalid reference to overloaded function");
3557 }
3558}
3559
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003560} // end namespace clang