blob: 8463c5d34ba5e6d81b2641fd6eb6c6de32425f6a [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 Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
42 ICC_Conversion,
43 ICC_Conversion,
44 ICC_Conversion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000047 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion
49 };
50 return Category[(int)Kind];
51}
52
53/// GetConversionRank - Retrieve the implicit conversion rank
54/// corresponding to the given implicit conversion kind.
55ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
56 static const ImplicitConversionRank
57 Rank[(int)ICK_Num_Conversion_Kinds] = {
58 ICR_Exact_Match,
59 ICR_Exact_Match,
60 ICR_Exact_Match,
61 ICR_Exact_Match,
62 ICR_Exact_Match,
63 ICR_Promotion,
64 ICR_Promotion,
65 ICR_Conversion,
66 ICR_Conversion,
67 ICR_Conversion,
68 ICR_Conversion,
69 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000070 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 ICR_Conversion
72 };
73 return Rank[(int)Kind];
74}
75
76/// GetImplicitConversionName - Return the name of this kind of
77/// implicit conversion.
78const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
79 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
80 "No conversion",
81 "Lvalue-to-rvalue",
82 "Array-to-pointer",
83 "Function-to-pointer",
84 "Qualification",
85 "Integral promotion",
86 "Floating point promotion",
87 "Integral conversion",
88 "Floating conversion",
89 "Floating-integral conversion",
90 "Pointer conversion",
91 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +000092 "Boolean conversion",
93 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000094 };
95 return Name[Kind];
96}
97
Douglas Gregor60d62c22008-10-31 16:23:19 +000098/// StandardConversionSequence - Set the standard conversion
99/// sequence to the identity conversion.
100void StandardConversionSequence::setAsIdentityConversion() {
101 First = ICK_Identity;
102 Second = ICK_Identity;
103 Third = ICK_Identity;
104 Deprecated = false;
105 ReferenceBinding = false;
106 DirectBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000107 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000108}
109
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000110/// getRank - Retrieve the rank of this standard conversion sequence
111/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
112/// implicit conversions.
113ImplicitConversionRank StandardConversionSequence::getRank() const {
114 ImplicitConversionRank Rank = ICR_Exact_Match;
115 if (GetConversionRank(First) > Rank)
116 Rank = GetConversionRank(First);
117 if (GetConversionRank(Second) > Rank)
118 Rank = GetConversionRank(Second);
119 if (GetConversionRank(Third) > Rank)
120 Rank = GetConversionRank(Third);
121 return Rank;
122}
123
124/// isPointerConversionToBool - Determines whether this conversion is
125/// a conversion of a pointer or pointer-to-member to bool. This is
126/// used as part of the ranking of standard conversion sequences
127/// (C++ 13.3.3.2p4).
128bool StandardConversionSequence::isPointerConversionToBool() const
129{
130 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
131 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
132
133 // Note that FromType has not necessarily been transformed by the
134 // array-to-pointer or function-to-pointer implicit conversions, so
135 // check for their presence as well as checking whether FromType is
136 // a pointer.
137 if (ToType->isBooleanType() &&
138 (FromType->isPointerType() ||
139 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
140 return true;
141
142 return false;
143}
144
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000145/// isPointerConversionToVoidPointer - Determines whether this
146/// conversion is a conversion of a pointer to a void pointer. This is
147/// used as part of the ranking of standard conversion sequences (C++
148/// 13.3.3.2p4).
149bool
150StandardConversionSequence::
151isPointerConversionToVoidPointer(ASTContext& Context) const
152{
153 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
154 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
155
156 // Note that FromType has not necessarily been transformed by the
157 // array-to-pointer implicit conversion, so check for its presence
158 // and redo the conversion to get a pointer.
159 if (First == ICK_Array_To_Pointer)
160 FromType = Context.getArrayDecayedType(FromType);
161
162 if (Second == ICK_Pointer_Conversion)
163 if (const PointerType* ToPtrType = ToType->getAsPointerType())
164 return ToPtrType->getPointeeType()->isVoidType();
165
166 return false;
167}
168
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000169/// DebugPrint - Print this standard conversion sequence to standard
170/// error. Useful for debugging overloading issues.
171void StandardConversionSequence::DebugPrint() const {
172 bool PrintedSomething = false;
173 if (First != ICK_Identity) {
174 fprintf(stderr, "%s", GetImplicitConversionName(First));
175 PrintedSomething = true;
176 }
177
178 if (Second != ICK_Identity) {
179 if (PrintedSomething) {
180 fprintf(stderr, " -> ");
181 }
182 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000183
184 if (CopyConstructor) {
185 fprintf(stderr, " (by copy constructor)");
186 } else if (DirectBinding) {
187 fprintf(stderr, " (direct reference binding)");
188 } else if (ReferenceBinding) {
189 fprintf(stderr, " (reference binding)");
190 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000191 PrintedSomething = true;
192 }
193
194 if (Third != ICK_Identity) {
195 if (PrintedSomething) {
196 fprintf(stderr, " -> ");
197 }
198 fprintf(stderr, "%s", GetImplicitConversionName(Third));
199 PrintedSomething = true;
200 }
201
202 if (!PrintedSomething) {
203 fprintf(stderr, "No conversions required");
204 }
205}
206
207/// DebugPrint - Print this user-defined conversion sequence to standard
208/// error. Useful for debugging overloading issues.
209void UserDefinedConversionSequence::DebugPrint() const {
210 if (Before.First || Before.Second || Before.Third) {
211 Before.DebugPrint();
212 fprintf(stderr, " -> ");
213 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000214 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000215 if (After.First || After.Second || After.Third) {
216 fprintf(stderr, " -> ");
217 After.DebugPrint();
218 }
219}
220
221/// DebugPrint - Print this implicit conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void ImplicitConversionSequence::DebugPrint() const {
224 switch (ConversionKind) {
225 case StandardConversion:
226 fprintf(stderr, "Standard conversion: ");
227 Standard.DebugPrint();
228 break;
229 case UserDefinedConversion:
230 fprintf(stderr, "User-defined conversion: ");
231 UserDefined.DebugPrint();
232 break;
233 case EllipsisConversion:
234 fprintf(stderr, "Ellipsis conversion");
235 break;
236 case BadConversion:
237 fprintf(stderr, "Bad conversion");
238 break;
239 }
240
241 fprintf(stderr, "\n");
242}
243
244// IsOverload - Determine whether the given New declaration is an
245// overload of the Old declaration. This routine returns false if New
246// and Old cannot be overloaded, e.g., if they are functions with the
247// same signature (C++ 1.3.10) or if the Old declaration isn't a
248// function (or overload set). When it does return false and Old is an
249// OverloadedFunctionDecl, MatchedDecl will be set to point to the
250// FunctionDecl that New cannot be overloaded with.
251//
252// Example: Given the following input:
253//
254// void f(int, float); // #1
255// void f(int, int); // #2
256// int f(int, int); // #3
257//
258// When we process #1, there is no previous declaration of "f",
259// so IsOverload will not be used.
260//
261// When we process #2, Old is a FunctionDecl for #1. By comparing the
262// parameter types, we see that #1 and #2 are overloaded (since they
263// have different signatures), so this routine returns false;
264// MatchedDecl is unchanged.
265//
266// When we process #3, Old is an OverloadedFunctionDecl containing #1
267// and #2. We compare the signatures of #3 to #1 (they're overloaded,
268// so we do nothing) and then #3 to #2. Since the signatures of #3 and
269// #2 are identical (return types of functions are not part of the
270// signature), IsOverload returns false and MatchedDecl will be set to
271// point to the FunctionDecl for #2.
272bool
273Sema::IsOverload(FunctionDecl *New, Decl* OldD,
274 OverloadedFunctionDecl::function_iterator& MatchedDecl)
275{
276 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
277 // Is this new function an overload of every function in the
278 // overload set?
279 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
280 FuncEnd = Ovl->function_end();
281 for (; Func != FuncEnd; ++Func) {
282 if (!IsOverload(New, *Func, MatchedDecl)) {
283 MatchedDecl = Func;
284 return false;
285 }
286 }
287
288 // This function overloads every function in the overload set.
289 return true;
290 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
291 // Is the function New an overload of the function Old?
292 QualType OldQType = Context.getCanonicalType(Old->getType());
293 QualType NewQType = Context.getCanonicalType(New->getType());
294
295 // Compare the signatures (C++ 1.3.10) of the two functions to
296 // determine whether they are overloads. If we find any mismatch
297 // in the signature, they are overloads.
298
299 // If either of these functions is a K&R-style function (no
300 // prototype), then we consider them to have matching signatures.
301 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
302 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
303 return false;
304
305 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
306 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
307
308 // The signature of a function includes the types of its
309 // parameters (C++ 1.3.10), which includes the presence or absence
310 // of the ellipsis; see C++ DR 357).
311 if (OldQType != NewQType &&
312 (OldType->getNumArgs() != NewType->getNumArgs() ||
313 OldType->isVariadic() != NewType->isVariadic() ||
314 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
315 NewType->arg_type_begin())))
316 return true;
317
318 // If the function is a class member, its signature includes the
319 // cv-qualifiers (if any) on the function itself.
320 //
321 // As part of this, also check whether one of the member functions
322 // is static, in which case they are not overloads (C++
323 // 13.1p2). While not part of the definition of the signature,
324 // this check is important to determine whether these functions
325 // can be overloaded.
326 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
327 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
328 if (OldMethod && NewMethod &&
329 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000330 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000331 return true;
332
333 // The signatures match; this is not an overload.
334 return false;
335 } else {
336 // (C++ 13p1):
337 // Only function declarations can be overloaded; object and type
338 // declarations cannot be overloaded.
339 return false;
340 }
341}
342
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000343/// TryImplicitConversion - Attempt to perform an implicit conversion
344/// from the given expression (Expr) to the given type (ToType). This
345/// function returns an implicit conversion sequence that can be used
346/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000347///
348/// void f(float f);
349/// void g(int i) { f(i); }
350///
351/// this routine would produce an implicit conversion sequence to
352/// describe the initialization of f from i, which will be a standard
353/// conversion sequence containing an lvalue-to-rvalue conversion (C++
354/// 4.1) followed by a floating-integral conversion (C++ 4.9).
355//
356/// Note that this routine only determines how the conversion can be
357/// performed; it does not actually perform the conversion. As such,
358/// it will not produce any diagnostics if no conversion is available,
359/// but will instead return an implicit conversion sequence of kind
360/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000361///
362/// If @p SuppressUserConversions, then user-defined conversions are
363/// not permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000364ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000365Sema::TryImplicitConversion(Expr* From, QualType ToType,
366 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000367{
368 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000369 if (IsStandardConversion(From, ToType, ICS.Standard))
370 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000371 else if (!SuppressUserConversions &&
372 IsUserDefinedConversion(From, ToType, ICS.UserDefined)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000373 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000374 // C++ [over.ics.user]p4:
375 // A conversion of an expression of class type to the same class
376 // type is given Exact Match rank, and a conversion of an
377 // expression of class type to a base class of that type is
378 // given Conversion rank, in spite of the fact that a copy
379 // constructor (i.e., a user-defined conversion function) is
380 // called for those cases.
381 if (CXXConstructorDecl *Constructor
382 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
383 if (Constructor->isCopyConstructor(Context)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000384 // Turn this into a "standard" conversion sequence, so that it
385 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000386 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
387 ICS.Standard.setAsIdentityConversion();
388 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
389 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000390 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000391 if (IsDerivedFrom(From->getType().getUnqualifiedType(),
392 ToType.getUnqualifiedType()))
393 ICS.Standard.Second = ICK_Derived_To_Base;
394 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000395 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000396 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000397 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000398
399 return ICS;
400}
401
402/// IsStandardConversion - Determines whether there is a standard
403/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
404/// expression From to the type ToType. Standard conversion sequences
405/// only consider non-class types; for conversions that involve class
406/// types, use TryImplicitConversion. If a conversion exists, SCS will
407/// contain the standard conversion sequence required to perform this
408/// conversion and this routine will return true. Otherwise, this
409/// routine will return false and the value of SCS is unspecified.
410bool
411Sema::IsStandardConversion(Expr* From, QualType ToType,
412 StandardConversionSequence &SCS)
413{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000414 QualType FromType = From->getType();
415
Douglas Gregor60d62c22008-10-31 16:23:19 +0000416 // There are no standard conversions for class types, so abort early.
417 if (FromType->isRecordType() || ToType->isRecordType())
418 return false;
419
420 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000421 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000422 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000423 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000424 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000425 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000426
427 // The first conversion can be an lvalue-to-rvalue conversion,
428 // array-to-pointer conversion, or function-to-pointer conversion
429 // (C++ 4p1).
430
431 // Lvalue-to-rvalue conversion (C++ 4.1):
432 // An lvalue (3.10) of a non-function, non-array type T can be
433 // converted to an rvalue.
434 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
435 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000436 !FromType->isFunctionType() && !FromType->isArrayType() &&
437 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000438 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000439
440 // If T is a non-class type, the type of the rvalue is the
441 // cv-unqualified version of T. Otherwise, the type of the rvalue
442 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000443 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000444 }
445 // Array-to-pointer conversion (C++ 4.2)
446 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000447 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000448
449 // An lvalue or rvalue of type "array of N T" or "array of unknown
450 // bound of T" can be converted to an rvalue of type "pointer to
451 // T" (C++ 4.2p1).
452 FromType = Context.getArrayDecayedType(FromType);
453
454 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
455 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000456 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000457
458 // For the purpose of ranking in overload resolution
459 // (13.3.3.1.1), this conversion is considered an
460 // array-to-pointer conversion followed by a qualification
461 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000462 SCS.Second = ICK_Identity;
463 SCS.Third = ICK_Qualification;
464 SCS.ToTypePtr = ToType.getAsOpaquePtr();
465 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000466 }
467 }
468 // Function-to-pointer conversion (C++ 4.3).
469 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000470 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000471
472 // An lvalue of function type T can be converted to an rvalue of
473 // type "pointer to T." The result is a pointer to the
474 // function. (C++ 4.3p1).
475 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000476 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000477 // Address of overloaded function (C++ [over.over]).
478 else if (FunctionDecl *Fn
479 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
480 SCS.First = ICK_Function_To_Pointer;
481
482 // We were able to resolve the address of the overloaded function,
483 // so we can convert to the type of that function.
484 FromType = Fn->getType();
485 if (ToType->isReferenceType())
486 FromType = Context.getReferenceType(FromType);
487 else
488 FromType = Context.getPointerType(FromType);
489 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490 // We don't require any conversions for the first step.
491 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000492 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000493 }
494
495 // The second conversion can be an integral promotion, floating
496 // point promotion, integral conversion, floating point conversion,
497 // floating-integral conversion, pointer conversion,
498 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor45920e82008-12-19 17:40:08 +0000499 bool IncompatibleObjC = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000500 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
501 Context.getCanonicalType(ToType).getUnqualifiedType()) {
502 // The unqualified versions of the types are the same: there's no
503 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000504 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 }
506 // Integral promotion (C++ 4.5).
507 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000508 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000509 FromType = ToType.getUnqualifiedType();
510 }
511 // Floating point promotion (C++ 4.6).
512 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000513 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514 FromType = ToType.getUnqualifiedType();
515 }
516 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000517 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000518 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000519 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000520 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000521 FromType = ToType.getUnqualifiedType();
522 }
523 // Floating point conversions (C++ 4.8).
524 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000525 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000526 FromType = ToType.getUnqualifiedType();
527 }
528 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000529 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000530 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000531 ToType->isIntegralType() && !ToType->isBooleanType() &&
532 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
534 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000535 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000536 FromType = ToType.getUnqualifiedType();
537 }
538 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000539 else if (IsPointerConversion(From, FromType, ToType, FromType,
540 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000541 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000542 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000543 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000544 // FIXME: Pointer to member conversions (4.11).
545 // Boolean conversions (C++ 4.12).
546 // FIXME: pointer-to-member type
547 else if (ToType->isBooleanType() &&
548 (FromType->isArithmeticType() ||
549 FromType->isEnumeralType() ||
550 FromType->isPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000551 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000552 FromType = Context.BoolTy;
553 } else {
554 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000555 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000556 }
557
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000558 QualType CanonFrom;
559 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000560 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000561 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000562 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000563 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000564 CanonFrom = Context.getCanonicalType(FromType);
565 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000566 } else {
567 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000568 SCS.Third = ICK_Identity;
569
570 // C++ [over.best.ics]p6:
571 // [...] Any difference in top-level cv-qualification is
572 // subsumed by the initialization itself and does not constitute
573 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000574 CanonFrom = Context.getCanonicalType(FromType);
575 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000576 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000577 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
578 FromType = ToType;
579 CanonFrom = CanonTo;
580 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000581 }
582
583 // If we have not converted the argument type to the parameter type,
584 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000585 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000586 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000587
Douglas Gregor60d62c22008-10-31 16:23:19 +0000588 SCS.ToTypePtr = FromType.getAsOpaquePtr();
589 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000590}
591
592/// IsIntegralPromotion - Determines whether the conversion from the
593/// expression From (whose potentially-adjusted type is FromType) to
594/// ToType is an integral promotion (C++ 4.5). If so, returns true and
595/// sets PromotedType to the promoted type.
596bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
597{
598 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000599 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000600 if (!To) {
601 return false;
602 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000603
604 // An rvalue of type char, signed char, unsigned char, short int, or
605 // unsigned short int can be converted to an rvalue of type int if
606 // int can represent all the values of the source type; otherwise,
607 // the source rvalue can be converted to an rvalue of type unsigned
608 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000609 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000610 if (// We can promote any signed, promotable integer type to an int
611 (FromType->isSignedIntegerType() ||
612 // We can promote any unsigned integer type whose size is
613 // less than int to an int.
614 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000615 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000616 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000617 }
618
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000619 return To->getKind() == BuiltinType::UInt;
620 }
621
622 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
623 // can be converted to an rvalue of the first of the following types
624 // that can represent all the values of its underlying type: int,
625 // unsigned int, long, or unsigned long (C++ 4.5p2).
626 if ((FromType->isEnumeralType() || FromType->isWideCharType())
627 && ToType->isIntegerType()) {
628 // Determine whether the type we're converting from is signed or
629 // unsigned.
630 bool FromIsSigned;
631 uint64_t FromSize = Context.getTypeSize(FromType);
632 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
633 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
634 FromIsSigned = UnderlyingType->isSignedIntegerType();
635 } else {
636 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
637 FromIsSigned = true;
638 }
639
640 // The types we'll try to promote to, in the appropriate
641 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000642 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000643 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000644 Context.LongTy, Context.UnsignedLongTy ,
645 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000646 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000647 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000648 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
649 if (FromSize < ToSize ||
650 (FromSize == ToSize &&
651 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
652 // We found the type that we can promote to. If this is the
653 // type we wanted, we have a promotion. Otherwise, no
654 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000655 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000656 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
657 }
658 }
659 }
660
661 // An rvalue for an integral bit-field (9.6) can be converted to an
662 // rvalue of type int if int can represent all the values of the
663 // bit-field; otherwise, it can be converted to unsigned int if
664 // unsigned int can represent all the values of the bit-field. If
665 // the bit-field is larger yet, no integral promotion applies to
666 // it. If the bit-field has an enumerated type, it is treated as any
667 // other value of that type for promotion purposes (C++ 4.5p3).
668 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
669 using llvm::APSInt;
Douglas Gregor86f19402008-12-20 23:49:58 +0000670 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
671 APSInt BitWidth;
672 if (MemberDecl->isBitField() &&
673 FromType->isIntegralType() && !FromType->isEnumeralType() &&
674 From->isIntegerConstantExpr(BitWidth, Context)) {
675 APSInt ToSize(Context.getTypeSize(ToType));
676
677 // Are we promoting to an int from a bitfield that fits in an int?
678 if (BitWidth < ToSize ||
679 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
680 return To->getKind() == BuiltinType::Int;
681 }
682
683 // Are we promoting to an unsigned int from an unsigned bitfield
684 // that fits into an unsigned int?
685 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
686 return To->getKind() == BuiltinType::UInt;
687 }
688
689 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000690 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000691 }
692 }
693
694 // An rvalue of type bool can be converted to an rvalue of type int,
695 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000696 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000697 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000698 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000699
700 return false;
701}
702
703/// IsFloatingPointPromotion - Determines whether the conversion from
704/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
705/// returns true and sets PromotedType to the promoted type.
706bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
707{
708 /// An rvalue of type float can be converted to an rvalue of type
709 /// double. (C++ 4.6p1).
710 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
711 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
712 if (FromBuiltin->getKind() == BuiltinType::Float &&
713 ToBuiltin->getKind() == BuiltinType::Double)
714 return true;
715
716 return false;
717}
718
Douglas Gregorcb7de522008-11-26 23:31:11 +0000719/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
720/// the pointer type FromPtr to a pointer to type ToPointee, with the
721/// same type qualifiers as FromPtr has on its pointee type. ToType,
722/// if non-empty, will be a pointer to ToType that may or may not have
723/// the right set of qualifiers on its pointee.
724static QualType
725BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
726 QualType ToPointee, QualType ToType,
727 ASTContext &Context) {
728 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
729 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
730 unsigned Quals = CanonFromPointee.getCVRQualifiers();
731
732 // Exact qualifier match -> return the pointer type we're converting to.
733 if (CanonToPointee.getCVRQualifiers() == Quals) {
734 // ToType is exactly what we need. Return it.
735 if (ToType.getTypePtr())
736 return ToType;
737
738 // Build a pointer to ToPointee. It has the right qualifiers
739 // already.
740 return Context.getPointerType(ToPointee);
741 }
742
743 // Just build a canonical type that has the right qualifiers.
744 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
745}
746
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000747/// IsPointerConversion - Determines whether the conversion of the
748/// expression From, which has the (possibly adjusted) type FromType,
749/// can be converted to the type ToType via a pointer conversion (C++
750/// 4.10). If so, returns true and places the converted type (that
751/// might differ from ToType in its cv-qualifiers at some level) into
752/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000753///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000754/// This routine also supports conversions to and from block pointers
755/// and conversions with Objective-C's 'id', 'id<protocols...>', and
756/// pointers to interfaces. FIXME: Once we've determined the
757/// appropriate overloading rules for Objective-C, we may want to
758/// split the Objective-C checks into a different routine; however,
759/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000760/// conversions, so for now they live here. IncompatibleObjC will be
761/// set if the conversion is an allowed Objective-C conversion that
762/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000763bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000764 QualType& ConvertedType,
765 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000766{
Douglas Gregor45920e82008-12-19 17:40:08 +0000767 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000768 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
769 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000770
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000771 // Conversion from a null pointer constant to any Objective-C pointer type.
772 if (Context.isObjCObjectPointerType(ToType) &&
773 From->isNullPointerConstant(Context)) {
774 ConvertedType = ToType;
775 return true;
776 }
777
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000778 // Blocks: Block pointers can be converted to void*.
779 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
780 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
781 ConvertedType = ToType;
782 return true;
783 }
784 // Blocks: A null pointer constant can be converted to a block
785 // pointer type.
786 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
787 ConvertedType = ToType;
788 return true;
789 }
790
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000791 const PointerType* ToTypePtr = ToType->getAsPointerType();
792 if (!ToTypePtr)
793 return false;
794
795 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
796 if (From->isNullPointerConstant(Context)) {
797 ConvertedType = ToType;
798 return true;
799 }
Sebastian Redl07779722008-10-31 14:43:28 +0000800
Douglas Gregorcb7de522008-11-26 23:31:11 +0000801 // Beyond this point, both types need to be pointers.
802 const PointerType *FromTypePtr = FromType->getAsPointerType();
803 if (!FromTypePtr)
804 return false;
805
806 QualType FromPointeeType = FromTypePtr->getPointeeType();
807 QualType ToPointeeType = ToTypePtr->getPointeeType();
808
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000809 // An rvalue of type "pointer to cv T," where T is an object type,
810 // can be converted to an rvalue of type "pointer to cv void" (C++
811 // 4.10p2).
Douglas Gregorc7887512008-12-19 19:13:09 +0000812 if (FromPointeeType->isIncompleteOrObjectType() &&
813 ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000814 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
815 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000816 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000817 return true;
818 }
819
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000820 // C++ [conv.ptr]p3:
821 //
822 // An rvalue of type "pointer to cv D," where D is a class type,
823 // can be converted to an rvalue of type "pointer to cv B," where
824 // B is a base class (clause 10) of D. If B is an inaccessible
825 // (clause 11) or ambiguous (10.2) base class of D, a program that
826 // necessitates this conversion is ill-formed. The result of the
827 // conversion is a pointer to the base class sub-object of the
828 // derived class object. The null pointer value is converted to
829 // the null pointer value of the destination type.
830 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000831 // Note that we do not check for ambiguity or inaccessibility
832 // here. That is handled by CheckPointerConversion.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000833 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
834 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000835 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
836 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000837 ToType, Context);
838 return true;
839 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000840
Douglas Gregorc7887512008-12-19 19:13:09 +0000841 return false;
842}
843
844/// isObjCPointerConversion - Determines whether this is an
845/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
846/// with the same arguments and return values.
847bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
848 QualType& ConvertedType,
849 bool &IncompatibleObjC) {
850 if (!getLangOptions().ObjC1)
851 return false;
852
853 // Conversions with Objective-C's id<...>.
854 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
855 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
856 ConvertedType = ToType;
857 return true;
858 }
859
860 const PointerType* ToTypePtr = ToType->getAsPointerType();
861 if (!ToTypePtr)
862 return false;
863
864 // Beyond this point, both types need to be pointers.
865 const PointerType *FromTypePtr = FromType->getAsPointerType();
866 if (!FromTypePtr)
867 return false;
868
869 QualType FromPointeeType = FromTypePtr->getPointeeType();
870 QualType ToPointeeType = ToTypePtr->getPointeeType();
871
Douglas Gregorcb7de522008-11-26 23:31:11 +0000872 // Objective C++: We're able to convert from a pointer to an
873 // interface to a pointer to a different interface.
874 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
875 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
876 if (FromIface && ToIface &&
877 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000878 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
879 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000880 ToType, Context);
881 return true;
882 }
883
Douglas Gregor45920e82008-12-19 17:40:08 +0000884 if (FromIface && ToIface &&
885 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
886 // Okay: this is some kind of implicit downcast of Objective-C
887 // interfaces, which is permitted. However, we're going to
888 // complain about it.
889 IncompatibleObjC = true;
890 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
891 ToPointeeType,
892 ToType, Context);
893 return true;
894 }
895
Douglas Gregorcb7de522008-11-26 23:31:11 +0000896 // Objective C++: We're able to convert between "id" and a pointer
897 // to any interface (in both directions).
898 if ((FromIface && Context.isObjCIdType(ToPointeeType))
899 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000900 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
901 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000902 ToType, Context);
903 return true;
904 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000905
Douglas Gregordda78892008-12-18 23:43:31 +0000906 // Objective C++: Allow conversions between the Objective-C "id" and
907 // "Class", in either direction.
908 if ((Context.isObjCIdType(FromPointeeType) &&
909 Context.isObjCClassType(ToPointeeType)) ||
910 (Context.isObjCClassType(FromPointeeType) &&
911 Context.isObjCIdType(ToPointeeType))) {
912 ConvertedType = ToType;
913 return true;
914 }
915
Douglas Gregorc7887512008-12-19 19:13:09 +0000916 // If we have pointers to pointers, recursively check whether this
917 // is an Objective-C conversion.
918 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
919 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
920 IncompatibleObjC)) {
921 // We always complain about this conversion.
922 IncompatibleObjC = true;
923 ConvertedType = ToType;
924 return true;
925 }
926
927 // If we have pointers to functions, check whether the only
928 // differences in the argument and result types are in Objective-C
929 // pointer conversions. If so, we permit the conversion (but
930 // complain about it).
931 const FunctionTypeProto *FromFunctionType
932 = FromPointeeType->getAsFunctionTypeProto();
933 const FunctionTypeProto *ToFunctionType
934 = ToPointeeType->getAsFunctionTypeProto();
935 if (FromFunctionType && ToFunctionType) {
936 // If the function types are exactly the same, this isn't an
937 // Objective-C pointer conversion.
938 if (Context.getCanonicalType(FromPointeeType)
939 == Context.getCanonicalType(ToPointeeType))
940 return false;
941
942 // Perform the quick checks that will tell us whether these
943 // function types are obviously different.
944 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
945 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
946 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
947 return false;
948
949 bool HasObjCConversion = false;
950 if (Context.getCanonicalType(FromFunctionType->getResultType())
951 == Context.getCanonicalType(ToFunctionType->getResultType())) {
952 // Okay, the types match exactly. Nothing to do.
953 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
954 ToFunctionType->getResultType(),
955 ConvertedType, IncompatibleObjC)) {
956 // Okay, we have an Objective-C pointer conversion.
957 HasObjCConversion = true;
958 } else {
959 // Function types are too different. Abort.
960 return false;
961 }
962
963 // Check argument types.
964 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
965 ArgIdx != NumArgs; ++ArgIdx) {
966 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
967 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
968 if (Context.getCanonicalType(FromArgType)
969 == Context.getCanonicalType(ToArgType)) {
970 // Okay, the types match exactly. Nothing to do.
971 } else if (isObjCPointerConversion(FromArgType, ToArgType,
972 ConvertedType, IncompatibleObjC)) {
973 // Okay, we have an Objective-C pointer conversion.
974 HasObjCConversion = true;
975 } else {
976 // Argument types are too different. Abort.
977 return false;
978 }
979 }
980
981 if (HasObjCConversion) {
982 // We had an Objective-C conversion. Allow this pointer
983 // conversion, but complain about it.
984 ConvertedType = ToType;
985 IncompatibleObjC = true;
986 return true;
987 }
988 }
989
990 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000991}
992
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000993/// CheckPointerConversion - Check the pointer conversion from the
994/// expression From to the type ToType. This routine checks for
995/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
996/// conversions for which IsPointerConversion has already returned
997/// true. It returns true and produces a diagnostic if there was an
998/// error, or returns false otherwise.
999bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1000 QualType FromType = From->getType();
1001
1002 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1003 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl07779722008-10-31 14:43:28 +00001004 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1005 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001006 QualType FromPointeeType = FromPtrType->getPointeeType(),
1007 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001008
1009 // Objective-C++ conversions are always okay.
1010 // FIXME: We should have a different class of conversions for
1011 // the Objective-C++ implicit conversions.
1012 if (Context.isObjCIdType(FromPointeeType) ||
1013 Context.isObjCIdType(ToPointeeType) ||
1014 Context.isObjCClassType(FromPointeeType) ||
1015 Context.isObjCClassType(ToPointeeType))
1016 return false;
1017
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001018 if (FromPointeeType->isRecordType() &&
1019 ToPointeeType->isRecordType()) {
1020 // We must have a derived-to-base conversion. Check an
1021 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001022 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1023 From->getExprLoc(),
1024 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001025 }
1026 }
1027
1028 return false;
1029}
1030
Douglas Gregor98cd5992008-10-21 23:43:52 +00001031/// IsQualificationConversion - Determines whether the conversion from
1032/// an rvalue of type FromType to ToType is a qualification conversion
1033/// (C++ 4.4).
1034bool
1035Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1036{
1037 FromType = Context.getCanonicalType(FromType);
1038 ToType = Context.getCanonicalType(ToType);
1039
1040 // If FromType and ToType are the same type, this is not a
1041 // qualification conversion.
1042 if (FromType == ToType)
1043 return false;
1044
1045 // (C++ 4.4p4):
1046 // A conversion can add cv-qualifiers at levels other than the first
1047 // in multi-level pointers, subject to the following rules: [...]
1048 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001049 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001050 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001051 // Within each iteration of the loop, we check the qualifiers to
1052 // determine if this still looks like a qualification
1053 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001054 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001055 // until there are no more pointers or pointers-to-members left to
1056 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001057 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001058
1059 // -- for every j > 0, if const is in cv 1,j then const is in cv
1060 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001061 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001062 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001063
Douglas Gregor98cd5992008-10-21 23:43:52 +00001064 // -- if the cv 1,j and cv 2,j are different, then const is in
1065 // every cv for 0 < k < j.
1066 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001067 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001068 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001069
Douglas Gregor98cd5992008-10-21 23:43:52 +00001070 // Keep track of whether all prior cv-qualifiers in the "to" type
1071 // include const.
1072 PreviousToQualsIncludeConst
1073 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001074 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001075
1076 // We are left with FromType and ToType being the pointee types
1077 // after unwrapping the original FromType and ToType the same number
1078 // of types. If we unwrapped any pointers, and if FromType and
1079 // ToType have the same unqualified type (since we checked
1080 // qualifiers above), then this is a qualification conversion.
1081 return UnwrappedAnyPointer &&
1082 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1083}
1084
Douglas Gregor60d62c22008-10-31 16:23:19 +00001085/// IsUserDefinedConversion - Determines whether there is a
1086/// user-defined conversion sequence (C++ [over.ics.user]) that
1087/// converts expression From to the type ToType. If such a conversion
1088/// exists, User will contain the user-defined conversion sequence
1089/// that performs such a conversion and this routine will return
1090/// true. Otherwise, this routine returns false and User is
1091/// unspecified.
1092bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1093 UserDefinedConversionSequence& User)
1094{
1095 OverloadCandidateSet CandidateSet;
1096 if (const CXXRecordType *ToRecordType
1097 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
1098 // C++ [over.match.ctor]p1:
1099 // When objects of class type are direct-initialized (8.5), or
1100 // copy-initialized from an expression of the same or a
1101 // derived class type (8.5), overload resolution selects the
1102 // constructor. [...] For copy-initialization, the candidate
1103 // functions are all the converting constructors (12.3.1) of
1104 // that class. The argument list is the expression-list within
1105 // the parentheses of the initializer.
1106 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001107 DeclarationName ConstructorName
1108 = Context.DeclarationNames.getCXXConstructorName(
1109 Context.getCanonicalType(ToType));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001110 DeclContext::lookup_iterator Con, ConEnd;
1111 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(Context, ConstructorName);
1112 Con != ConEnd; ++Con) {
1113 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001114 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +00001115 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1116 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001117 }
1118 }
1119
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001120 if (const CXXRecordType *FromRecordType
1121 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
1122 // Add all of the conversion functions as candidates.
1123 // FIXME: Look for conversions in base classes!
1124 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
1125 OverloadedFunctionDecl *Conversions
1126 = FromRecordDecl->getConversionFunctions();
1127 for (OverloadedFunctionDecl::function_iterator Func
1128 = Conversions->function_begin();
1129 Func != Conversions->function_end(); ++Func) {
1130 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1131 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1132 }
1133 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001134
1135 OverloadCandidateSet::iterator Best;
1136 switch (BestViableFunction(CandidateSet, Best)) {
1137 case OR_Success:
1138 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001139 if (CXXConstructorDecl *Constructor
1140 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1141 // C++ [over.ics.user]p1:
1142 // If the user-defined conversion is specified by a
1143 // constructor (12.3.1), the initial standard conversion
1144 // sequence converts the source type to the type required by
1145 // the argument of the constructor.
1146 //
1147 // FIXME: What about ellipsis conversions?
1148 QualType ThisType = Constructor->getThisType(Context);
1149 User.Before = Best->Conversions[0].Standard;
1150 User.ConversionFunction = Constructor;
1151 User.After.setAsIdentityConversion();
1152 User.After.FromTypePtr
1153 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1154 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1155 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001156 } else if (CXXConversionDecl *Conversion
1157 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1158 // C++ [over.ics.user]p1:
1159 //
1160 // [...] If the user-defined conversion is specified by a
1161 // conversion function (12.3.2), the initial standard
1162 // conversion sequence converts the source type to the
1163 // implicit object parameter of the conversion function.
1164 User.Before = Best->Conversions[0].Standard;
1165 User.ConversionFunction = Conversion;
1166
1167 // C++ [over.ics.user]p2:
1168 // The second standard conversion sequence converts the
1169 // result of the user-defined conversion to the target type
1170 // for the sequence. Since an implicit conversion sequence
1171 // is an initialization, the special rules for
1172 // initialization by user-defined conversion apply when
1173 // selecting the best user-defined conversion for a
1174 // user-defined conversion sequence (see 13.3.3 and
1175 // 13.3.3.1).
1176 User.After = Best->FinalConversion;
1177 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001178 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001179 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001180 return false;
1181 }
1182
1183 case OR_No_Viable_Function:
1184 // No conversion here! We're done.
1185 return false;
1186
1187 case OR_Ambiguous:
1188 // FIXME: See C++ [over.best.ics]p10 for the handling of
1189 // ambiguous conversion sequences.
1190 return false;
1191 }
1192
1193 return false;
1194}
1195
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001196/// CompareImplicitConversionSequences - Compare two implicit
1197/// conversion sequences to determine whether one is better than the
1198/// other or if they are indistinguishable (C++ 13.3.3.2).
1199ImplicitConversionSequence::CompareKind
1200Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1201 const ImplicitConversionSequence& ICS2)
1202{
1203 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1204 // conversion sequences (as defined in 13.3.3.1)
1205 // -- a standard conversion sequence (13.3.3.1.1) is a better
1206 // conversion sequence than a user-defined conversion sequence or
1207 // an ellipsis conversion sequence, and
1208 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1209 // conversion sequence than an ellipsis conversion sequence
1210 // (13.3.3.1.3).
1211 //
1212 if (ICS1.ConversionKind < ICS2.ConversionKind)
1213 return ImplicitConversionSequence::Better;
1214 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1215 return ImplicitConversionSequence::Worse;
1216
1217 // Two implicit conversion sequences of the same form are
1218 // indistinguishable conversion sequences unless one of the
1219 // following rules apply: (C++ 13.3.3.2p3):
1220 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1221 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1222 else if (ICS1.ConversionKind ==
1223 ImplicitConversionSequence::UserDefinedConversion) {
1224 // User-defined conversion sequence U1 is a better conversion
1225 // sequence than another user-defined conversion sequence U2 if
1226 // they contain the same user-defined conversion function or
1227 // constructor and if the second standard conversion sequence of
1228 // U1 is better than the second standard conversion sequence of
1229 // U2 (C++ 13.3.3.2p3).
1230 if (ICS1.UserDefined.ConversionFunction ==
1231 ICS2.UserDefined.ConversionFunction)
1232 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1233 ICS2.UserDefined.After);
1234 }
1235
1236 return ImplicitConversionSequence::Indistinguishable;
1237}
1238
1239/// CompareStandardConversionSequences - Compare two standard
1240/// conversion sequences to determine whether one is better than the
1241/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1242ImplicitConversionSequence::CompareKind
1243Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1244 const StandardConversionSequence& SCS2)
1245{
1246 // Standard conversion sequence S1 is a better conversion sequence
1247 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1248
1249 // -- S1 is a proper subsequence of S2 (comparing the conversion
1250 // sequences in the canonical form defined by 13.3.3.1.1,
1251 // excluding any Lvalue Transformation; the identity conversion
1252 // sequence is considered to be a subsequence of any
1253 // non-identity conversion sequence) or, if not that,
1254 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1255 // Neither is a proper subsequence of the other. Do nothing.
1256 ;
1257 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1258 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1259 (SCS1.Second == ICK_Identity &&
1260 SCS1.Third == ICK_Identity))
1261 // SCS1 is a proper subsequence of SCS2.
1262 return ImplicitConversionSequence::Better;
1263 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1264 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1265 (SCS2.Second == ICK_Identity &&
1266 SCS2.Third == ICK_Identity))
1267 // SCS2 is a proper subsequence of SCS1.
1268 return ImplicitConversionSequence::Worse;
1269
1270 // -- the rank of S1 is better than the rank of S2 (by the rules
1271 // defined below), or, if not that,
1272 ImplicitConversionRank Rank1 = SCS1.getRank();
1273 ImplicitConversionRank Rank2 = SCS2.getRank();
1274 if (Rank1 < Rank2)
1275 return ImplicitConversionSequence::Better;
1276 else if (Rank2 < Rank1)
1277 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001278
Douglas Gregor57373262008-10-22 14:17:15 +00001279 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1280 // are indistinguishable unless one of the following rules
1281 // applies:
1282
1283 // A conversion that is not a conversion of a pointer, or
1284 // pointer to member, to bool is better than another conversion
1285 // that is such a conversion.
1286 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1287 return SCS2.isPointerConversionToBool()
1288 ? ImplicitConversionSequence::Better
1289 : ImplicitConversionSequence::Worse;
1290
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001291 // C++ [over.ics.rank]p4b2:
1292 //
1293 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001294 // conversion of B* to A* is better than conversion of B* to
1295 // void*, and conversion of A* to void* is better than conversion
1296 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001297 bool SCS1ConvertsToVoid
1298 = SCS1.isPointerConversionToVoidPointer(Context);
1299 bool SCS2ConvertsToVoid
1300 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001301 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1302 // Exactly one of the conversion sequences is a conversion to
1303 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001304 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1305 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001306 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1307 // Neither conversion sequence converts to a void pointer; compare
1308 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001309 if (ImplicitConversionSequence::CompareKind DerivedCK
1310 = CompareDerivedToBaseConversions(SCS1, SCS2))
1311 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001312 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1313 // Both conversion sequences are conversions to void
1314 // pointers. Compare the source types to determine if there's an
1315 // inheritance relationship in their sources.
1316 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1317 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1318
1319 // Adjust the types we're converting from via the array-to-pointer
1320 // conversion, if we need to.
1321 if (SCS1.First == ICK_Array_To_Pointer)
1322 FromType1 = Context.getArrayDecayedType(FromType1);
1323 if (SCS2.First == ICK_Array_To_Pointer)
1324 FromType2 = Context.getArrayDecayedType(FromType2);
1325
1326 QualType FromPointee1
1327 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1328 QualType FromPointee2
1329 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1330
1331 if (IsDerivedFrom(FromPointee2, FromPointee1))
1332 return ImplicitConversionSequence::Better;
1333 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1334 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001335
1336 // Objective-C++: If one interface is more specific than the
1337 // other, it is the better one.
1338 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1339 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1340 if (FromIface1 && FromIface1) {
1341 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1342 return ImplicitConversionSequence::Better;
1343 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1344 return ImplicitConversionSequence::Worse;
1345 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001346 }
Douglas Gregor57373262008-10-22 14:17:15 +00001347
1348 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1349 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001350 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001351 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001352 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001353
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001354 // C++ [over.ics.rank]p3b4:
1355 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1356 // which the references refer are the same type except for
1357 // top-level cv-qualifiers, and the type to which the reference
1358 // initialized by S2 refers is more cv-qualified than the type
1359 // to which the reference initialized by S1 refers.
1360 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1361 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1362 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1363 T1 = Context.getCanonicalType(T1);
1364 T2 = Context.getCanonicalType(T2);
1365 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1366 if (T2.isMoreQualifiedThan(T1))
1367 return ImplicitConversionSequence::Better;
1368 else if (T1.isMoreQualifiedThan(T2))
1369 return ImplicitConversionSequence::Worse;
1370 }
1371 }
Douglas Gregor57373262008-10-22 14:17:15 +00001372
1373 return ImplicitConversionSequence::Indistinguishable;
1374}
1375
1376/// CompareQualificationConversions - Compares two standard conversion
1377/// sequences to determine whether they can be ranked based on their
1378/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1379ImplicitConversionSequence::CompareKind
1380Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1381 const StandardConversionSequence& SCS2)
1382{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001383 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001384 // -- S1 and S2 differ only in their qualification conversion and
1385 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1386 // cv-qualification signature of type T1 is a proper subset of
1387 // the cv-qualification signature of type T2, and S1 is not the
1388 // deprecated string literal array-to-pointer conversion (4.2).
1389 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1390 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1391 return ImplicitConversionSequence::Indistinguishable;
1392
1393 // FIXME: the example in the standard doesn't use a qualification
1394 // conversion (!)
1395 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1396 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1397 T1 = Context.getCanonicalType(T1);
1398 T2 = Context.getCanonicalType(T2);
1399
1400 // If the types are the same, we won't learn anything by unwrapped
1401 // them.
1402 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1403 return ImplicitConversionSequence::Indistinguishable;
1404
1405 ImplicitConversionSequence::CompareKind Result
1406 = ImplicitConversionSequence::Indistinguishable;
1407 while (UnwrapSimilarPointerTypes(T1, T2)) {
1408 // Within each iteration of the loop, we check the qualifiers to
1409 // determine if this still looks like a qualification
1410 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001411 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001412 // until there are no more pointers or pointers-to-members left
1413 // to unwrap. This essentially mimics what
1414 // IsQualificationConversion does, but here we're checking for a
1415 // strict subset of qualifiers.
1416 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1417 // The qualifiers are the same, so this doesn't tell us anything
1418 // about how the sequences rank.
1419 ;
1420 else if (T2.isMoreQualifiedThan(T1)) {
1421 // T1 has fewer qualifiers, so it could be the better sequence.
1422 if (Result == ImplicitConversionSequence::Worse)
1423 // Neither has qualifiers that are a subset of the other's
1424 // qualifiers.
1425 return ImplicitConversionSequence::Indistinguishable;
1426
1427 Result = ImplicitConversionSequence::Better;
1428 } else if (T1.isMoreQualifiedThan(T2)) {
1429 // T2 has fewer qualifiers, so it could be the better sequence.
1430 if (Result == ImplicitConversionSequence::Better)
1431 // Neither has qualifiers that are a subset of the other's
1432 // qualifiers.
1433 return ImplicitConversionSequence::Indistinguishable;
1434
1435 Result = ImplicitConversionSequence::Worse;
1436 } else {
1437 // Qualifiers are disjoint.
1438 return ImplicitConversionSequence::Indistinguishable;
1439 }
1440
1441 // If the types after this point are equivalent, we're done.
1442 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1443 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001444 }
1445
Douglas Gregor57373262008-10-22 14:17:15 +00001446 // Check that the winning standard conversion sequence isn't using
1447 // the deprecated string literal array to pointer conversion.
1448 switch (Result) {
1449 case ImplicitConversionSequence::Better:
1450 if (SCS1.Deprecated)
1451 Result = ImplicitConversionSequence::Indistinguishable;
1452 break;
1453
1454 case ImplicitConversionSequence::Indistinguishable:
1455 break;
1456
1457 case ImplicitConversionSequence::Worse:
1458 if (SCS2.Deprecated)
1459 Result = ImplicitConversionSequence::Indistinguishable;
1460 break;
1461 }
1462
1463 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001464}
1465
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001466/// CompareDerivedToBaseConversions - Compares two standard conversion
1467/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001468/// various kinds of derived-to-base conversions (C++
1469/// [over.ics.rank]p4b3). As part of these checks, we also look at
1470/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001471ImplicitConversionSequence::CompareKind
1472Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1473 const StandardConversionSequence& SCS2) {
1474 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1475 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1476 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1477 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1478
1479 // Adjust the types we're converting from via the array-to-pointer
1480 // conversion, if we need to.
1481 if (SCS1.First == ICK_Array_To_Pointer)
1482 FromType1 = Context.getArrayDecayedType(FromType1);
1483 if (SCS2.First == ICK_Array_To_Pointer)
1484 FromType2 = Context.getArrayDecayedType(FromType2);
1485
1486 // Canonicalize all of the types.
1487 FromType1 = Context.getCanonicalType(FromType1);
1488 ToType1 = Context.getCanonicalType(ToType1);
1489 FromType2 = Context.getCanonicalType(FromType2);
1490 ToType2 = Context.getCanonicalType(ToType2);
1491
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001492 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001493 //
1494 // If class B is derived directly or indirectly from class A and
1495 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001496 //
1497 // For Objective-C, we let A, B, and C also be Objective-C
1498 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001499
1500 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001501 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001502 SCS2.Second == ICK_Pointer_Conversion &&
1503 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1504 FromType1->isPointerType() && FromType2->isPointerType() &&
1505 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001506 QualType FromPointee1
1507 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1508 QualType ToPointee1
1509 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1510 QualType FromPointee2
1511 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1512 QualType ToPointee2
1513 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001514
1515 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1516 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1517 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1518 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1519
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001520 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001521 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1522 if (IsDerivedFrom(ToPointee1, ToPointee2))
1523 return ImplicitConversionSequence::Better;
1524 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1525 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001526
1527 if (ToIface1 && ToIface2) {
1528 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1529 return ImplicitConversionSequence::Better;
1530 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1531 return ImplicitConversionSequence::Worse;
1532 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001533 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001534
1535 // -- conversion of B* to A* is better than conversion of C* to A*,
1536 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1537 if (IsDerivedFrom(FromPointee2, FromPointee1))
1538 return ImplicitConversionSequence::Better;
1539 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1540 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001541
1542 if (FromIface1 && FromIface2) {
1543 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1544 return ImplicitConversionSequence::Better;
1545 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1546 return ImplicitConversionSequence::Worse;
1547 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001548 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001549 }
1550
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001551 // Compare based on reference bindings.
1552 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1553 SCS1.Second == ICK_Derived_To_Base) {
1554 // -- binding of an expression of type C to a reference of type
1555 // B& is better than binding an expression of type C to a
1556 // reference of type A&,
1557 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1558 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1559 if (IsDerivedFrom(ToType1, ToType2))
1560 return ImplicitConversionSequence::Better;
1561 else if (IsDerivedFrom(ToType2, ToType1))
1562 return ImplicitConversionSequence::Worse;
1563 }
1564
Douglas Gregor225c41e2008-11-03 19:09:14 +00001565 // -- binding of an expression of type B to a reference of type
1566 // A& is better than binding an expression of type C to a
1567 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001568 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1569 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1570 if (IsDerivedFrom(FromType2, FromType1))
1571 return ImplicitConversionSequence::Better;
1572 else if (IsDerivedFrom(FromType1, FromType2))
1573 return ImplicitConversionSequence::Worse;
1574 }
1575 }
1576
1577
1578 // FIXME: conversion of A::* to B::* is better than conversion of
1579 // A::* to C::*,
1580
1581 // FIXME: conversion of B::* to C::* is better than conversion of
1582 // A::* to C::*, and
1583
Douglas Gregor225c41e2008-11-03 19:09:14 +00001584 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1585 SCS1.Second == ICK_Derived_To_Base) {
1586 // -- conversion of C to B is better than conversion of C to A,
1587 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1588 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1589 if (IsDerivedFrom(ToType1, ToType2))
1590 return ImplicitConversionSequence::Better;
1591 else if (IsDerivedFrom(ToType2, ToType1))
1592 return ImplicitConversionSequence::Worse;
1593 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001594
Douglas Gregor225c41e2008-11-03 19:09:14 +00001595 // -- conversion of B to A is better than conversion of C to A.
1596 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1597 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1598 if (IsDerivedFrom(FromType2, FromType1))
1599 return ImplicitConversionSequence::Better;
1600 else if (IsDerivedFrom(FromType1, FromType2))
1601 return ImplicitConversionSequence::Worse;
1602 }
1603 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001604
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001605 return ImplicitConversionSequence::Indistinguishable;
1606}
1607
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001608/// TryCopyInitialization - Try to copy-initialize a value of type
1609/// ToType from the expression From. Return the implicit conversion
1610/// sequence required to pass this argument, which may be a bad
1611/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001612/// a parameter of this type). If @p SuppressUserConversions, then we
1613/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001614ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001615Sema::TryCopyInitialization(Expr *From, QualType ToType,
1616 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001617 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001618 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001619 AssignConvertType ConvTy =
1620 CheckSingleAssignmentConstraints(ToType, From);
1621 ImplicitConversionSequence ICS;
1622 if (getLangOptions().NoExtensions? ConvTy != Compatible
1623 : ConvTy == Incompatible)
1624 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1625 else
1626 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1627 return ICS;
1628 } else if (ToType->isReferenceType()) {
1629 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001630 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001631 return ICS;
1632 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001633 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001634 }
1635}
1636
1637/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1638/// type ToType. Returns true (and emits a diagnostic) if there was
1639/// an error, returns false if the initialization succeeded.
1640bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1641 const char* Flavor) {
1642 if (!getLangOptions().CPlusPlus) {
1643 // In C, argument passing is the same as performing an assignment.
1644 QualType FromType = From->getType();
1645 AssignConvertType ConvTy =
1646 CheckSingleAssignmentConstraints(ToType, From);
1647
1648 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1649 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001650 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001651
1652 if (ToType->isReferenceType())
1653 return CheckReferenceInit(From, ToType);
1654
Douglas Gregor45920e82008-12-19 17:40:08 +00001655 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001656 return false;
1657
1658 return Diag(From->getSourceRange().getBegin(),
1659 diag::err_typecheck_convert_incompatible)
1660 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001661}
1662
Douglas Gregor96176b32008-11-18 23:14:02 +00001663/// TryObjectArgumentInitialization - Try to initialize the object
1664/// parameter of the given member function (@c Method) from the
1665/// expression @p From.
1666ImplicitConversionSequence
1667Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1668 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1669 unsigned MethodQuals = Method->getTypeQualifiers();
1670 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1671
1672 // Set up the conversion sequence as a "bad" conversion, to allow us
1673 // to exit early.
1674 ImplicitConversionSequence ICS;
1675 ICS.Standard.setAsIdentityConversion();
1676 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1677
1678 // We need to have an object of class type.
1679 QualType FromType = From->getType();
1680 if (!FromType->isRecordType())
1681 return ICS;
1682
1683 // The implicit object parmeter is has the type "reference to cv X",
1684 // where X is the class of which the function is a member
1685 // (C++ [over.match.funcs]p4). However, when finding an implicit
1686 // conversion sequence for the argument, we are not allowed to
1687 // create temporaries or perform user-defined conversions
1688 // (C++ [over.match.funcs]p5). We perform a simplified version of
1689 // reference binding here, that allows class rvalues to bind to
1690 // non-constant references.
1691
1692 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1693 // with the implicit object parameter (C++ [over.match.funcs]p5).
1694 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1695 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1696 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1697 return ICS;
1698
1699 // Check that we have either the same type or a derived type. It
1700 // affects the conversion rank.
1701 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1702 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1703 ICS.Standard.Second = ICK_Identity;
1704 else if (IsDerivedFrom(FromType, ClassType))
1705 ICS.Standard.Second = ICK_Derived_To_Base;
1706 else
1707 return ICS;
1708
1709 // Success. Mark this as a reference binding.
1710 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1711 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1712 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1713 ICS.Standard.ReferenceBinding = true;
1714 ICS.Standard.DirectBinding = true;
1715 return ICS;
1716}
1717
1718/// PerformObjectArgumentInitialization - Perform initialization of
1719/// the implicit object parameter for the given Method with the given
1720/// expression.
1721bool
1722Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1723 QualType ImplicitParamType
1724 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1725 ImplicitConversionSequence ICS
1726 = TryObjectArgumentInitialization(From, Method);
1727 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1728 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001729 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001730 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001731
1732 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1733 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1734 From->getSourceRange().getBegin(),
1735 From->getSourceRange()))
1736 return true;
1737
1738 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1739 return false;
1740}
1741
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001742/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001743/// candidate functions, using the given function call arguments. If
1744/// @p SuppressUserConversions, then don't allow user-defined
1745/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001746void
1747Sema::AddOverloadCandidate(FunctionDecl *Function,
1748 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001749 OverloadCandidateSet& CandidateSet,
1750 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001751{
1752 const FunctionTypeProto* Proto
1753 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1754 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001755 assert(!isa<CXXConversionDecl>(Function) &&
1756 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001757
Douglas Gregor88a35142008-12-22 05:46:06 +00001758 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
1759 // If we get here, it's because we're calling a member function
1760 // that is named without a member access expression (e.g.,
1761 // "this->f") that was either written explicitly or created
1762 // implicitly. This can happen with a qualified call to a member
1763 // function, e.g., X::f(). We use a NULL object as the implied
1764 // object argument (C++ [over.call.func]p3).
1765 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
1766 SuppressUserConversions);
1767 return;
1768 }
1769
1770
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001771 // Add this candidate
1772 CandidateSet.push_back(OverloadCandidate());
1773 OverloadCandidate& Candidate = CandidateSet.back();
1774 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00001775 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001776 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001777 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001778
1779 unsigned NumArgsInProto = Proto->getNumArgs();
1780
1781 // (C++ 13.3.2p2): A candidate function having fewer than m
1782 // parameters is viable only if it has an ellipsis in its parameter
1783 // list (8.3.5).
1784 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1785 Candidate.Viable = false;
1786 return;
1787 }
1788
1789 // (C++ 13.3.2p2): A candidate function having more than m parameters
1790 // is viable only if the (m+1)st parameter has a default argument
1791 // (8.3.6). For the purposes of overload resolution, the
1792 // parameter list is truncated on the right, so that there are
1793 // exactly m parameters.
1794 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1795 if (NumArgs < MinRequiredArgs) {
1796 // Not enough arguments.
1797 Candidate.Viable = false;
1798 return;
1799 }
1800
1801 // Determine the implicit conversion sequences for each of the
1802 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001803 Candidate.Conversions.resize(NumArgs);
1804 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1805 if (ArgIdx < NumArgsInProto) {
1806 // (C++ 13.3.2p3): for F to be a viable function, there shall
1807 // exist for each argument an implicit conversion sequence
1808 // (13.3.3.1) that converts that argument to the corresponding
1809 // parameter of F.
1810 QualType ParamType = Proto->getArgType(ArgIdx);
1811 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001812 = TryCopyInitialization(Args[ArgIdx], ParamType,
1813 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001814 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001815 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001816 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001817 break;
1818 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001819 } else {
1820 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1821 // argument for which there is no corresponding parameter is
1822 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1823 Candidate.Conversions[ArgIdx].ConversionKind
1824 = ImplicitConversionSequence::EllipsisConversion;
1825 }
1826 }
1827}
1828
Douglas Gregor96176b32008-11-18 23:14:02 +00001829/// AddMethodCandidate - Adds the given C++ member function to the set
1830/// of candidate functions, using the given function call arguments
1831/// and the object argument (@c Object). For example, in a call
1832/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1833/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1834/// allow user-defined conversions via constructors or conversion
1835/// operators.
1836void
1837Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1838 Expr **Args, unsigned NumArgs,
1839 OverloadCandidateSet& CandidateSet,
1840 bool SuppressUserConversions)
1841{
1842 const FunctionTypeProto* Proto
1843 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1844 assert(Proto && "Methods without a prototype cannot be overloaded");
1845 assert(!isa<CXXConversionDecl>(Method) &&
1846 "Use AddConversionCandidate for conversion functions");
1847
1848 // Add this candidate
1849 CandidateSet.push_back(OverloadCandidate());
1850 OverloadCandidate& Candidate = CandidateSet.back();
1851 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001852 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001853 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001854
1855 unsigned NumArgsInProto = Proto->getNumArgs();
1856
1857 // (C++ 13.3.2p2): A candidate function having fewer than m
1858 // parameters is viable only if it has an ellipsis in its parameter
1859 // list (8.3.5).
1860 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1861 Candidate.Viable = false;
1862 return;
1863 }
1864
1865 // (C++ 13.3.2p2): A candidate function having more than m parameters
1866 // is viable only if the (m+1)st parameter has a default argument
1867 // (8.3.6). For the purposes of overload resolution, the
1868 // parameter list is truncated on the right, so that there are
1869 // exactly m parameters.
1870 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1871 if (NumArgs < MinRequiredArgs) {
1872 // Not enough arguments.
1873 Candidate.Viable = false;
1874 return;
1875 }
1876
1877 Candidate.Viable = true;
1878 Candidate.Conversions.resize(NumArgs + 1);
1879
Douglas Gregor88a35142008-12-22 05:46:06 +00001880 if (Method->isStatic() || !Object)
1881 // The implicit object argument is ignored.
1882 Candidate.IgnoreObjectArgument = true;
1883 else {
1884 // Determine the implicit conversion sequence for the object
1885 // parameter.
1886 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1887 if (Candidate.Conversions[0].ConversionKind
1888 == ImplicitConversionSequence::BadConversion) {
1889 Candidate.Viable = false;
1890 return;
1891 }
Douglas Gregor96176b32008-11-18 23:14:02 +00001892 }
1893
1894 // Determine the implicit conversion sequences for each of the
1895 // arguments.
1896 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1897 if (ArgIdx < NumArgsInProto) {
1898 // (C++ 13.3.2p3): for F to be a viable function, there shall
1899 // exist for each argument an implicit conversion sequence
1900 // (13.3.3.1) that converts that argument to the corresponding
1901 // parameter of F.
1902 QualType ParamType = Proto->getArgType(ArgIdx);
1903 Candidate.Conversions[ArgIdx + 1]
1904 = TryCopyInitialization(Args[ArgIdx], ParamType,
1905 SuppressUserConversions);
1906 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1907 == ImplicitConversionSequence::BadConversion) {
1908 Candidate.Viable = false;
1909 break;
1910 }
1911 } else {
1912 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1913 // argument for which there is no corresponding parameter is
1914 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1915 Candidate.Conversions[ArgIdx + 1].ConversionKind
1916 = ImplicitConversionSequence::EllipsisConversion;
1917 }
1918 }
1919}
1920
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001921/// AddConversionCandidate - Add a C++ conversion function as a
1922/// candidate in the candidate set (C++ [over.match.conv],
1923/// C++ [over.match.copy]). From is the expression we're converting from,
1924/// and ToType is the type that we're eventually trying to convert to
1925/// (which may or may not be the same type as the type that the
1926/// conversion function produces).
1927void
1928Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1929 Expr *From, QualType ToType,
1930 OverloadCandidateSet& CandidateSet) {
1931 // Add this candidate
1932 CandidateSet.push_back(OverloadCandidate());
1933 OverloadCandidate& Candidate = CandidateSet.back();
1934 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001935 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001936 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001937 Candidate.FinalConversion.setAsIdentityConversion();
1938 Candidate.FinalConversion.FromTypePtr
1939 = Conversion->getConversionType().getAsOpaquePtr();
1940 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1941
Douglas Gregor96176b32008-11-18 23:14:02 +00001942 // Determine the implicit conversion sequence for the implicit
1943 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001944 Candidate.Viable = true;
1945 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00001946 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001947
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001948 if (Candidate.Conversions[0].ConversionKind
1949 == ImplicitConversionSequence::BadConversion) {
1950 Candidate.Viable = false;
1951 return;
1952 }
1953
1954 // To determine what the conversion from the result of calling the
1955 // conversion function to the type we're eventually trying to
1956 // convert to (ToType), we need to synthesize a call to the
1957 // conversion function and attempt copy initialization from it. This
1958 // makes sure that we get the right semantics with respect to
1959 // lvalues/rvalues and the type. Fortunately, we can allocate this
1960 // call on the stack and we don't need its arguments to be
1961 // well-formed.
1962 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1963 SourceLocation());
1964 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001965 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001966 CallExpr Call(&ConversionFn, 0, 0,
1967 Conversion->getConversionType().getNonReferenceType(),
1968 SourceLocation());
1969 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1970 switch (ICS.ConversionKind) {
1971 case ImplicitConversionSequence::StandardConversion:
1972 Candidate.FinalConversion = ICS.Standard;
1973 break;
1974
1975 case ImplicitConversionSequence::BadConversion:
1976 Candidate.Viable = false;
1977 break;
1978
1979 default:
1980 assert(false &&
1981 "Can only end up with a standard conversion sequence or failure");
1982 }
1983}
1984
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001985/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
1986/// converts the given @c Object to a function pointer via the
1987/// conversion function @c Conversion, and then attempts to call it
1988/// with the given arguments (C++ [over.call.object]p2-4). Proto is
1989/// the type of function that we'll eventually be calling.
1990void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
1991 const FunctionTypeProto *Proto,
1992 Expr *Object, Expr **Args, unsigned NumArgs,
1993 OverloadCandidateSet& CandidateSet) {
1994 CandidateSet.push_back(OverloadCandidate());
1995 OverloadCandidate& Candidate = CandidateSet.back();
1996 Candidate.Function = 0;
1997 Candidate.Surrogate = Conversion;
1998 Candidate.Viable = true;
1999 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002000 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002001 Candidate.Conversions.resize(NumArgs + 1);
2002
2003 // Determine the implicit conversion sequence for the implicit
2004 // object parameter.
2005 ImplicitConversionSequence ObjectInit
2006 = TryObjectArgumentInitialization(Object, Conversion);
2007 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2008 Candidate.Viable = false;
2009 return;
2010 }
2011
2012 // The first conversion is actually a user-defined conversion whose
2013 // first conversion is ObjectInit's standard conversion (which is
2014 // effectively a reference binding). Record it as such.
2015 Candidate.Conversions[0].ConversionKind
2016 = ImplicitConversionSequence::UserDefinedConversion;
2017 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2018 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2019 Candidate.Conversions[0].UserDefined.After
2020 = Candidate.Conversions[0].UserDefined.Before;
2021 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2022
2023 // Find the
2024 unsigned NumArgsInProto = Proto->getNumArgs();
2025
2026 // (C++ 13.3.2p2): A candidate function having fewer than m
2027 // parameters is viable only if it has an ellipsis in its parameter
2028 // list (8.3.5).
2029 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2030 Candidate.Viable = false;
2031 return;
2032 }
2033
2034 // Function types don't have any default arguments, so just check if
2035 // we have enough arguments.
2036 if (NumArgs < NumArgsInProto) {
2037 // Not enough arguments.
2038 Candidate.Viable = false;
2039 return;
2040 }
2041
2042 // Determine the implicit conversion sequences for each of the
2043 // arguments.
2044 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2045 if (ArgIdx < NumArgsInProto) {
2046 // (C++ 13.3.2p3): for F to be a viable function, there shall
2047 // exist for each argument an implicit conversion sequence
2048 // (13.3.3.1) that converts that argument to the corresponding
2049 // parameter of F.
2050 QualType ParamType = Proto->getArgType(ArgIdx);
2051 Candidate.Conversions[ArgIdx + 1]
2052 = TryCopyInitialization(Args[ArgIdx], ParamType,
2053 /*SuppressUserConversions=*/false);
2054 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2055 == ImplicitConversionSequence::BadConversion) {
2056 Candidate.Viable = false;
2057 break;
2058 }
2059 } else {
2060 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2061 // argument for which there is no corresponding parameter is
2062 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2063 Candidate.Conversions[ArgIdx + 1].ConversionKind
2064 = ImplicitConversionSequence::EllipsisConversion;
2065 }
2066 }
2067}
2068
Douglas Gregor447b69e2008-11-19 03:25:36 +00002069/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2070/// an acceptable non-member overloaded operator for a call whose
2071/// arguments have types T1 (and, if non-empty, T2). This routine
2072/// implements the check in C++ [over.match.oper]p3b2 concerning
2073/// enumeration types.
2074static bool
2075IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2076 QualType T1, QualType T2,
2077 ASTContext &Context) {
2078 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2079 return true;
2080
2081 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
2082 if (Proto->getNumArgs() < 1)
2083 return false;
2084
2085 if (T1->isEnumeralType()) {
2086 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2087 if (Context.getCanonicalType(T1).getUnqualifiedType()
2088 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2089 return true;
2090 }
2091
2092 if (Proto->getNumArgs() < 2)
2093 return false;
2094
2095 if (!T2.isNull() && T2->isEnumeralType()) {
2096 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2097 if (Context.getCanonicalType(T2).getUnqualifiedType()
2098 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2099 return true;
2100 }
2101
2102 return false;
2103}
2104
Douglas Gregor96176b32008-11-18 23:14:02 +00002105/// AddOperatorCandidates - Add the overloaded operator candidates for
2106/// the operator Op that was used in an operator expression such as "x
2107/// Op y". S is the scope in which the expression occurred (used for
2108/// name lookup of the operator), Args/NumArgs provides the operator
2109/// arguments, and CandidateSet will store the added overload
2110/// candidates. (C++ [over.match.oper]).
2111void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2112 Expr **Args, unsigned NumArgs,
2113 OverloadCandidateSet& CandidateSet) {
2114 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2115
2116 // C++ [over.match.oper]p3:
2117 // For a unary operator @ with an operand of a type whose
2118 // cv-unqualified version is T1, and for a binary operator @ with
2119 // a left operand of a type whose cv-unqualified version is T1 and
2120 // a right operand of a type whose cv-unqualified version is T2,
2121 // three sets of candidate functions, designated member
2122 // candidates, non-member candidates and built-in candidates, are
2123 // constructed as follows:
2124 QualType T1 = Args[0]->getType();
2125 QualType T2;
2126 if (NumArgs > 1)
2127 T2 = Args[1]->getType();
2128
2129 // -- If T1 is a class type, the set of member candidates is the
2130 // result of the qualified lookup of T1::operator@
2131 // (13.3.1.1.1); otherwise, the set of member candidates is
2132 // empty.
2133 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002134 DeclContext::lookup_const_iterator Oper, OperEnd;
2135 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(Context, OpName);
2136 Oper != OperEnd; ++Oper)
2137 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2138 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002139 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002140 }
2141
2142 // -- The set of non-member candidates is the result of the
2143 // unqualified lookup of operator@ in the context of the
2144 // expression according to the usual rules for name lookup in
2145 // unqualified function calls (3.4.2) except that all member
2146 // functions are ignored. However, if no operand has a class
2147 // type, only those non-member functions in the lookup set
2148 // that have a first parameter of type T1 or “reference to
2149 // (possibly cv-qualified) T1”, when T1 is an enumeration
2150 // type, or (if there is a right operand) a second parameter
2151 // of type T2 or “reference to (possibly cv-qualified) T2”,
2152 // when T2 is an enumeration type, are candidate functions.
2153 {
2154 NamedDecl *NonMemberOps = 0;
2155 for (IdentifierResolver::iterator I
2156 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
2157 I != IdResolver.end(); ++I) {
2158 // We don't need to check the identifier namespace, because
2159 // operator names can only be ordinary identifiers.
2160
2161 // Ignore member functions.
2162 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
2163 if (SD->getDeclContext()->isCXXRecord())
2164 continue;
2165 }
2166
2167 // We found something with this name. We're done.
2168 NonMemberOps = *I;
2169 break;
2170 }
2171
Douglas Gregor447b69e2008-11-19 03:25:36 +00002172 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) {
2173 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2174 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2175 /*SuppressUserConversions=*/false);
2176 } else if (OverloadedFunctionDecl *Ovl
2177 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002178 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2179 FEnd = Ovl->function_end();
Douglas Gregor447b69e2008-11-19 03:25:36 +00002180 F != FEnd; ++F) {
2181 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context))
2182 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2183 /*SuppressUserConversions=*/false);
2184 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002185 }
2186 }
2187
2188 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00002189 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor96176b32008-11-18 23:14:02 +00002190}
2191
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002192/// AddBuiltinCandidate - Add a candidate for a built-in
2193/// operator. ResultTy and ParamTys are the result and parameter types
2194/// of the built-in candidate, respectively. Args and NumArgs are the
2195/// arguments being passed to the candidate.
2196void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2197 Expr **Args, unsigned NumArgs,
2198 OverloadCandidateSet& CandidateSet) {
2199 // Add this candidate
2200 CandidateSet.push_back(OverloadCandidate());
2201 OverloadCandidate& Candidate = CandidateSet.back();
2202 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002203 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002204 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002205 Candidate.BuiltinTypes.ResultTy = ResultTy;
2206 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2207 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2208
2209 // Determine the implicit conversion sequences for each of the
2210 // arguments.
2211 Candidate.Viable = true;
2212 Candidate.Conversions.resize(NumArgs);
2213 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2214 Candidate.Conversions[ArgIdx]
2215 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
2216 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002217 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002218 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002219 break;
2220 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002221 }
2222}
2223
2224/// BuiltinCandidateTypeSet - A set of types that will be used for the
2225/// candidate operator functions for built-in operators (C++
2226/// [over.built]). The types are separated into pointer types and
2227/// enumeration types.
2228class BuiltinCandidateTypeSet {
2229 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002230 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002231
2232 /// PointerTypes - The set of pointer types that will be used in the
2233 /// built-in candidates.
2234 TypeSet PointerTypes;
2235
2236 /// EnumerationTypes - The set of enumeration types that will be
2237 /// used in the built-in candidates.
2238 TypeSet EnumerationTypes;
2239
2240 /// Context - The AST context in which we will build the type sets.
2241 ASTContext &Context;
2242
2243 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2244
2245public:
2246 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002247 class iterator {
2248 TypeSet::iterator Base;
2249
2250 public:
2251 typedef QualType value_type;
2252 typedef QualType reference;
2253 typedef QualType pointer;
2254 typedef std::ptrdiff_t difference_type;
2255 typedef std::input_iterator_tag iterator_category;
2256
2257 iterator(TypeSet::iterator B) : Base(B) { }
2258
2259 iterator& operator++() {
2260 ++Base;
2261 return *this;
2262 }
2263
2264 iterator operator++(int) {
2265 iterator tmp(*this);
2266 ++(*this);
2267 return tmp;
2268 }
2269
2270 reference operator*() const {
2271 return QualType::getFromOpaquePtr(*Base);
2272 }
2273
2274 pointer operator->() const {
2275 return **this;
2276 }
2277
2278 friend bool operator==(iterator LHS, iterator RHS) {
2279 return LHS.Base == RHS.Base;
2280 }
2281
2282 friend bool operator!=(iterator LHS, iterator RHS) {
2283 return LHS.Base != RHS.Base;
2284 }
2285 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002286
2287 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2288
2289 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
2290
2291 /// pointer_begin - First pointer type found;
2292 iterator pointer_begin() { return PointerTypes.begin(); }
2293
2294 /// pointer_end - Last pointer type found;
2295 iterator pointer_end() { return PointerTypes.end(); }
2296
2297 /// enumeration_begin - First enumeration type found;
2298 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2299
2300 /// enumeration_end - Last enumeration type found;
2301 iterator enumeration_end() { return EnumerationTypes.end(); }
2302};
2303
2304/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2305/// the set of pointer types along with any more-qualified variants of
2306/// that type. For example, if @p Ty is "int const *", this routine
2307/// will add "int const *", "int const volatile *", "int const
2308/// restrict *", and "int const volatile restrict *" to the set of
2309/// pointer types. Returns true if the add of @p Ty itself succeeded,
2310/// false otherwise.
2311bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2312 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002313 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002314 return false;
2315
2316 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2317 QualType PointeeTy = PointerTy->getPointeeType();
2318 // FIXME: Optimize this so that we don't keep trying to add the same types.
2319
2320 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2321 // with all pointer conversions that don't cast away constness?
2322 if (!PointeeTy.isConstQualified())
2323 AddWithMoreQualifiedTypeVariants
2324 (Context.getPointerType(PointeeTy.withConst()));
2325 if (!PointeeTy.isVolatileQualified())
2326 AddWithMoreQualifiedTypeVariants
2327 (Context.getPointerType(PointeeTy.withVolatile()));
2328 if (!PointeeTy.isRestrictQualified())
2329 AddWithMoreQualifiedTypeVariants
2330 (Context.getPointerType(PointeeTy.withRestrict()));
2331 }
2332
2333 return true;
2334}
2335
2336/// AddTypesConvertedFrom - Add each of the types to which the type @p
2337/// Ty can be implicit converted to the given set of @p Types. We're
2338/// primarily interested in pointer types, enumeration types,
2339void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2340 bool AllowUserConversions) {
2341 // Only deal with canonical types.
2342 Ty = Context.getCanonicalType(Ty);
2343
2344 // Look through reference types; they aren't part of the type of an
2345 // expression for the purposes of conversions.
2346 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2347 Ty = RefTy->getPointeeType();
2348
2349 // We don't care about qualifiers on the type.
2350 Ty = Ty.getUnqualifiedType();
2351
2352 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2353 QualType PointeeTy = PointerTy->getPointeeType();
2354
2355 // Insert our type, and its more-qualified variants, into the set
2356 // of types.
2357 if (!AddWithMoreQualifiedTypeVariants(Ty))
2358 return;
2359
2360 // Add 'cv void*' to our set of types.
2361 if (!Ty->isVoidType()) {
2362 QualType QualVoid
2363 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2364 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2365 }
2366
2367 // If this is a pointer to a class type, add pointers to its bases
2368 // (with the same level of cv-qualification as the original
2369 // derived class, of course).
2370 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2371 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2372 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2373 Base != ClassDecl->bases_end(); ++Base) {
2374 QualType BaseTy = Context.getCanonicalType(Base->getType());
2375 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2376
2377 // Add the pointer type, recursively, so that we get all of
2378 // the indirect base classes, too.
2379 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
2380 }
2381 }
2382 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002383 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002384 } else if (AllowUserConversions) {
2385 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2386 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2387 // FIXME: Visit conversion functions in the base classes, too.
2388 OverloadedFunctionDecl *Conversions
2389 = ClassDecl->getConversionFunctions();
2390 for (OverloadedFunctionDecl::function_iterator Func
2391 = Conversions->function_begin();
2392 Func != Conversions->function_end(); ++Func) {
2393 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2394 AddTypesConvertedFrom(Conv->getConversionType(), false);
2395 }
2396 }
2397 }
2398}
2399
Douglas Gregor74253732008-11-19 15:42:04 +00002400/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2401/// operator overloads to the candidate set (C++ [over.built]), based
2402/// on the operator @p Op and the arguments given. For example, if the
2403/// operator is a binary '+', this routine might add "int
2404/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002405void
Douglas Gregor74253732008-11-19 15:42:04 +00002406Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2407 Expr **Args, unsigned NumArgs,
2408 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002409 // The set of "promoted arithmetic types", which are the arithmetic
2410 // types are that preserved by promotion (C++ [over.built]p2). Note
2411 // that the first few of these types are the promoted integral
2412 // types; these types need to be first.
2413 // FIXME: What about complex?
2414 const unsigned FirstIntegralType = 0;
2415 const unsigned LastIntegralType = 13;
2416 const unsigned FirstPromotedIntegralType = 7,
2417 LastPromotedIntegralType = 13;
2418 const unsigned FirstPromotedArithmeticType = 7,
2419 LastPromotedArithmeticType = 16;
2420 const unsigned NumArithmeticTypes = 16;
2421 QualType ArithmeticTypes[NumArithmeticTypes] = {
2422 Context.BoolTy, Context.CharTy, Context.WCharTy,
2423 Context.SignedCharTy, Context.ShortTy,
2424 Context.UnsignedCharTy, Context.UnsignedShortTy,
2425 Context.IntTy, Context.LongTy, Context.LongLongTy,
2426 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2427 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2428 };
2429
2430 // Find all of the types that the arguments can convert to, but only
2431 // if the operator we're looking at has built-in operator candidates
2432 // that make use of these types.
2433 BuiltinCandidateTypeSet CandidateTypes(Context);
2434 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2435 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002436 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002437 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002438 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2439 (Op == OO_Star && NumArgs == 1)) {
2440 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002441 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2442 }
2443
2444 bool isComparison = false;
2445 switch (Op) {
2446 case OO_None:
2447 case NUM_OVERLOADED_OPERATORS:
2448 assert(false && "Expected an overloaded operator");
2449 break;
2450
Douglas Gregor74253732008-11-19 15:42:04 +00002451 case OO_Star: // '*' is either unary or binary
2452 if (NumArgs == 1)
2453 goto UnaryStar;
2454 else
2455 goto BinaryStar;
2456 break;
2457
2458 case OO_Plus: // '+' is either unary or binary
2459 if (NumArgs == 1)
2460 goto UnaryPlus;
2461 else
2462 goto BinaryPlus;
2463 break;
2464
2465 case OO_Minus: // '-' is either unary or binary
2466 if (NumArgs == 1)
2467 goto UnaryMinus;
2468 else
2469 goto BinaryMinus;
2470 break;
2471
2472 case OO_Amp: // '&' is either unary or binary
2473 if (NumArgs == 1)
2474 goto UnaryAmp;
2475 else
2476 goto BinaryAmp;
2477
2478 case OO_PlusPlus:
2479 case OO_MinusMinus:
2480 // C++ [over.built]p3:
2481 //
2482 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2483 // is either volatile or empty, there exist candidate operator
2484 // functions of the form
2485 //
2486 // VQ T& operator++(VQ T&);
2487 // T operator++(VQ T&, int);
2488 //
2489 // C++ [over.built]p4:
2490 //
2491 // For every pair (T, VQ), where T is an arithmetic type other
2492 // than bool, and VQ is either volatile or empty, there exist
2493 // candidate operator functions of the form
2494 //
2495 // VQ T& operator--(VQ T&);
2496 // T operator--(VQ T&, int);
2497 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2498 Arith < NumArithmeticTypes; ++Arith) {
2499 QualType ArithTy = ArithmeticTypes[Arith];
2500 QualType ParamTypes[2]
2501 = { Context.getReferenceType(ArithTy), Context.IntTy };
2502
2503 // Non-volatile version.
2504 if (NumArgs == 1)
2505 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2506 else
2507 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2508
2509 // Volatile version
2510 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2511 if (NumArgs == 1)
2512 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2513 else
2514 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2515 }
2516
2517 // C++ [over.built]p5:
2518 //
2519 // For every pair (T, VQ), where T is a cv-qualified or
2520 // cv-unqualified object type, and VQ is either volatile or
2521 // empty, there exist candidate operator functions of the form
2522 //
2523 // T*VQ& operator++(T*VQ&);
2524 // T*VQ& operator--(T*VQ&);
2525 // T* operator++(T*VQ&, int);
2526 // T* operator--(T*VQ&, int);
2527 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2528 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2529 // Skip pointer types that aren't pointers to object types.
Douglas Gregorcb7de522008-11-26 23:31:11 +00002530 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002531 continue;
2532
2533 QualType ParamTypes[2] = {
2534 Context.getReferenceType(*Ptr), Context.IntTy
2535 };
2536
2537 // Without volatile
2538 if (NumArgs == 1)
2539 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2540 else
2541 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2542
2543 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2544 // With volatile
2545 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2546 if (NumArgs == 1)
2547 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2548 else
2549 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2550 }
2551 }
2552 break;
2553
2554 UnaryStar:
2555 // C++ [over.built]p6:
2556 // For every cv-qualified or cv-unqualified object type T, there
2557 // exist candidate operator functions of the form
2558 //
2559 // T& operator*(T*);
2560 //
2561 // C++ [over.built]p7:
2562 // For every function type T, there exist candidate operator
2563 // functions of the form
2564 // T& operator*(T*);
2565 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2566 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2567 QualType ParamTy = *Ptr;
2568 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2569 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2570 &ParamTy, Args, 1, CandidateSet);
2571 }
2572 break;
2573
2574 UnaryPlus:
2575 // C++ [over.built]p8:
2576 // For every type T, there exist candidate operator functions of
2577 // the form
2578 //
2579 // T* operator+(T*);
2580 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2581 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2582 QualType ParamTy = *Ptr;
2583 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2584 }
2585
2586 // Fall through
2587
2588 UnaryMinus:
2589 // C++ [over.built]p9:
2590 // For every promoted arithmetic type T, there exist candidate
2591 // operator functions of the form
2592 //
2593 // T operator+(T);
2594 // T operator-(T);
2595 for (unsigned Arith = FirstPromotedArithmeticType;
2596 Arith < LastPromotedArithmeticType; ++Arith) {
2597 QualType ArithTy = ArithmeticTypes[Arith];
2598 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2599 }
2600 break;
2601
2602 case OO_Tilde:
2603 // C++ [over.built]p10:
2604 // For every promoted integral type T, there exist candidate
2605 // operator functions of the form
2606 //
2607 // T operator~(T);
2608 for (unsigned Int = FirstPromotedIntegralType;
2609 Int < LastPromotedIntegralType; ++Int) {
2610 QualType IntTy = ArithmeticTypes[Int];
2611 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2612 }
2613 break;
2614
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002615 case OO_New:
2616 case OO_Delete:
2617 case OO_Array_New:
2618 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002619 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002620 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002621 break;
2622
2623 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002624 UnaryAmp:
2625 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002626 // C++ [over.match.oper]p3:
2627 // -- For the operator ',', the unary operator '&', or the
2628 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002629 break;
2630
2631 case OO_Less:
2632 case OO_Greater:
2633 case OO_LessEqual:
2634 case OO_GreaterEqual:
2635 case OO_EqualEqual:
2636 case OO_ExclaimEqual:
2637 // C++ [over.built]p15:
2638 //
2639 // For every pointer or enumeration type T, there exist
2640 // candidate operator functions of the form
2641 //
2642 // bool operator<(T, T);
2643 // bool operator>(T, T);
2644 // bool operator<=(T, T);
2645 // bool operator>=(T, T);
2646 // bool operator==(T, T);
2647 // bool operator!=(T, T);
2648 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2649 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2650 QualType ParamTypes[2] = { *Ptr, *Ptr };
2651 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2652 }
2653 for (BuiltinCandidateTypeSet::iterator Enum
2654 = CandidateTypes.enumeration_begin();
2655 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2656 QualType ParamTypes[2] = { *Enum, *Enum };
2657 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2658 }
2659
2660 // Fall through.
2661 isComparison = true;
2662
Douglas Gregor74253732008-11-19 15:42:04 +00002663 BinaryPlus:
2664 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002665 if (!isComparison) {
2666 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2667
2668 // C++ [over.built]p13:
2669 //
2670 // For every cv-qualified or cv-unqualified object type T
2671 // there exist candidate operator functions of the form
2672 //
2673 // T* operator+(T*, ptrdiff_t);
2674 // T& operator[](T*, ptrdiff_t); [BELOW]
2675 // T* operator-(T*, ptrdiff_t);
2676 // T* operator+(ptrdiff_t, T*);
2677 // T& operator[](ptrdiff_t, T*); [BELOW]
2678 //
2679 // C++ [over.built]p14:
2680 //
2681 // For every T, where T is a pointer to object type, there
2682 // exist candidate operator functions of the form
2683 //
2684 // ptrdiff_t operator-(T, T);
2685 for (BuiltinCandidateTypeSet::iterator Ptr
2686 = CandidateTypes.pointer_begin();
2687 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2688 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2689
2690 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2691 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2692
2693 if (Op == OO_Plus) {
2694 // T* operator+(ptrdiff_t, T*);
2695 ParamTypes[0] = ParamTypes[1];
2696 ParamTypes[1] = *Ptr;
2697 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2698 } else {
2699 // ptrdiff_t operator-(T, T);
2700 ParamTypes[1] = *Ptr;
2701 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2702 Args, 2, CandidateSet);
2703 }
2704 }
2705 }
2706 // Fall through
2707
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002708 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002709 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002710 // C++ [over.built]p12:
2711 //
2712 // For every pair of promoted arithmetic types L and R, there
2713 // exist candidate operator functions of the form
2714 //
2715 // LR operator*(L, R);
2716 // LR operator/(L, R);
2717 // LR operator+(L, R);
2718 // LR operator-(L, R);
2719 // bool operator<(L, R);
2720 // bool operator>(L, R);
2721 // bool operator<=(L, R);
2722 // bool operator>=(L, R);
2723 // bool operator==(L, R);
2724 // bool operator!=(L, R);
2725 //
2726 // where LR is the result of the usual arithmetic conversions
2727 // between types L and R.
2728 for (unsigned Left = FirstPromotedArithmeticType;
2729 Left < LastPromotedArithmeticType; ++Left) {
2730 for (unsigned Right = FirstPromotedArithmeticType;
2731 Right < LastPromotedArithmeticType; ++Right) {
2732 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2733 QualType Result
2734 = isComparison? Context.BoolTy
2735 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2736 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2737 }
2738 }
2739 break;
2740
2741 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002742 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002743 case OO_Caret:
2744 case OO_Pipe:
2745 case OO_LessLess:
2746 case OO_GreaterGreater:
2747 // C++ [over.built]p17:
2748 //
2749 // For every pair of promoted integral types L and R, there
2750 // exist candidate operator functions of the form
2751 //
2752 // LR operator%(L, R);
2753 // LR operator&(L, R);
2754 // LR operator^(L, R);
2755 // LR operator|(L, R);
2756 // L operator<<(L, R);
2757 // L operator>>(L, R);
2758 //
2759 // where LR is the result of the usual arithmetic conversions
2760 // between types L and R.
2761 for (unsigned Left = FirstPromotedIntegralType;
2762 Left < LastPromotedIntegralType; ++Left) {
2763 for (unsigned Right = FirstPromotedIntegralType;
2764 Right < LastPromotedIntegralType; ++Right) {
2765 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2766 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2767 ? LandR[0]
2768 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2769 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2770 }
2771 }
2772 break;
2773
2774 case OO_Equal:
2775 // C++ [over.built]p20:
2776 //
2777 // For every pair (T, VQ), where T is an enumeration or
2778 // (FIXME:) pointer to member type and VQ is either volatile or
2779 // empty, there exist candidate operator functions of the form
2780 //
2781 // VQ T& operator=(VQ T&, T);
2782 for (BuiltinCandidateTypeSet::iterator Enum
2783 = CandidateTypes.enumeration_begin();
2784 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2785 QualType ParamTypes[2];
2786
2787 // T& operator=(T&, T)
2788 ParamTypes[0] = Context.getReferenceType(*Enum);
2789 ParamTypes[1] = *Enum;
2790 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2791
Douglas Gregor74253732008-11-19 15:42:04 +00002792 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2793 // volatile T& operator=(volatile T&, T)
2794 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2795 ParamTypes[1] = *Enum;
2796 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2797 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002798 }
2799 // Fall through.
2800
2801 case OO_PlusEqual:
2802 case OO_MinusEqual:
2803 // C++ [over.built]p19:
2804 //
2805 // For every pair (T, VQ), where T is any type and VQ is either
2806 // volatile or empty, there exist candidate operator functions
2807 // of the form
2808 //
2809 // T*VQ& operator=(T*VQ&, T*);
2810 //
2811 // C++ [over.built]p21:
2812 //
2813 // For every pair (T, VQ), where T is a cv-qualified or
2814 // cv-unqualified object type and VQ is either volatile or
2815 // empty, there exist candidate operator functions of the form
2816 //
2817 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2818 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2819 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2820 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2821 QualType ParamTypes[2];
2822 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2823
2824 // non-volatile version
2825 ParamTypes[0] = Context.getReferenceType(*Ptr);
2826 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2827
Douglas Gregor74253732008-11-19 15:42:04 +00002828 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2829 // volatile version
2830 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2831 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2832 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002833 }
2834 // Fall through.
2835
2836 case OO_StarEqual:
2837 case OO_SlashEqual:
2838 // C++ [over.built]p18:
2839 //
2840 // For every triple (L, VQ, R), where L is an arithmetic type,
2841 // VQ is either volatile or empty, and R is a promoted
2842 // arithmetic type, there exist candidate operator functions of
2843 // the form
2844 //
2845 // VQ L& operator=(VQ L&, R);
2846 // VQ L& operator*=(VQ L&, R);
2847 // VQ L& operator/=(VQ L&, R);
2848 // VQ L& operator+=(VQ L&, R);
2849 // VQ L& operator-=(VQ L&, R);
2850 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2851 for (unsigned Right = FirstPromotedArithmeticType;
2852 Right < LastPromotedArithmeticType; ++Right) {
2853 QualType ParamTypes[2];
2854 ParamTypes[1] = ArithmeticTypes[Right];
2855
2856 // Add this built-in operator as a candidate (VQ is empty).
2857 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2858 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2859
2860 // Add this built-in operator as a candidate (VQ is 'volatile').
2861 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2862 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2863 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2864 }
2865 }
2866 break;
2867
2868 case OO_PercentEqual:
2869 case OO_LessLessEqual:
2870 case OO_GreaterGreaterEqual:
2871 case OO_AmpEqual:
2872 case OO_CaretEqual:
2873 case OO_PipeEqual:
2874 // C++ [over.built]p22:
2875 //
2876 // For every triple (L, VQ, R), where L is an integral type, VQ
2877 // is either volatile or empty, and R is a promoted integral
2878 // type, there exist candidate operator functions of the form
2879 //
2880 // VQ L& operator%=(VQ L&, R);
2881 // VQ L& operator<<=(VQ L&, R);
2882 // VQ L& operator>>=(VQ L&, R);
2883 // VQ L& operator&=(VQ L&, R);
2884 // VQ L& operator^=(VQ L&, R);
2885 // VQ L& operator|=(VQ L&, R);
2886 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2887 for (unsigned Right = FirstPromotedIntegralType;
2888 Right < LastPromotedIntegralType; ++Right) {
2889 QualType ParamTypes[2];
2890 ParamTypes[1] = ArithmeticTypes[Right];
2891
2892 // Add this built-in operator as a candidate (VQ is empty).
2893 // FIXME: We should be caching these declarations somewhere,
2894 // rather than re-building them every time.
2895 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2896 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2897
2898 // Add this built-in operator as a candidate (VQ is 'volatile').
2899 ParamTypes[0] = ArithmeticTypes[Left];
2900 ParamTypes[0].addVolatile();
2901 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2902 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2903 }
2904 }
2905 break;
2906
Douglas Gregor74253732008-11-19 15:42:04 +00002907 case OO_Exclaim: {
2908 // C++ [over.operator]p23:
2909 //
2910 // There also exist candidate operator functions of the form
2911 //
2912 // bool operator!(bool);
2913 // bool operator&&(bool, bool); [BELOW]
2914 // bool operator||(bool, bool); [BELOW]
2915 QualType ParamTy = Context.BoolTy;
2916 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2917 break;
2918 }
2919
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002920 case OO_AmpAmp:
2921 case OO_PipePipe: {
2922 // C++ [over.operator]p23:
2923 //
2924 // There also exist candidate operator functions of the form
2925 //
Douglas Gregor74253732008-11-19 15:42:04 +00002926 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002927 // bool operator&&(bool, bool);
2928 // bool operator||(bool, bool);
2929 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2930 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2931 break;
2932 }
2933
2934 case OO_Subscript:
2935 // C++ [over.built]p13:
2936 //
2937 // For every cv-qualified or cv-unqualified object type T there
2938 // exist candidate operator functions of the form
2939 //
2940 // T* operator+(T*, ptrdiff_t); [ABOVE]
2941 // T& operator[](T*, ptrdiff_t);
2942 // T* operator-(T*, ptrdiff_t); [ABOVE]
2943 // T* operator+(ptrdiff_t, T*); [ABOVE]
2944 // T& operator[](ptrdiff_t, T*);
2945 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2946 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2947 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2948 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2949 QualType ResultTy = Context.getReferenceType(PointeeType);
2950
2951 // T& operator[](T*, ptrdiff_t)
2952 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2953
2954 // T& operator[](ptrdiff_t, T*);
2955 ParamTypes[0] = ParamTypes[1];
2956 ParamTypes[1] = *Ptr;
2957 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2958 }
2959 break;
2960
2961 case OO_ArrowStar:
2962 // FIXME: No support for pointer-to-members yet.
2963 break;
2964 }
2965}
2966
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002967/// AddOverloadCandidates - Add all of the function overloads in Ovl
2968/// to the candidate set.
2969void
Douglas Gregor18fe5682008-11-03 20:45:27 +00002970Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002971 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002972 OverloadCandidateSet& CandidateSet,
2973 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002974{
Douglas Gregor18fe5682008-11-03 20:45:27 +00002975 for (OverloadedFunctionDecl::function_const_iterator Func
2976 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002977 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00002978 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2979 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002980}
2981
2982/// isBetterOverloadCandidate - Determines whether the first overload
2983/// candidate is a better candidate than the second (C++ 13.3.3p1).
2984bool
2985Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2986 const OverloadCandidate& Cand2)
2987{
2988 // Define viable functions to be better candidates than non-viable
2989 // functions.
2990 if (!Cand2.Viable)
2991 return Cand1.Viable;
2992 else if (!Cand1.Viable)
2993 return false;
2994
Douglas Gregor88a35142008-12-22 05:46:06 +00002995 // C++ [over.match.best]p1:
2996 //
2997 // -- if F is a static member function, ICS1(F) is defined such
2998 // that ICS1(F) is neither better nor worse than ICS1(G) for
2999 // any function G, and, symmetrically, ICS1(G) is neither
3000 // better nor worse than ICS1(F).
3001 unsigned StartArg = 0;
3002 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3003 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003004
3005 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3006 // function than another viable function F2 if for all arguments i,
3007 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3008 // then...
3009 unsigned NumArgs = Cand1.Conversions.size();
3010 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3011 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003012 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003013 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3014 Cand2.Conversions[ArgIdx])) {
3015 case ImplicitConversionSequence::Better:
3016 // Cand1 has a better conversion sequence.
3017 HasBetterConversion = true;
3018 break;
3019
3020 case ImplicitConversionSequence::Worse:
3021 // Cand1 can't be better than Cand2.
3022 return false;
3023
3024 case ImplicitConversionSequence::Indistinguishable:
3025 // Do nothing.
3026 break;
3027 }
3028 }
3029
3030 if (HasBetterConversion)
3031 return true;
3032
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003033 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3034 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003035
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003036 // C++ [over.match.best]p1b4:
3037 //
3038 // -- the context is an initialization by user-defined conversion
3039 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3040 // from the return type of F1 to the destination type (i.e.,
3041 // the type of the entity being initialized) is a better
3042 // conversion sequence than the standard conversion sequence
3043 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003044 if (Cand1.Function && Cand2.Function &&
3045 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003046 isa<CXXConversionDecl>(Cand2.Function)) {
3047 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3048 Cand2.FinalConversion)) {
3049 case ImplicitConversionSequence::Better:
3050 // Cand1 has a better conversion sequence.
3051 return true;
3052
3053 case ImplicitConversionSequence::Worse:
3054 // Cand1 can't be better than Cand2.
3055 return false;
3056
3057 case ImplicitConversionSequence::Indistinguishable:
3058 // Do nothing
3059 break;
3060 }
3061 }
3062
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003063 return false;
3064}
3065
3066/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3067/// within an overload candidate set. If overloading is successful,
3068/// the result will be OR_Success and Best will be set to point to the
3069/// best viable function within the candidate set. Otherwise, one of
3070/// several kinds of errors will be returned; see
3071/// Sema::OverloadingResult.
3072Sema::OverloadingResult
3073Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3074 OverloadCandidateSet::iterator& Best)
3075{
3076 // Find the best viable function.
3077 Best = CandidateSet.end();
3078 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3079 Cand != CandidateSet.end(); ++Cand) {
3080 if (Cand->Viable) {
3081 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3082 Best = Cand;
3083 }
3084 }
3085
3086 // If we didn't find any viable functions, abort.
3087 if (Best == CandidateSet.end())
3088 return OR_No_Viable_Function;
3089
3090 // Make sure that this function is better than every other viable
3091 // function. If not, we have an ambiguity.
3092 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3093 Cand != CandidateSet.end(); ++Cand) {
3094 if (Cand->Viable &&
3095 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003096 !isBetterOverloadCandidate(*Best, *Cand)) {
3097 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003098 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003099 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003100 }
3101
3102 // Best is the best viable function.
3103 return OR_Success;
3104}
3105
3106/// PrintOverloadCandidates - When overload resolution fails, prints
3107/// diagnostic messages containing the candidates in the candidate
3108/// set. If OnlyViable is true, only viable candidates will be printed.
3109void
3110Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3111 bool OnlyViable)
3112{
3113 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3114 LastCand = CandidateSet.end();
3115 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003116 if (Cand->Viable || !OnlyViable) {
3117 if (Cand->Function) {
3118 // Normal function
3119 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003120 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003121 // Desugar the type of the surrogate down to a function type,
3122 // retaining as many typedefs as possible while still showing
3123 // the function type (and, therefore, its parameter types).
3124 QualType FnType = Cand->Surrogate->getConversionType();
3125 bool isReference = false;
3126 bool isPointer = false;
3127 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
3128 FnType = FnTypeRef->getPointeeType();
3129 isReference = true;
3130 }
3131 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3132 FnType = FnTypePtr->getPointeeType();
3133 isPointer = true;
3134 }
3135 // Desugar down to a function type.
3136 FnType = QualType(FnType->getAsFunctionType(), 0);
3137 // Reconstruct the pointer/reference as appropriate.
3138 if (isPointer) FnType = Context.getPointerType(FnType);
3139 if (isReference) FnType = Context.getReferenceType(FnType);
3140
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003141 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003142 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003143 } else {
3144 // FIXME: We need to get the identifier in here
3145 // FIXME: Do we want the error message to point at the
3146 // operator? (built-ins won't have a location)
3147 QualType FnType
3148 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3149 Cand->BuiltinTypes.ParamTypes,
3150 Cand->Conversions.size(),
3151 false, 0);
3152
Chris Lattnerd1625842008-11-24 06:25:27 +00003153 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003154 }
3155 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003156 }
3157}
3158
Douglas Gregor904eed32008-11-10 20:40:00 +00003159/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3160/// an overloaded function (C++ [over.over]), where @p From is an
3161/// expression with overloaded function type and @p ToType is the type
3162/// we're trying to resolve to. For example:
3163///
3164/// @code
3165/// int f(double);
3166/// int f(int);
3167///
3168/// int (*pfd)(double) = f; // selects f(double)
3169/// @endcode
3170///
3171/// This routine returns the resulting FunctionDecl if it could be
3172/// resolved, and NULL otherwise. When @p Complain is true, this
3173/// routine will emit diagnostics if there is an error.
3174FunctionDecl *
3175Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3176 bool Complain) {
3177 QualType FunctionType = ToType;
3178 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3179 FunctionType = ToTypePtr->getPointeeType();
3180
3181 // We only look at pointers or references to functions.
3182 if (!FunctionType->isFunctionType())
3183 return 0;
3184
3185 // Find the actual overloaded function declaration.
3186 OverloadedFunctionDecl *Ovl = 0;
3187
3188 // C++ [over.over]p1:
3189 // [...] [Note: any redundant set of parentheses surrounding the
3190 // overloaded function name is ignored (5.1). ]
3191 Expr *OvlExpr = From->IgnoreParens();
3192
3193 // C++ [over.over]p1:
3194 // [...] The overloaded function name can be preceded by the &
3195 // operator.
3196 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3197 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3198 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3199 }
3200
3201 // Try to dig out the overloaded function.
3202 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3203 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3204
3205 // If there's no overloaded function declaration, we're done.
3206 if (!Ovl)
3207 return 0;
3208
3209 // Look through all of the overloaded functions, searching for one
3210 // whose type matches exactly.
3211 // FIXME: When templates or using declarations come along, we'll actually
3212 // have to deal with duplicates, partial ordering, etc. For now, we
3213 // can just do a simple search.
3214 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3215 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3216 Fun != Ovl->function_end(); ++Fun) {
3217 // C++ [over.over]p3:
3218 // Non-member functions and static member functions match
3219 // targets of type “pointer-to-function”or
3220 // “reference-to-function.”
3221 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
3222 if (!Method->isStatic())
3223 continue;
3224
3225 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3226 return *Fun;
3227 }
3228
3229 return 0;
3230}
3231
Douglas Gregorf6b89692008-11-26 05:54:23 +00003232/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3233/// (which eventually refers to the set of overloaded functions in
3234/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the
3235/// function call down to a specific function. If overload resolution
Douglas Gregor0a396682008-11-26 06:01:48 +00003236/// succeeds, returns the function declaration produced by overload
3237/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003238/// arguments and Fn, and returns NULL.
Douglas Gregor0a396682008-11-26 06:01:48 +00003239FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl,
3240 SourceLocation LParenLoc,
3241 Expr **Args, unsigned NumArgs,
3242 SourceLocation *CommaLocs,
3243 SourceLocation RParenLoc) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003244 OverloadCandidateSet CandidateSet;
3245 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
3246 OverloadCandidateSet::iterator Best;
3247 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003248 case OR_Success:
3249 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003250
3251 case OR_No_Viable_Function:
3252 Diag(Fn->getSourceRange().getBegin(),
3253 diag::err_ovl_no_viable_function_in_call)
3254 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3255 << Fn->getSourceRange();
3256 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3257 break;
3258
3259 case OR_Ambiguous:
3260 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3261 << Ovl->getDeclName() << Fn->getSourceRange();
3262 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3263 break;
3264 }
3265
3266 // Overload resolution failed. Destroy all of the subexpressions and
3267 // return NULL.
3268 Fn->Destroy(Context);
3269 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3270 Args[Arg]->Destroy(Context);
3271 return 0;
3272}
3273
Douglas Gregor88a35142008-12-22 05:46:06 +00003274/// BuildCallToMemberFunction - Build a call to a member
3275/// function. MemExpr is the expression that refers to the member
3276/// function (and includes the object parameter), Args/NumArgs are the
3277/// arguments to the function call (not including the object
3278/// parameter). The caller needs to validate that the member
3279/// expression refers to a member function or an overloaded member
3280/// function.
3281Sema::ExprResult
3282Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3283 SourceLocation LParenLoc, Expr **Args,
3284 unsigned NumArgs, SourceLocation *CommaLocs,
3285 SourceLocation RParenLoc) {
3286 // Dig out the member expression. This holds both the object
3287 // argument and the member function we're referring to.
3288 MemberExpr *MemExpr = 0;
3289 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3290 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3291 else
3292 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3293 assert(MemExpr && "Building member call without member expression");
3294
3295 // Extract the object argument.
3296 Expr *ObjectArg = MemExpr->getBase();
3297 if (MemExpr->isArrow())
3298 ObjectArg = new UnaryOperator(ObjectArg, UnaryOperator::Deref,
3299 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
3300 SourceLocation());
3301 CXXMethodDecl *Method = 0;
3302 if (OverloadedFunctionDecl *Ovl
3303 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3304 // Add overload candidates
3305 OverloadCandidateSet CandidateSet;
3306 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3307 FuncEnd = Ovl->function_end();
3308 Func != FuncEnd; ++Func) {
3309 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3310 Method = cast<CXXMethodDecl>(*Func);
3311 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3312 /*SuppressUserConversions=*/false);
3313 }
3314
3315 OverloadCandidateSet::iterator Best;
3316 switch (BestViableFunction(CandidateSet, Best)) {
3317 case OR_Success:
3318 Method = cast<CXXMethodDecl>(Best->Function);
3319 break;
3320
3321 case OR_No_Viable_Function:
3322 Diag(MemExpr->getSourceRange().getBegin(),
3323 diag::err_ovl_no_viable_member_function_in_call)
3324 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3325 << MemExprE->getSourceRange();
3326 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3327 // FIXME: Leaking incoming expressions!
3328 return true;
3329
3330 case OR_Ambiguous:
3331 Diag(MemExpr->getSourceRange().getBegin(),
3332 diag::err_ovl_ambiguous_member_call)
3333 << Ovl->getDeclName() << MemExprE->getSourceRange();
3334 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3335 // FIXME: Leaking incoming expressions!
3336 return true;
3337 }
3338
3339 FixOverloadedFunctionReference(MemExpr, Method);
3340 } else {
3341 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3342 }
3343
3344 assert(Method && "Member call to something that isn't a method?");
3345 llvm::OwningPtr<CXXMemberCallExpr>
3346 TheCall(new CXXMemberCallExpr(MemExpr, Args, NumArgs,
3347 Method->getResultType().getNonReferenceType(),
3348 RParenLoc));
3349
3350 // Convert the object argument (for a non-static member function call).
3351 if (!Method->isStatic() &&
3352 PerformObjectArgumentInitialization(ObjectArg, Method))
3353 return true;
3354 MemExpr->setBase(ObjectArg);
3355
3356 // Convert the rest of the arguments
3357 const FunctionTypeProto *Proto = cast<FunctionTypeProto>(Method->getType());
3358 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
3359 RParenLoc))
3360 return true;
3361
3362 return CheckFunctionCall(Method, TheCall.take());
3363}
3364
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003365/// BuildCallToObjectOfClassType - Build a call to an object of class
3366/// type (C++ [over.call.object]), which can end up invoking an
3367/// overloaded function call operator (@c operator()) or performing a
3368/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00003369Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00003370Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3371 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003372 Expr **Args, unsigned NumArgs,
3373 SourceLocation *CommaLocs,
3374 SourceLocation RParenLoc) {
3375 assert(Object->getType()->isRecordType() && "Requires object type argument");
3376 const RecordType *Record = Object->getType()->getAsRecordType();
3377
3378 // C++ [over.call.object]p1:
3379 // If the primary-expression E in the function call syntax
3380 // evaluates to a class object of type “cv T”, then the set of
3381 // candidate functions includes at least the function call
3382 // operators of T. The function call operators of T are obtained by
3383 // ordinary lookup of the name operator() in the context of
3384 // (E).operator().
3385 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00003386 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003387 DeclContext::lookup_const_iterator Oper, OperEnd;
3388 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(Context, OpName);
3389 Oper != OperEnd; ++Oper)
3390 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
3391 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003392
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003393 // C++ [over.call.object]p2:
3394 // In addition, for each conversion function declared in T of the
3395 // form
3396 //
3397 // operator conversion-type-id () cv-qualifier;
3398 //
3399 // where cv-qualifier is the same cv-qualification as, or a
3400 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003401 // denotes the type "pointer to function of (P1,...,Pn) returning
3402 // R", or the type "reference to pointer to function of
3403 // (P1,...,Pn) returning R", or the type "reference to function
3404 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003405 // is also considered as a candidate function. Similarly,
3406 // surrogate call functions are added to the set of candidate
3407 // functions for each conversion function declared in an
3408 // accessible base class provided the function is not hidden
3409 // within T by another intervening declaration.
3410 //
3411 // FIXME: Look in base classes for more conversion operators!
3412 OverloadedFunctionDecl *Conversions
3413 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003414 for (OverloadedFunctionDecl::function_iterator
3415 Func = Conversions->function_begin(),
3416 FuncEnd = Conversions->function_end();
3417 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003418 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3419
3420 // Strip the reference type (if any) and then the pointer type (if
3421 // any) to get down to what might be a function type.
3422 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3423 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3424 ConvType = ConvPtrType->getPointeeType();
3425
3426 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3427 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3428 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003429
3430 // Perform overload resolution.
3431 OverloadCandidateSet::iterator Best;
3432 switch (BestViableFunction(CandidateSet, Best)) {
3433 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003434 // Overload resolution succeeded; we'll build the appropriate call
3435 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003436 break;
3437
3438 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003439 Diag(Object->getSourceRange().getBegin(),
3440 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003441 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003442 << Object->getSourceRange();
3443 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003444 break;
3445
3446 case OR_Ambiguous:
3447 Diag(Object->getSourceRange().getBegin(),
3448 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003449 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003450 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3451 break;
3452 }
3453
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003454 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003455 // We had an error; delete all of the subexpressions and return
3456 // the error.
3457 delete Object;
3458 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3459 delete Args[ArgIdx];
3460 return true;
3461 }
3462
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003463 if (Best->Function == 0) {
3464 // Since there is no function declaration, this is one of the
3465 // surrogate candidates. Dig out the conversion function.
3466 CXXConversionDecl *Conv
3467 = cast<CXXConversionDecl>(
3468 Best->Conversions[0].UserDefined.ConversionFunction);
3469
3470 // We selected one of the surrogate functions that converts the
3471 // object parameter to a function pointer. Perform the conversion
3472 // on the object argument, then let ActOnCallExpr finish the job.
3473 // FIXME: Represent the user-defined conversion in the AST!
3474 ImpCastExprToType(Object,
3475 Conv->getConversionType().getNonReferenceType(),
3476 Conv->getConversionType()->isReferenceType());
Douglas Gregor5c37de72008-12-06 00:22:45 +00003477 return ActOnCallExpr(S, (ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003478 CommaLocs, RParenLoc);
3479 }
3480
3481 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3482 // that calls this method, using Object for the implicit object
3483 // parameter and passing along the remaining arguments.
3484 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003485 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3486
3487 unsigned NumArgsInProto = Proto->getNumArgs();
3488 unsigned NumArgsToCheck = NumArgs;
3489
3490 // Build the full argument list for the method call (the
3491 // implicit object parameter is placed at the beginning of the
3492 // list).
3493 Expr **MethodArgs;
3494 if (NumArgs < NumArgsInProto) {
3495 NumArgsToCheck = NumArgsInProto;
3496 MethodArgs = new Expr*[NumArgsInProto + 1];
3497 } else {
3498 MethodArgs = new Expr*[NumArgs + 1];
3499 }
3500 MethodArgs[0] = Object;
3501 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3502 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3503
3504 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3505 SourceLocation());
3506 UsualUnaryConversions(NewFn);
3507
3508 // Once we've built TheCall, all of the expressions are properly
3509 // owned.
3510 QualType ResultTy = Method->getResultType().getNonReferenceType();
3511 llvm::OwningPtr<CXXOperatorCallExpr>
3512 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3513 ResultTy, RParenLoc));
3514 delete [] MethodArgs;
3515
3516 // Initialize the implicit object parameter.
3517 if (!PerformObjectArgumentInitialization(Object, Method))
3518 return true;
3519 TheCall->setArg(0, Object);
3520
3521 // Check the argument types.
3522 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3523 QualType ProtoArgType = Proto->getArgType(i);
3524
3525 Expr *Arg;
3526 if (i < NumArgs)
3527 Arg = Args[i];
3528 else
3529 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
3530 QualType ArgType = Arg->getType();
3531
3532 // Pass the argument.
3533 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3534 return true;
3535
3536 TheCall->setArg(i + 1, Arg);
3537 }
3538
3539 // If this is a variadic call, handle args passed through "...".
3540 if (Proto->isVariadic()) {
3541 // Promote the arguments (C99 6.5.2.2p7).
3542 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3543 Expr *Arg = Args[i];
3544 DefaultArgumentPromotion(Arg);
3545 TheCall->setArg(i + 1, Arg);
3546 }
3547 }
3548
3549 return CheckFunctionCall(Method, TheCall.take());
3550}
3551
Douglas Gregor8ba10742008-11-20 16:27:02 +00003552/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3553/// (if one exists), where @c Base is an expression of class type and
3554/// @c Member is the name of the member we're trying to find.
3555Action::ExprResult
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003556Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003557 SourceLocation MemberLoc,
3558 IdentifierInfo &Member) {
3559 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3560
3561 // C++ [over.ref]p1:
3562 //
3563 // [...] An expression x->m is interpreted as (x.operator->())->m
3564 // for a class object x of type T if T::operator->() exists and if
3565 // the operator is selected as the best match function by the
3566 // overload resolution mechanism (13.3).
3567 // FIXME: look in base classes.
3568 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3569 OverloadCandidateSet CandidateSet;
3570 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003571
3572 DeclContext::lookup_const_iterator Oper, OperEnd;
3573 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(Context, OpName);
3574 Oper != OperEnd; ++Oper)
3575 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003576 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003577
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003578 llvm::OwningPtr<Expr> BasePtr(Base);
3579
Douglas Gregor8ba10742008-11-20 16:27:02 +00003580 // Perform overload resolution.
3581 OverloadCandidateSet::iterator Best;
3582 switch (BestViableFunction(CandidateSet, Best)) {
3583 case OR_Success:
3584 // Overload resolution succeeded; we'll build the call below.
3585 break;
3586
3587 case OR_No_Viable_Function:
3588 if (CandidateSet.empty())
3589 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003590 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003591 else
3592 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003593 << "operator->" << (unsigned)CandidateSet.size()
3594 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003595 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003596 return true;
3597
3598 case OR_Ambiguous:
3599 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003600 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003601 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003602 return true;
3603 }
3604
3605 // Convert the object parameter.
3606 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003607 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003608 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003609
3610 // No concerns about early exits now.
3611 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003612
3613 // Build the operator call.
3614 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3615 UsualUnaryConversions(FnExpr);
3616 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3617 Method->getResultType().getNonReferenceType(),
3618 OpLoc);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003619 return ActOnMemberReferenceExpr(S, Base, OpLoc, tok::arrow, MemberLoc, Member);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003620}
3621
Douglas Gregor904eed32008-11-10 20:40:00 +00003622/// FixOverloadedFunctionReference - E is an expression that refers to
3623/// a C++ overloaded function (possibly with some parentheses and
3624/// perhaps a '&' around it). We have resolved the overloaded function
3625/// to the function declaration Fn, so patch up the expression E to
3626/// refer (possibly indirectly) to Fn.
3627void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3628 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3629 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3630 E->setType(PE->getSubExpr()->getType());
3631 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3632 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3633 "Can only take the address of an overloaded function");
3634 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3635 E->setType(Context.getPointerType(E->getType()));
3636 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3637 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3638 "Expected overloaded function");
3639 DR->setDecl(Fn);
3640 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00003641 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
3642 MemExpr->setMemberDecl(Fn);
3643 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00003644 } else {
3645 assert(false && "Invalid reference to overloaded function");
3646 }
3647}
3648
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003649} // end namespace clang