blob: 049aca51ce00a8653de6549194699363a9f50dbf [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,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000042 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000045 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000050 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000051 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000052 ICC_Conversion
53 };
54 return Category[(int)Kind];
55}
56
57/// GetConversionRank - Retrieve the implicit conversion rank
58/// corresponding to the given implicit conversion kind.
59ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
60 static const ImplicitConversionRank
61 Rank[(int)ICK_Num_Conversion_Kinds] = {
62 ICR_Exact_Match,
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Promotion,
68 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000069 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000077 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000078 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000079 ICR_Conversion
80 };
81 return Rank[(int)Kind];
82}
83
84/// GetImplicitConversionName - Return the name of this kind of
85/// implicit conversion.
86const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
87 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
88 "No conversion",
89 "Lvalue-to-rvalue",
90 "Array-to-pointer",
91 "Function-to-pointer",
92 "Qualification",
93 "Integral promotion",
94 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000095 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000096 "Integral conversion",
97 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000098 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000099 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Pointer conversion",
102 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000103 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000104 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000105 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 };
107 return Name[Kind];
108}
109
Douglas Gregor60d62c22008-10-31 16:23:19 +0000110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113 First = ICK_Identity;
114 Second = ICK_Identity;
115 Third = ICK_Identity;
116 Deprecated = false;
117 ReferenceBinding = false;
118 DirectBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000119 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000120}
121
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000122/// getRank - Retrieve the rank of this standard conversion sequence
123/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
124/// implicit conversions.
125ImplicitConversionRank StandardConversionSequence::getRank() const {
126 ImplicitConversionRank Rank = ICR_Exact_Match;
127 if (GetConversionRank(First) > Rank)
128 Rank = GetConversionRank(First);
129 if (GetConversionRank(Second) > Rank)
130 Rank = GetConversionRank(Second);
131 if (GetConversionRank(Third) > Rank)
132 Rank = GetConversionRank(Third);
133 return Rank;
134}
135
136/// isPointerConversionToBool - Determines whether this conversion is
137/// a conversion of a pointer or pointer-to-member to bool. This is
138/// used as part of the ranking of standard conversion sequences
139/// (C++ 13.3.3.2p4).
140bool StandardConversionSequence::isPointerConversionToBool() const
141{
142 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
143 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
144
145 // Note that FromType has not necessarily been transformed by the
146 // array-to-pointer or function-to-pointer implicit conversions, so
147 // check for their presence as well as checking whether FromType is
148 // a pointer.
149 if (ToType->isBooleanType() &&
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000150 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000151 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
152 return true;
153
154 return false;
155}
156
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000157/// isPointerConversionToVoidPointer - Determines whether this
158/// conversion is a conversion of a pointer to a void pointer. This is
159/// used as part of the ranking of standard conversion sequences (C++
160/// 13.3.3.2p4).
161bool
162StandardConversionSequence::
163isPointerConversionToVoidPointer(ASTContext& Context) const
164{
165 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
166 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
167
168 // Note that FromType has not necessarily been transformed by the
169 // array-to-pointer implicit conversion, so check for its presence
170 // and redo the conversion to get a pointer.
171 if (First == ICK_Array_To_Pointer)
172 FromType = Context.getArrayDecayedType(FromType);
173
174 if (Second == ICK_Pointer_Conversion)
175 if (const PointerType* ToPtrType = ToType->getAsPointerType())
176 return ToPtrType->getPointeeType()->isVoidType();
177
178 return false;
179}
180
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000181/// DebugPrint - Print this standard conversion sequence to standard
182/// error. Useful for debugging overloading issues.
183void StandardConversionSequence::DebugPrint() const {
184 bool PrintedSomething = false;
185 if (First != ICK_Identity) {
186 fprintf(stderr, "%s", GetImplicitConversionName(First));
187 PrintedSomething = true;
188 }
189
190 if (Second != ICK_Identity) {
191 if (PrintedSomething) {
192 fprintf(stderr, " -> ");
193 }
194 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000195
196 if (CopyConstructor) {
197 fprintf(stderr, " (by copy constructor)");
198 } else if (DirectBinding) {
199 fprintf(stderr, " (direct reference binding)");
200 } else if (ReferenceBinding) {
201 fprintf(stderr, " (reference binding)");
202 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000203 PrintedSomething = true;
204 }
205
206 if (Third != ICK_Identity) {
207 if (PrintedSomething) {
208 fprintf(stderr, " -> ");
209 }
210 fprintf(stderr, "%s", GetImplicitConversionName(Third));
211 PrintedSomething = true;
212 }
213
214 if (!PrintedSomething) {
215 fprintf(stderr, "No conversions required");
216 }
217}
218
219/// DebugPrint - Print this user-defined conversion sequence to standard
220/// error. Useful for debugging overloading issues.
221void UserDefinedConversionSequence::DebugPrint() const {
222 if (Before.First || Before.Second || Before.Third) {
223 Before.DebugPrint();
224 fprintf(stderr, " -> ");
225 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000226 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000227 if (After.First || After.Second || After.Third) {
228 fprintf(stderr, " -> ");
229 After.DebugPrint();
230 }
231}
232
233/// DebugPrint - Print this implicit conversion sequence to standard
234/// error. Useful for debugging overloading issues.
235void ImplicitConversionSequence::DebugPrint() const {
236 switch (ConversionKind) {
237 case StandardConversion:
238 fprintf(stderr, "Standard conversion: ");
239 Standard.DebugPrint();
240 break;
241 case UserDefinedConversion:
242 fprintf(stderr, "User-defined conversion: ");
243 UserDefined.DebugPrint();
244 break;
245 case EllipsisConversion:
246 fprintf(stderr, "Ellipsis conversion");
247 break;
248 case BadConversion:
249 fprintf(stderr, "Bad conversion");
250 break;
251 }
252
253 fprintf(stderr, "\n");
254}
255
256// IsOverload - Determine whether the given New declaration is an
257// overload of the Old declaration. This routine returns false if New
258// and Old cannot be overloaded, e.g., if they are functions with the
259// same signature (C++ 1.3.10) or if the Old declaration isn't a
260// function (or overload set). When it does return false and Old is an
261// OverloadedFunctionDecl, MatchedDecl will be set to point to the
262// FunctionDecl that New cannot be overloaded with.
263//
264// Example: Given the following input:
265//
266// void f(int, float); // #1
267// void f(int, int); // #2
268// int f(int, int); // #3
269//
270// When we process #1, there is no previous declaration of "f",
271// so IsOverload will not be used.
272//
273// When we process #2, Old is a FunctionDecl for #1. By comparing the
274// parameter types, we see that #1 and #2 are overloaded (since they
275// have different signatures), so this routine returns false;
276// MatchedDecl is unchanged.
277//
278// When we process #3, Old is an OverloadedFunctionDecl containing #1
279// and #2. We compare the signatures of #3 to #1 (they're overloaded,
280// so we do nothing) and then #3 to #2. Since the signatures of #3 and
281// #2 are identical (return types of functions are not part of the
282// signature), IsOverload returns false and MatchedDecl will be set to
283// point to the FunctionDecl for #2.
284bool
285Sema::IsOverload(FunctionDecl *New, Decl* OldD,
286 OverloadedFunctionDecl::function_iterator& MatchedDecl)
287{
288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
290 // overload set?
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
295 MatchedDecl = Func;
296 return false;
297 }
298 }
299
300 // This function overloads every function in the overload set.
301 return true;
302 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
303 // Is the function New an overload of the function Old?
304 QualType OldQType = Context.getCanonicalType(Old->getType());
305 QualType NewQType = Context.getCanonicalType(New->getType());
306
307 // Compare the signatures (C++ 1.3.10) of the two functions to
308 // determine whether they are overloads. If we find any mismatch
309 // in the signature, they are overloads.
310
311 // If either of these functions is a K&R-style function (no
312 // prototype), then we consider them to have matching signatures.
313 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
314 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
315 return false;
316
317 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
318 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
319
320 // The signature of a function includes the types of its
321 // parameters (C++ 1.3.10), which includes the presence or absence
322 // of the ellipsis; see C++ DR 357).
323 if (OldQType != NewQType &&
324 (OldType->getNumArgs() != NewType->getNumArgs() ||
325 OldType->isVariadic() != NewType->isVariadic() ||
326 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
327 NewType->arg_type_begin())))
328 return true;
329
330 // If the function is a class member, its signature includes the
331 // cv-qualifiers (if any) on the function itself.
332 //
333 // As part of this, also check whether one of the member functions
334 // is static, in which case they are not overloads (C++
335 // 13.1p2). While not part of the definition of the signature,
336 // this check is important to determine whether these functions
337 // can be overloaded.
338 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
339 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
340 if (OldMethod && NewMethod &&
341 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000342 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000343 return true;
344
345 // The signatures match; this is not an overload.
346 return false;
347 } else {
348 // (C++ 13p1):
349 // Only function declarations can be overloaded; object and type
350 // declarations cannot be overloaded.
351 return false;
352 }
353}
354
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000355/// TryImplicitConversion - Attempt to perform an implicit conversion
356/// from the given expression (Expr) to the given type (ToType). This
357/// function returns an implicit conversion sequence that can be used
358/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000359///
360/// void f(float f);
361/// void g(int i) { f(i); }
362///
363/// this routine would produce an implicit conversion sequence to
364/// describe the initialization of f from i, which will be a standard
365/// conversion sequence containing an lvalue-to-rvalue conversion (C++
366/// 4.1) followed by a floating-integral conversion (C++ 4.9).
367//
368/// Note that this routine only determines how the conversion can be
369/// performed; it does not actually perform the conversion. As such,
370/// it will not produce any diagnostics if no conversion is available,
371/// but will instead return an implicit conversion sequence of kind
372/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000373///
374/// If @p SuppressUserConversions, then user-defined conversions are
375/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000376/// If @p AllowExplicit, then explicit user-defined conversions are
377/// permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000378ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000379Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000380 bool SuppressUserConversions,
Douglas Gregor734d9862009-01-30 23:27:23 +0000381 bool AllowExplicit)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000382{
383 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000384 if (IsStandardConversion(From, ToType, ICS.Standard))
385 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000386 else if (getLangOptions().CPlusPlus &&
387 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor734d9862009-01-30 23:27:23 +0000388 !SuppressUserConversions, AllowExplicit)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000389 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000390 // C++ [over.ics.user]p4:
391 // A conversion of an expression of class type to the same class
392 // type is given Exact Match rank, and a conversion of an
393 // expression of class type to a base class of that type is
394 // given Conversion rank, in spite of the fact that a copy
395 // constructor (i.e., a user-defined conversion function) is
396 // called for those cases.
397 if (CXXConstructorDecl *Constructor
398 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000399 QualType FromCanon
400 = Context.getCanonicalType(From->getType().getUnqualifiedType());
401 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
402 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000403 // Turn this into a "standard" conversion sequence, so that it
404 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000405 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
406 ICS.Standard.setAsIdentityConversion();
407 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
408 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000409 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000410 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000411 ICS.Standard.Second = ICK_Derived_To_Base;
412 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000413 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000414
415 // C++ [over.best.ics]p4:
416 // However, when considering the argument of a user-defined
417 // conversion function that is a candidate by 13.3.1.3 when
418 // invoked for the copying of the temporary in the second step
419 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
420 // 13.3.1.6 in all cases, only standard conversion sequences and
421 // ellipsis conversion sequences are allowed.
422 if (SuppressUserConversions &&
423 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
424 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000425 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000426 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000427
428 return ICS;
429}
430
431/// IsStandardConversion - Determines whether there is a standard
432/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
433/// expression From to the type ToType. Standard conversion sequences
434/// only consider non-class types; for conversions that involve class
435/// types, use TryImplicitConversion. If a conversion exists, SCS will
436/// contain the standard conversion sequence required to perform this
437/// conversion and this routine will return true. Otherwise, this
438/// routine will return false and the value of SCS is unspecified.
439bool
440Sema::IsStandardConversion(Expr* From, QualType ToType,
441 StandardConversionSequence &SCS)
442{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000443 QualType FromType = From->getType();
444
Douglas Gregor60d62c22008-10-31 16:23:19 +0000445 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000446 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000447 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000448 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000449 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000450 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451
Douglas Gregorf9201e02009-02-11 23:02:49 +0000452 // There are no standard conversions for class types in C++, so
453 // abort early. When overloading in C, however, we do permit
454 if (FromType->isRecordType() || ToType->isRecordType()) {
455 if (getLangOptions().CPlusPlus)
456 return false;
457
458 // When we're overloading in C, we allow, as standard conversions,
459 }
460
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000461 // The first conversion can be an lvalue-to-rvalue conversion,
462 // array-to-pointer conversion, or function-to-pointer conversion
463 // (C++ 4p1).
464
465 // Lvalue-to-rvalue conversion (C++ 4.1):
466 // An lvalue (3.10) of a non-function, non-array type T can be
467 // converted to an rvalue.
468 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
469 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000470 !FromType->isFunctionType() && !FromType->isArrayType() &&
471 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000472 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473
474 // If T is a non-class type, the type of the rvalue is the
475 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000476 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
477 // just strip the qualifiers because they don't matter.
478
479 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor60d62c22008-10-31 16:23:19 +0000480 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000481 }
482 // Array-to-pointer conversion (C++ 4.2)
483 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000484 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000485
486 // An lvalue or rvalue of type "array of N T" or "array of unknown
487 // bound of T" can be converted to an rvalue of type "pointer to
488 // T" (C++ 4.2p1).
489 FromType = Context.getArrayDecayedType(FromType);
490
491 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
492 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000493 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000494
495 // For the purpose of ranking in overload resolution
496 // (13.3.3.1.1), this conversion is considered an
497 // array-to-pointer conversion followed by a qualification
498 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000499 SCS.Second = ICK_Identity;
500 SCS.Third = ICK_Qualification;
501 SCS.ToTypePtr = ToType.getAsOpaquePtr();
502 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000503 }
504 }
505 // Function-to-pointer conversion (C++ 4.3).
506 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000507 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000508
509 // An lvalue of function type T can be converted to an rvalue of
510 // type "pointer to T." The result is a pointer to the
511 // function. (C++ 4.3p1).
512 FromType = Context.getPointerType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000513 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000514 // Address of overloaded function (C++ [over.over]).
515 else if (FunctionDecl *Fn
516 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
517 SCS.First = ICK_Function_To_Pointer;
518
519 // We were able to resolve the address of the overloaded function,
520 // so we can convert to the type of that function.
521 FromType = Fn->getType();
522 if (ToType->isReferenceType())
523 FromType = Context.getReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000524 else if (ToType->isMemberPointerType()) {
525 // Resolve address only succeeds if both sides are member pointers,
526 // but it doesn't have to be the same class. See DR 247.
527 // Note that this means that the type of &Derived::fn can be
528 // Ret (Base::*)(Args) if the fn overload actually found is from the
529 // base class, even if it was brought into the derived class via a
530 // using declaration. The standard isn't clear on this issue at all.
531 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
532 FromType = Context.getMemberPointerType(FromType,
533 Context.getTypeDeclType(M->getParent()).getTypePtr());
534 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000535 FromType = Context.getPointerType(FromType);
536 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000537 // We don't require any conversions for the first step.
538 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000539 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000540 }
541
542 // The second conversion can be an integral promotion, floating
543 // point promotion, integral conversion, floating point conversion,
544 // floating-integral conversion, pointer conversion,
545 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000546 // For overloading in C, this can also be a "compatible-type"
547 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000548 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000549 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000550 // The unqualified versions of the types are the same: there's no
551 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000552 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000553 }
554 // Integral promotion (C++ 4.5).
555 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000556 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000557 FromType = ToType.getUnqualifiedType();
558 }
559 // Floating point promotion (C++ 4.6).
560 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000561 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000562 FromType = ToType.getUnqualifiedType();
563 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000564 // Complex promotion (Clang extension)
565 else if (IsComplexPromotion(FromType, ToType)) {
566 SCS.Second = ICK_Complex_Promotion;
567 FromType = ToType.getUnqualifiedType();
568 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000569 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000570 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000571 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000572 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000573 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000574 FromType = ToType.getUnqualifiedType();
575 }
576 // Floating point conversions (C++ 4.8).
577 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000578 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000579 FromType = ToType.getUnqualifiedType();
580 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000581 // Complex conversions (C99 6.3.1.6)
582 else if (FromType->isComplexType() && ToType->isComplexType()) {
583 SCS.Second = ICK_Complex_Conversion;
584 FromType = ToType.getUnqualifiedType();
585 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000586 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000587 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000588 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000589 ToType->isIntegralType() && !ToType->isBooleanType() &&
590 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000591 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
592 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000593 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000594 FromType = ToType.getUnqualifiedType();
595 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000596 // Complex-real conversions (C99 6.3.1.7)
597 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
598 (ToType->isComplexType() && FromType->isArithmeticType())) {
599 SCS.Second = ICK_Complex_Real;
600 FromType = ToType.getUnqualifiedType();
601 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000602 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000603 else if (IsPointerConversion(From, FromType, ToType, FromType,
604 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000605 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000606 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000607 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000608 // Pointer to member conversions (4.11).
609 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
610 SCS.Second = ICK_Pointer_Member;
611 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000612 // Boolean conversions (C++ 4.12).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000613 else if (ToType->isBooleanType() &&
614 (FromType->isArithmeticType() ||
615 FromType->isEnumeralType() ||
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000616 FromType->isPointerType() ||
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000617 FromType->isBlockPointerType() ||
618 FromType->isMemberPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000619 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000620 FromType = Context.BoolTy;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000621 }
622 // Compatible conversions (Clang extension for C function overloading)
623 else if (!getLangOptions().CPlusPlus &&
624 Context.typesAreCompatible(ToType, FromType)) {
625 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000626 } else {
627 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000628 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000629 }
630
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000631 QualType CanonFrom;
632 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000633 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000634 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000635 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000636 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000637 CanonFrom = Context.getCanonicalType(FromType);
638 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000639 } else {
640 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000641 SCS.Third = ICK_Identity;
642
643 // C++ [over.best.ics]p6:
644 // [...] Any difference in top-level cv-qualification is
645 // subsumed by the initialization itself and does not constitute
646 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000647 CanonFrom = Context.getCanonicalType(FromType);
648 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000649 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000650 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
651 FromType = ToType;
652 CanonFrom = CanonTo;
653 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000654 }
655
656 // If we have not converted the argument type to the parameter type,
657 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000658 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000659 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000660
Douglas Gregor60d62c22008-10-31 16:23:19 +0000661 SCS.ToTypePtr = FromType.getAsOpaquePtr();
662 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000663}
664
665/// IsIntegralPromotion - Determines whether the conversion from the
666/// expression From (whose potentially-adjusted type is FromType) to
667/// ToType is an integral promotion (C++ 4.5). If so, returns true and
668/// sets PromotedType to the promoted type.
669bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
670{
671 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000672 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000673 if (!To) {
674 return false;
675 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000676
677 // An rvalue of type char, signed char, unsigned char, short int, or
678 // unsigned short int can be converted to an rvalue of type int if
679 // int can represent all the values of the source type; otherwise,
680 // the source rvalue can be converted to an rvalue of type unsigned
681 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000682 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000683 if (// We can promote any signed, promotable integer type to an int
684 (FromType->isSignedIntegerType() ||
685 // We can promote any unsigned integer type whose size is
686 // less than int to an int.
687 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000688 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000689 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000690 }
691
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000692 return To->getKind() == BuiltinType::UInt;
693 }
694
695 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
696 // can be converted to an rvalue of the first of the following types
697 // that can represent all the values of its underlying type: int,
698 // unsigned int, long, or unsigned long (C++ 4.5p2).
699 if ((FromType->isEnumeralType() || FromType->isWideCharType())
700 && ToType->isIntegerType()) {
701 // Determine whether the type we're converting from is signed or
702 // unsigned.
703 bool FromIsSigned;
704 uint64_t FromSize = Context.getTypeSize(FromType);
705 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
706 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
707 FromIsSigned = UnderlyingType->isSignedIntegerType();
708 } else {
709 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
710 FromIsSigned = true;
711 }
712
713 // The types we'll try to promote to, in the appropriate
714 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000715 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000716 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000717 Context.LongTy, Context.UnsignedLongTy ,
718 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000719 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000720 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000721 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
722 if (FromSize < ToSize ||
723 (FromSize == ToSize &&
724 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
725 // We found the type that we can promote to. If this is the
726 // type we wanted, we have a promotion. Otherwise, no
727 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000728 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000729 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
730 }
731 }
732 }
733
734 // An rvalue for an integral bit-field (9.6) can be converted to an
735 // rvalue of type int if int can represent all the values of the
736 // bit-field; otherwise, it can be converted to unsigned int if
737 // unsigned int can represent all the values of the bit-field. If
738 // the bit-field is larger yet, no integral promotion applies to
739 // it. If the bit-field has an enumerated type, it is treated as any
740 // other value of that type for promotion purposes (C++ 4.5p3).
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000741 // FIXME: We should delay checking of bit-fields until we actually
742 // perform the conversion.
743 if (MemberExpr *MemRef = dyn_cast_or_null<MemberExpr>(From)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000744 using llvm::APSInt;
Douglas Gregor86f19402008-12-20 23:49:58 +0000745 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
746 APSInt BitWidth;
747 if (MemberDecl->isBitField() &&
748 FromType->isIntegralType() && !FromType->isEnumeralType() &&
749 From->isIntegerConstantExpr(BitWidth, Context)) {
750 APSInt ToSize(Context.getTypeSize(ToType));
751
752 // Are we promoting to an int from a bitfield that fits in an int?
753 if (BitWidth < ToSize ||
754 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
755 return To->getKind() == BuiltinType::Int;
756 }
757
758 // Are we promoting to an unsigned int from an unsigned bitfield
759 // that fits into an unsigned int?
760 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
761 return To->getKind() == BuiltinType::UInt;
762 }
763
764 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000765 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000766 }
767 }
768
769 // An rvalue of type bool can be converted to an rvalue of type int,
770 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000771 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000772 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000773 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000774
775 return false;
776}
777
778/// IsFloatingPointPromotion - Determines whether the conversion from
779/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
780/// returns true and sets PromotedType to the promoted type.
781bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
782{
783 /// An rvalue of type float can be converted to an rvalue of type
784 /// double. (C++ 4.6p1).
785 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000786 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000787 if (FromBuiltin->getKind() == BuiltinType::Float &&
788 ToBuiltin->getKind() == BuiltinType::Double)
789 return true;
790
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000791 // C99 6.3.1.5p1:
792 // When a float is promoted to double or long double, or a
793 // double is promoted to long double [...].
794 if (!getLangOptions().CPlusPlus &&
795 (FromBuiltin->getKind() == BuiltinType::Float ||
796 FromBuiltin->getKind() == BuiltinType::Double) &&
797 (ToBuiltin->getKind() == BuiltinType::LongDouble))
798 return true;
799 }
800
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000801 return false;
802}
803
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000804/// \brief Determine if a conversion is a complex promotion.
805///
806/// A complex promotion is defined as a complex -> complex conversion
807/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000808/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000809bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
810 const ComplexType *FromComplex = FromType->getAsComplexType();
811 if (!FromComplex)
812 return false;
813
814 const ComplexType *ToComplex = ToType->getAsComplexType();
815 if (!ToComplex)
816 return false;
817
818 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000819 ToComplex->getElementType()) ||
820 IsIntegralPromotion(0, FromComplex->getElementType(),
821 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000822}
823
Douglas Gregorcb7de522008-11-26 23:31:11 +0000824/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
825/// the pointer type FromPtr to a pointer to type ToPointee, with the
826/// same type qualifiers as FromPtr has on its pointee type. ToType,
827/// if non-empty, will be a pointer to ToType that may or may not have
828/// the right set of qualifiers on its pointee.
829static QualType
830BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
831 QualType ToPointee, QualType ToType,
832 ASTContext &Context) {
833 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
834 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
835 unsigned Quals = CanonFromPointee.getCVRQualifiers();
836
837 // Exact qualifier match -> return the pointer type we're converting to.
838 if (CanonToPointee.getCVRQualifiers() == Quals) {
839 // ToType is exactly what we need. Return it.
840 if (ToType.getTypePtr())
841 return ToType;
842
843 // Build a pointer to ToPointee. It has the right qualifiers
844 // already.
845 return Context.getPointerType(ToPointee);
846 }
847
848 // Just build a canonical type that has the right qualifiers.
849 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
850}
851
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000852/// IsPointerConversion - Determines whether the conversion of the
853/// expression From, which has the (possibly adjusted) type FromType,
854/// can be converted to the type ToType via a pointer conversion (C++
855/// 4.10). If so, returns true and places the converted type (that
856/// might differ from ToType in its cv-qualifiers at some level) into
857/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000858///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000859/// This routine also supports conversions to and from block pointers
860/// and conversions with Objective-C's 'id', 'id<protocols...>', and
861/// pointers to interfaces. FIXME: Once we've determined the
862/// appropriate overloading rules for Objective-C, we may want to
863/// split the Objective-C checks into a different routine; however,
864/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000865/// conversions, so for now they live here. IncompatibleObjC will be
866/// set if the conversion is an allowed Objective-C conversion that
867/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000868bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000869 QualType& ConvertedType,
870 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000871{
Douglas Gregor45920e82008-12-19 17:40:08 +0000872 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000873 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
874 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000875
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000876 // Conversion from a null pointer constant to any Objective-C pointer type.
877 if (Context.isObjCObjectPointerType(ToType) &&
878 From->isNullPointerConstant(Context)) {
879 ConvertedType = ToType;
880 return true;
881 }
882
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000883 // Blocks: Block pointers can be converted to void*.
884 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
885 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
886 ConvertedType = ToType;
887 return true;
888 }
889 // Blocks: A null pointer constant can be converted to a block
890 // pointer type.
891 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
892 ConvertedType = ToType;
893 return true;
894 }
895
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000896 const PointerType* ToTypePtr = ToType->getAsPointerType();
897 if (!ToTypePtr)
898 return false;
899
900 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
901 if (From->isNullPointerConstant(Context)) {
902 ConvertedType = ToType;
903 return true;
904 }
Sebastian Redl07779722008-10-31 14:43:28 +0000905
Douglas Gregorcb7de522008-11-26 23:31:11 +0000906 // Beyond this point, both types need to be pointers.
907 const PointerType *FromTypePtr = FromType->getAsPointerType();
908 if (!FromTypePtr)
909 return false;
910
911 QualType FromPointeeType = FromTypePtr->getPointeeType();
912 QualType ToPointeeType = ToTypePtr->getPointeeType();
913
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000914 // An rvalue of type "pointer to cv T," where T is an object type,
915 // can be converted to an rvalue of type "pointer to cv void" (C++
916 // 4.10p2).
Douglas Gregorc7887512008-12-19 19:13:09 +0000917 if (FromPointeeType->isIncompleteOrObjectType() &&
918 ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000919 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
920 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000921 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000922 return true;
923 }
924
Douglas Gregorf9201e02009-02-11 23:02:49 +0000925 // When we're overloading in C, we allow a special kind of pointer
926 // conversion for compatible-but-not-identical pointee types.
927 if (!getLangOptions().CPlusPlus &&
928 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
929 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
930 ToPointeeType,
931 ToType, Context);
932 return true;
933 }
934
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000935 // C++ [conv.ptr]p3:
936 //
937 // An rvalue of type "pointer to cv D," where D is a class type,
938 // can be converted to an rvalue of type "pointer to cv B," where
939 // B is a base class (clause 10) of D. If B is an inaccessible
940 // (clause 11) or ambiguous (10.2) base class of D, a program that
941 // necessitates this conversion is ill-formed. The result of the
942 // conversion is a pointer to the base class sub-object of the
943 // derived class object. The null pointer value is converted to
944 // the null pointer value of the destination type.
945 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000946 // Note that we do not check for ambiguity or inaccessibility
947 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +0000948 if (getLangOptions().CPlusPlus &&
949 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorcb7de522008-11-26 23:31:11 +0000950 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000951 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
952 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000953 ToType, Context);
954 return true;
955 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000956
Douglas Gregorc7887512008-12-19 19:13:09 +0000957 return false;
958}
959
960/// isObjCPointerConversion - Determines whether this is an
961/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
962/// with the same arguments and return values.
963bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
964 QualType& ConvertedType,
965 bool &IncompatibleObjC) {
966 if (!getLangOptions().ObjC1)
967 return false;
968
969 // Conversions with Objective-C's id<...>.
970 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
971 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
972 ConvertedType = ToType;
973 return true;
974 }
975
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000976 // Beyond this point, both types need to be pointers or block pointers.
977 QualType ToPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000978 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000979 if (ToTypePtr)
980 ToPointeeType = ToTypePtr->getPointeeType();
981 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
982 ToPointeeType = ToBlockPtr->getPointeeType();
983 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000984 return false;
985
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000986 QualType FromPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000987 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000988 if (FromTypePtr)
989 FromPointeeType = FromTypePtr->getPointeeType();
990 else if (const BlockPointerType *FromBlockPtr
991 = FromType->getAsBlockPointerType())
992 FromPointeeType = FromBlockPtr->getPointeeType();
993 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000994 return false;
995
Douglas Gregorcb7de522008-11-26 23:31:11 +0000996 // Objective C++: We're able to convert from a pointer to an
997 // interface to a pointer to a different interface.
998 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
999 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1000 if (FromIface && ToIface &&
1001 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001002 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001003 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001004 ToType, Context);
1005 return true;
1006 }
1007
Douglas Gregor45920e82008-12-19 17:40:08 +00001008 if (FromIface && ToIface &&
1009 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1010 // Okay: this is some kind of implicit downcast of Objective-C
1011 // interfaces, which is permitted. However, we're going to
1012 // complain about it.
1013 IncompatibleObjC = true;
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001014 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor45920e82008-12-19 17:40:08 +00001015 ToPointeeType,
1016 ToType, Context);
1017 return true;
1018 }
1019
Douglas Gregorcb7de522008-11-26 23:31:11 +00001020 // Objective C++: We're able to convert between "id" and a pointer
1021 // to any interface (in both directions).
Steve Naroff389bf462009-02-12 17:52:19 +00001022 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1023 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +00001024 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1025 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001026 ToType, Context);
1027 return true;
1028 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001029
Douglas Gregordda78892008-12-18 23:43:31 +00001030 // Objective C++: Allow conversions between the Objective-C "id" and
1031 // "Class", in either direction.
Steve Naroff389bf462009-02-12 17:52:19 +00001032 if ((Context.isObjCIdStructType(FromPointeeType) &&
1033 Context.isObjCClassStructType(ToPointeeType)) ||
1034 (Context.isObjCClassStructType(FromPointeeType) &&
1035 Context.isObjCIdStructType(ToPointeeType))) {
Douglas Gregordda78892008-12-18 23:43:31 +00001036 ConvertedType = ToType;
1037 return true;
1038 }
1039
Douglas Gregorc7887512008-12-19 19:13:09 +00001040 // If we have pointers to pointers, recursively check whether this
1041 // is an Objective-C conversion.
1042 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1043 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1044 IncompatibleObjC)) {
1045 // We always complain about this conversion.
1046 IncompatibleObjC = true;
1047 ConvertedType = ToType;
1048 return true;
1049 }
1050
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001051 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001052 // differences in the argument and result types are in Objective-C
1053 // pointer conversions. If so, we permit the conversion (but
1054 // complain about it).
1055 const FunctionTypeProto *FromFunctionType
1056 = FromPointeeType->getAsFunctionTypeProto();
1057 const FunctionTypeProto *ToFunctionType
1058 = ToPointeeType->getAsFunctionTypeProto();
1059 if (FromFunctionType && ToFunctionType) {
1060 // If the function types are exactly the same, this isn't an
1061 // Objective-C pointer conversion.
1062 if (Context.getCanonicalType(FromPointeeType)
1063 == Context.getCanonicalType(ToPointeeType))
1064 return false;
1065
1066 // Perform the quick checks that will tell us whether these
1067 // function types are obviously different.
1068 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1069 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1070 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1071 return false;
1072
1073 bool HasObjCConversion = false;
1074 if (Context.getCanonicalType(FromFunctionType->getResultType())
1075 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1076 // Okay, the types match exactly. Nothing to do.
1077 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1078 ToFunctionType->getResultType(),
1079 ConvertedType, IncompatibleObjC)) {
1080 // Okay, we have an Objective-C pointer conversion.
1081 HasObjCConversion = true;
1082 } else {
1083 // Function types are too different. Abort.
1084 return false;
1085 }
1086
1087 // Check argument types.
1088 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1089 ArgIdx != NumArgs; ++ArgIdx) {
1090 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1091 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1092 if (Context.getCanonicalType(FromArgType)
1093 == Context.getCanonicalType(ToArgType)) {
1094 // Okay, the types match exactly. Nothing to do.
1095 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1096 ConvertedType, IncompatibleObjC)) {
1097 // Okay, we have an Objective-C pointer conversion.
1098 HasObjCConversion = true;
1099 } else {
1100 // Argument types are too different. Abort.
1101 return false;
1102 }
1103 }
1104
1105 if (HasObjCConversion) {
1106 // We had an Objective-C conversion. Allow this pointer
1107 // conversion, but complain about it.
1108 ConvertedType = ToType;
1109 IncompatibleObjC = true;
1110 return true;
1111 }
1112 }
1113
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001114 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001115}
1116
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001117/// CheckPointerConversion - Check the pointer conversion from the
1118/// expression From to the type ToType. This routine checks for
1119/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1120/// conversions for which IsPointerConversion has already returned
1121/// true. It returns true and produces a diagnostic if there was an
1122/// error, or returns false otherwise.
1123bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1124 QualType FromType = From->getType();
1125
1126 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1127 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001128 QualType FromPointeeType = FromPtrType->getPointeeType(),
1129 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001130
1131 // Objective-C++ conversions are always okay.
1132 // FIXME: We should have a different class of conversions for
1133 // the Objective-C++ implicit conversions.
Steve Naroff389bf462009-02-12 17:52:19 +00001134 if (Context.isObjCIdStructType(FromPointeeType) ||
1135 Context.isObjCIdStructType(ToPointeeType) ||
1136 Context.isObjCClassStructType(FromPointeeType) ||
1137 Context.isObjCClassStructType(ToPointeeType))
Douglas Gregordda78892008-12-18 23:43:31 +00001138 return false;
1139
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001140 if (FromPointeeType->isRecordType() &&
1141 ToPointeeType->isRecordType()) {
1142 // We must have a derived-to-base conversion. Check an
1143 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001144 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1145 From->getExprLoc(),
1146 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001147 }
1148 }
1149
1150 return false;
1151}
1152
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001153/// IsMemberPointerConversion - Determines whether the conversion of the
1154/// expression From, which has the (possibly adjusted) type FromType, can be
1155/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1156/// If so, returns true and places the converted type (that might differ from
1157/// ToType in its cv-qualifiers at some level) into ConvertedType.
1158bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1159 QualType ToType, QualType &ConvertedType)
1160{
1161 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1162 if (!ToTypePtr)
1163 return false;
1164
1165 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1166 if (From->isNullPointerConstant(Context)) {
1167 ConvertedType = ToType;
1168 return true;
1169 }
1170
1171 // Otherwise, both types have to be member pointers.
1172 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1173 if (!FromTypePtr)
1174 return false;
1175
1176 // A pointer to member of B can be converted to a pointer to member of D,
1177 // where D is derived from B (C++ 4.11p2).
1178 QualType FromClass(FromTypePtr->getClass(), 0);
1179 QualType ToClass(ToTypePtr->getClass(), 0);
1180 // FIXME: What happens when these are dependent? Is this function even called?
1181
1182 if (IsDerivedFrom(ToClass, FromClass)) {
1183 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1184 ToClass.getTypePtr());
1185 return true;
1186 }
1187
1188 return false;
1189}
1190
1191/// CheckMemberPointerConversion - Check the member pointer conversion from the
1192/// expression From to the type ToType. This routine checks for ambiguous or
1193/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1194/// for which IsMemberPointerConversion has already returned true. It returns
1195/// true and produces a diagnostic if there was an error, or returns false
1196/// otherwise.
1197bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1198 QualType FromType = From->getType();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001199 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1200 if (!FromPtrType)
1201 return false;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001202
Sebastian Redl21593ac2009-01-28 18:33:18 +00001203 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1204 assert(ToPtrType && "No member pointer cast has a target type "
1205 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001206
Sebastian Redl21593ac2009-01-28 18:33:18 +00001207 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1208 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001209
Sebastian Redl21593ac2009-01-28 18:33:18 +00001210 // FIXME: What about dependent types?
1211 assert(FromClass->isRecordType() && "Pointer into non-class.");
1212 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001213
Sebastian Redl21593ac2009-01-28 18:33:18 +00001214 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1215 /*DetectVirtual=*/true);
1216 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1217 assert(DerivationOkay &&
1218 "Should not have been called if derivation isn't OK.");
1219 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001220
Sebastian Redl21593ac2009-01-28 18:33:18 +00001221 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1222 getUnqualifiedType())) {
1223 // Derivation is ambiguous. Redo the check to find the exact paths.
1224 Paths.clear();
1225 Paths.setRecordingPaths(true);
1226 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1227 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1228 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001229
Sebastian Redl21593ac2009-01-28 18:33:18 +00001230 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1231 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1232 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1233 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001234 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001235
1236 if (const CXXRecordType *VBase = Paths.getDetectedVirtual()) {
1237 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1238 << FromClass << ToClass << QualType(VBase, 0)
1239 << From->getSourceRange();
1240 return true;
1241 }
1242
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001243 return false;
1244}
1245
Douglas Gregor98cd5992008-10-21 23:43:52 +00001246/// IsQualificationConversion - Determines whether the conversion from
1247/// an rvalue of type FromType to ToType is a qualification conversion
1248/// (C++ 4.4).
1249bool
1250Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1251{
1252 FromType = Context.getCanonicalType(FromType);
1253 ToType = Context.getCanonicalType(ToType);
1254
1255 // If FromType and ToType are the same type, this is not a
1256 // qualification conversion.
1257 if (FromType == ToType)
1258 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001259
Douglas Gregor98cd5992008-10-21 23:43:52 +00001260 // (C++ 4.4p4):
1261 // A conversion can add cv-qualifiers at levels other than the first
1262 // in multi-level pointers, subject to the following rules: [...]
1263 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001264 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001265 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001266 // Within each iteration of the loop, we check the qualifiers to
1267 // determine if this still looks like a qualification
1268 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001269 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001270 // until there are no more pointers or pointers-to-members left to
1271 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001272 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001273
1274 // -- for every j > 0, if const is in cv 1,j then const is in cv
1275 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001276 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001277 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001278
Douglas Gregor98cd5992008-10-21 23:43:52 +00001279 // -- if the cv 1,j and cv 2,j are different, then const is in
1280 // every cv for 0 < k < j.
1281 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001282 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001283 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001284
Douglas Gregor98cd5992008-10-21 23:43:52 +00001285 // Keep track of whether all prior cv-qualifiers in the "to" type
1286 // include const.
1287 PreviousToQualsIncludeConst
1288 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001289 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001290
1291 // We are left with FromType and ToType being the pointee types
1292 // after unwrapping the original FromType and ToType the same number
1293 // of types. If we unwrapped any pointers, and if FromType and
1294 // ToType have the same unqualified type (since we checked
1295 // qualifiers above), then this is a qualification conversion.
1296 return UnwrappedAnyPointer &&
1297 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1298}
1299
Douglas Gregor734d9862009-01-30 23:27:23 +00001300/// Determines whether there is a user-defined conversion sequence
1301/// (C++ [over.ics.user]) that converts expression From to the type
1302/// ToType. If such a conversion exists, User will contain the
1303/// user-defined conversion sequence that performs such a conversion
1304/// and this routine will return true. Otherwise, this routine returns
1305/// false and User is unspecified.
1306///
1307/// \param AllowConversionFunctions true if the conversion should
1308/// consider conversion functions at all. If false, only constructors
1309/// will be considered.
1310///
1311/// \param AllowExplicit true if the conversion should consider C++0x
1312/// "explicit" conversion functions as well as non-explicit conversion
1313/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001314bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001315 UserDefinedConversionSequence& User,
Douglas Gregor734d9862009-01-30 23:27:23 +00001316 bool AllowConversionFunctions,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001317 bool AllowExplicit)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001318{
1319 OverloadCandidateSet CandidateSet;
1320 if (const CXXRecordType *ToRecordType
1321 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
1322 // C++ [over.match.ctor]p1:
1323 // When objects of class type are direct-initialized (8.5), or
1324 // copy-initialized from an expression of the same or a
1325 // derived class type (8.5), overload resolution selects the
1326 // constructor. [...] For copy-initialization, the candidate
1327 // functions are all the converting constructors (12.3.1) of
1328 // that class. The argument list is the expression-list within
1329 // the parentheses of the initializer.
1330 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001331 DeclarationName ConstructorName
1332 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregore63ef482009-01-13 00:11:19 +00001333 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001334 DeclContext::lookup_iterator Con, ConEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00001335 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001336 Con != ConEnd; ++Con) {
1337 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001338 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +00001339 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1340 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001341 }
1342 }
1343
Douglas Gregor734d9862009-01-30 23:27:23 +00001344 if (!AllowConversionFunctions) {
1345 // Don't allow any conversion functions to enter the overload set.
1346 } else if (const CXXRecordType *FromRecordType
1347 = dyn_cast_or_null<CXXRecordType>(
1348 From->getType()->getAsRecordType())) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001349 // Add all of the conversion functions as candidates.
1350 // FIXME: Look for conversions in base classes!
1351 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
1352 OverloadedFunctionDecl *Conversions
1353 = FromRecordDecl->getConversionFunctions();
1354 for (OverloadedFunctionDecl::function_iterator Func
1355 = Conversions->function_begin();
1356 Func != Conversions->function_end(); ++Func) {
1357 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001358 if (AllowExplicit || !Conv->isExplicit())
1359 AddConversionCandidate(Conv, From, ToType, CandidateSet);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001360 }
1361 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001362
1363 OverloadCandidateSet::iterator Best;
1364 switch (BestViableFunction(CandidateSet, Best)) {
1365 case OR_Success:
1366 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001367 if (CXXConstructorDecl *Constructor
1368 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1369 // C++ [over.ics.user]p1:
1370 // If the user-defined conversion is specified by a
1371 // constructor (12.3.1), the initial standard conversion
1372 // sequence converts the source type to the type required by
1373 // the argument of the constructor.
1374 //
1375 // FIXME: What about ellipsis conversions?
1376 QualType ThisType = Constructor->getThisType(Context);
1377 User.Before = Best->Conversions[0].Standard;
1378 User.ConversionFunction = Constructor;
1379 User.After.setAsIdentityConversion();
1380 User.After.FromTypePtr
1381 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1382 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1383 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001384 } else if (CXXConversionDecl *Conversion
1385 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1386 // C++ [over.ics.user]p1:
1387 //
1388 // [...] If the user-defined conversion is specified by a
1389 // conversion function (12.3.2), the initial standard
1390 // conversion sequence converts the source type to the
1391 // implicit object parameter of the conversion function.
1392 User.Before = Best->Conversions[0].Standard;
1393 User.ConversionFunction = Conversion;
1394
1395 // C++ [over.ics.user]p2:
1396 // The second standard conversion sequence converts the
1397 // result of the user-defined conversion to the target type
1398 // for the sequence. Since an implicit conversion sequence
1399 // is an initialization, the special rules for
1400 // initialization by user-defined conversion apply when
1401 // selecting the best user-defined conversion for a
1402 // user-defined conversion sequence (see 13.3.3 and
1403 // 13.3.3.1).
1404 User.After = Best->FinalConversion;
1405 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001406 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001407 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001408 return false;
1409 }
1410
1411 case OR_No_Viable_Function:
1412 // No conversion here! We're done.
1413 return false;
1414
1415 case OR_Ambiguous:
1416 // FIXME: See C++ [over.best.ics]p10 for the handling of
1417 // ambiguous conversion sequences.
1418 return false;
1419 }
1420
1421 return false;
1422}
1423
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001424/// CompareImplicitConversionSequences - Compare two implicit
1425/// conversion sequences to determine whether one is better than the
1426/// other or if they are indistinguishable (C++ 13.3.3.2).
1427ImplicitConversionSequence::CompareKind
1428Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1429 const ImplicitConversionSequence& ICS2)
1430{
1431 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1432 // conversion sequences (as defined in 13.3.3.1)
1433 // -- a standard conversion sequence (13.3.3.1.1) is a better
1434 // conversion sequence than a user-defined conversion sequence or
1435 // an ellipsis conversion sequence, and
1436 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1437 // conversion sequence than an ellipsis conversion sequence
1438 // (13.3.3.1.3).
1439 //
1440 if (ICS1.ConversionKind < ICS2.ConversionKind)
1441 return ImplicitConversionSequence::Better;
1442 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1443 return ImplicitConversionSequence::Worse;
1444
1445 // Two implicit conversion sequences of the same form are
1446 // indistinguishable conversion sequences unless one of the
1447 // following rules apply: (C++ 13.3.3.2p3):
1448 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1449 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1450 else if (ICS1.ConversionKind ==
1451 ImplicitConversionSequence::UserDefinedConversion) {
1452 // User-defined conversion sequence U1 is a better conversion
1453 // sequence than another user-defined conversion sequence U2 if
1454 // they contain the same user-defined conversion function or
1455 // constructor and if the second standard conversion sequence of
1456 // U1 is better than the second standard conversion sequence of
1457 // U2 (C++ 13.3.3.2p3).
1458 if (ICS1.UserDefined.ConversionFunction ==
1459 ICS2.UserDefined.ConversionFunction)
1460 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1461 ICS2.UserDefined.After);
1462 }
1463
1464 return ImplicitConversionSequence::Indistinguishable;
1465}
1466
1467/// CompareStandardConversionSequences - Compare two standard
1468/// conversion sequences to determine whether one is better than the
1469/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1470ImplicitConversionSequence::CompareKind
1471Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1472 const StandardConversionSequence& SCS2)
1473{
1474 // Standard conversion sequence S1 is a better conversion sequence
1475 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1476
1477 // -- S1 is a proper subsequence of S2 (comparing the conversion
1478 // sequences in the canonical form defined by 13.3.3.1.1,
1479 // excluding any Lvalue Transformation; the identity conversion
1480 // sequence is considered to be a subsequence of any
1481 // non-identity conversion sequence) or, if not that,
1482 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1483 // Neither is a proper subsequence of the other. Do nothing.
1484 ;
1485 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1486 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1487 (SCS1.Second == ICK_Identity &&
1488 SCS1.Third == ICK_Identity))
1489 // SCS1 is a proper subsequence of SCS2.
1490 return ImplicitConversionSequence::Better;
1491 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1492 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1493 (SCS2.Second == ICK_Identity &&
1494 SCS2.Third == ICK_Identity))
1495 // SCS2 is a proper subsequence of SCS1.
1496 return ImplicitConversionSequence::Worse;
1497
1498 // -- the rank of S1 is better than the rank of S2 (by the rules
1499 // defined below), or, if not that,
1500 ImplicitConversionRank Rank1 = SCS1.getRank();
1501 ImplicitConversionRank Rank2 = SCS2.getRank();
1502 if (Rank1 < Rank2)
1503 return ImplicitConversionSequence::Better;
1504 else if (Rank2 < Rank1)
1505 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001506
Douglas Gregor57373262008-10-22 14:17:15 +00001507 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1508 // are indistinguishable unless one of the following rules
1509 // applies:
1510
1511 // A conversion that is not a conversion of a pointer, or
1512 // pointer to member, to bool is better than another conversion
1513 // that is such a conversion.
1514 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1515 return SCS2.isPointerConversionToBool()
1516 ? ImplicitConversionSequence::Better
1517 : ImplicitConversionSequence::Worse;
1518
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001519 // C++ [over.ics.rank]p4b2:
1520 //
1521 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001522 // conversion of B* to A* is better than conversion of B* to
1523 // void*, and conversion of A* to void* is better than conversion
1524 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001525 bool SCS1ConvertsToVoid
1526 = SCS1.isPointerConversionToVoidPointer(Context);
1527 bool SCS2ConvertsToVoid
1528 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001529 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1530 // Exactly one of the conversion sequences is a conversion to
1531 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001532 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1533 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001534 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1535 // Neither conversion sequence converts to a void pointer; compare
1536 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001537 if (ImplicitConversionSequence::CompareKind DerivedCK
1538 = CompareDerivedToBaseConversions(SCS1, SCS2))
1539 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001540 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1541 // Both conversion sequences are conversions to void
1542 // pointers. Compare the source types to determine if there's an
1543 // inheritance relationship in their sources.
1544 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1545 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1546
1547 // Adjust the types we're converting from via the array-to-pointer
1548 // conversion, if we need to.
1549 if (SCS1.First == ICK_Array_To_Pointer)
1550 FromType1 = Context.getArrayDecayedType(FromType1);
1551 if (SCS2.First == ICK_Array_To_Pointer)
1552 FromType2 = Context.getArrayDecayedType(FromType2);
1553
1554 QualType FromPointee1
1555 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1556 QualType FromPointee2
1557 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1558
1559 if (IsDerivedFrom(FromPointee2, FromPointee1))
1560 return ImplicitConversionSequence::Better;
1561 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1562 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001563
1564 // Objective-C++: If one interface is more specific than the
1565 // other, it is the better one.
1566 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1567 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1568 if (FromIface1 && FromIface1) {
1569 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1570 return ImplicitConversionSequence::Better;
1571 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1572 return ImplicitConversionSequence::Worse;
1573 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001574 }
Douglas Gregor57373262008-10-22 14:17:15 +00001575
1576 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1577 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001578 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001579 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001580 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001581
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001582 // C++ [over.ics.rank]p3b4:
1583 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1584 // which the references refer are the same type except for
1585 // top-level cv-qualifiers, and the type to which the reference
1586 // initialized by S2 refers is more cv-qualified than the type
1587 // to which the reference initialized by S1 refers.
1588 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1589 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1590 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1591 T1 = Context.getCanonicalType(T1);
1592 T2 = Context.getCanonicalType(T2);
1593 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1594 if (T2.isMoreQualifiedThan(T1))
1595 return ImplicitConversionSequence::Better;
1596 else if (T1.isMoreQualifiedThan(T2))
1597 return ImplicitConversionSequence::Worse;
1598 }
1599 }
Douglas Gregor57373262008-10-22 14:17:15 +00001600
1601 return ImplicitConversionSequence::Indistinguishable;
1602}
1603
1604/// CompareQualificationConversions - Compares two standard conversion
1605/// sequences to determine whether they can be ranked based on their
1606/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1607ImplicitConversionSequence::CompareKind
1608Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1609 const StandardConversionSequence& SCS2)
1610{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001611 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001612 // -- S1 and S2 differ only in their qualification conversion and
1613 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1614 // cv-qualification signature of type T1 is a proper subset of
1615 // the cv-qualification signature of type T2, and S1 is not the
1616 // deprecated string literal array-to-pointer conversion (4.2).
1617 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1618 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1619 return ImplicitConversionSequence::Indistinguishable;
1620
1621 // FIXME: the example in the standard doesn't use a qualification
1622 // conversion (!)
1623 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1624 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1625 T1 = Context.getCanonicalType(T1);
1626 T2 = Context.getCanonicalType(T2);
1627
1628 // If the types are the same, we won't learn anything by unwrapped
1629 // them.
1630 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1631 return ImplicitConversionSequence::Indistinguishable;
1632
1633 ImplicitConversionSequence::CompareKind Result
1634 = ImplicitConversionSequence::Indistinguishable;
1635 while (UnwrapSimilarPointerTypes(T1, T2)) {
1636 // Within each iteration of the loop, we check the qualifiers to
1637 // determine if this still looks like a qualification
1638 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001639 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001640 // until there are no more pointers or pointers-to-members left
1641 // to unwrap. This essentially mimics what
1642 // IsQualificationConversion does, but here we're checking for a
1643 // strict subset of qualifiers.
1644 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1645 // The qualifiers are the same, so this doesn't tell us anything
1646 // about how the sequences rank.
1647 ;
1648 else if (T2.isMoreQualifiedThan(T1)) {
1649 // T1 has fewer qualifiers, so it could be the better sequence.
1650 if (Result == ImplicitConversionSequence::Worse)
1651 // Neither has qualifiers that are a subset of the other's
1652 // qualifiers.
1653 return ImplicitConversionSequence::Indistinguishable;
1654
1655 Result = ImplicitConversionSequence::Better;
1656 } else if (T1.isMoreQualifiedThan(T2)) {
1657 // T2 has fewer qualifiers, so it could be the better sequence.
1658 if (Result == ImplicitConversionSequence::Better)
1659 // Neither has qualifiers that are a subset of the other's
1660 // qualifiers.
1661 return ImplicitConversionSequence::Indistinguishable;
1662
1663 Result = ImplicitConversionSequence::Worse;
1664 } else {
1665 // Qualifiers are disjoint.
1666 return ImplicitConversionSequence::Indistinguishable;
1667 }
1668
1669 // If the types after this point are equivalent, we're done.
1670 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1671 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001672 }
1673
Douglas Gregor57373262008-10-22 14:17:15 +00001674 // Check that the winning standard conversion sequence isn't using
1675 // the deprecated string literal array to pointer conversion.
1676 switch (Result) {
1677 case ImplicitConversionSequence::Better:
1678 if (SCS1.Deprecated)
1679 Result = ImplicitConversionSequence::Indistinguishable;
1680 break;
1681
1682 case ImplicitConversionSequence::Indistinguishable:
1683 break;
1684
1685 case ImplicitConversionSequence::Worse:
1686 if (SCS2.Deprecated)
1687 Result = ImplicitConversionSequence::Indistinguishable;
1688 break;
1689 }
1690
1691 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001692}
1693
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001694/// CompareDerivedToBaseConversions - Compares two standard conversion
1695/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001696/// various kinds of derived-to-base conversions (C++
1697/// [over.ics.rank]p4b3). As part of these checks, we also look at
1698/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001699ImplicitConversionSequence::CompareKind
1700Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1701 const StandardConversionSequence& SCS2) {
1702 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1703 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1704 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1705 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1706
1707 // Adjust the types we're converting from via the array-to-pointer
1708 // conversion, if we need to.
1709 if (SCS1.First == ICK_Array_To_Pointer)
1710 FromType1 = Context.getArrayDecayedType(FromType1);
1711 if (SCS2.First == ICK_Array_To_Pointer)
1712 FromType2 = Context.getArrayDecayedType(FromType2);
1713
1714 // Canonicalize all of the types.
1715 FromType1 = Context.getCanonicalType(FromType1);
1716 ToType1 = Context.getCanonicalType(ToType1);
1717 FromType2 = Context.getCanonicalType(FromType2);
1718 ToType2 = Context.getCanonicalType(ToType2);
1719
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001720 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001721 //
1722 // If class B is derived directly or indirectly from class A and
1723 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001724 //
1725 // For Objective-C, we let A, B, and C also be Objective-C
1726 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001727
1728 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001729 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001730 SCS2.Second == ICK_Pointer_Conversion &&
1731 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1732 FromType1->isPointerType() && FromType2->isPointerType() &&
1733 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001734 QualType FromPointee1
1735 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1736 QualType ToPointee1
1737 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1738 QualType FromPointee2
1739 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1740 QualType ToPointee2
1741 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001742
1743 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1744 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1745 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1746 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1747
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001748 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001749 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1750 if (IsDerivedFrom(ToPointee1, ToPointee2))
1751 return ImplicitConversionSequence::Better;
1752 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1753 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001754
1755 if (ToIface1 && ToIface2) {
1756 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1757 return ImplicitConversionSequence::Better;
1758 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1759 return ImplicitConversionSequence::Worse;
1760 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001761 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001762
1763 // -- conversion of B* to A* is better than conversion of C* to A*,
1764 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1765 if (IsDerivedFrom(FromPointee2, FromPointee1))
1766 return ImplicitConversionSequence::Better;
1767 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1768 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001769
1770 if (FromIface1 && FromIface2) {
1771 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1772 return ImplicitConversionSequence::Better;
1773 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1774 return ImplicitConversionSequence::Worse;
1775 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001776 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001777 }
1778
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001779 // Compare based on reference bindings.
1780 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1781 SCS1.Second == ICK_Derived_To_Base) {
1782 // -- binding of an expression of type C to a reference of type
1783 // B& is better than binding an expression of type C to a
1784 // reference of type A&,
1785 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1786 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1787 if (IsDerivedFrom(ToType1, ToType2))
1788 return ImplicitConversionSequence::Better;
1789 else if (IsDerivedFrom(ToType2, ToType1))
1790 return ImplicitConversionSequence::Worse;
1791 }
1792
Douglas Gregor225c41e2008-11-03 19:09:14 +00001793 // -- binding of an expression of type B to a reference of type
1794 // A& is better than binding an expression of type C to a
1795 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001796 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1797 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1798 if (IsDerivedFrom(FromType2, FromType1))
1799 return ImplicitConversionSequence::Better;
1800 else if (IsDerivedFrom(FromType1, FromType2))
1801 return ImplicitConversionSequence::Worse;
1802 }
1803 }
1804
1805
1806 // FIXME: conversion of A::* to B::* is better than conversion of
1807 // A::* to C::*,
1808
1809 // FIXME: conversion of B::* to C::* is better than conversion of
1810 // A::* to C::*, and
1811
Douglas Gregor225c41e2008-11-03 19:09:14 +00001812 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1813 SCS1.Second == ICK_Derived_To_Base) {
1814 // -- conversion of C to B is better than conversion of C to A,
1815 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1816 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1817 if (IsDerivedFrom(ToType1, ToType2))
1818 return ImplicitConversionSequence::Better;
1819 else if (IsDerivedFrom(ToType2, ToType1))
1820 return ImplicitConversionSequence::Worse;
1821 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001822
Douglas Gregor225c41e2008-11-03 19:09:14 +00001823 // -- conversion of B to A is better than conversion of C to A.
1824 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1825 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1826 if (IsDerivedFrom(FromType2, FromType1))
1827 return ImplicitConversionSequence::Better;
1828 else if (IsDerivedFrom(FromType1, FromType2))
1829 return ImplicitConversionSequence::Worse;
1830 }
1831 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001832
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001833 return ImplicitConversionSequence::Indistinguishable;
1834}
1835
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001836/// TryCopyInitialization - Try to copy-initialize a value of type
1837/// ToType from the expression From. Return the implicit conversion
1838/// sequence required to pass this argument, which may be a bad
1839/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001840/// a parameter of this type). If @p SuppressUserConversions, then we
1841/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001842ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001843Sema::TryCopyInitialization(Expr *From, QualType ToType,
1844 bool SuppressUserConversions) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001845 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001846 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001847 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001848 return ICS;
1849 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001850 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001851 }
1852}
1853
1854/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1855/// type ToType. Returns true (and emits a diagnostic) if there was
1856/// an error, returns false if the initialization succeeded.
1857bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1858 const char* Flavor) {
1859 if (!getLangOptions().CPlusPlus) {
1860 // In C, argument passing is the same as performing an assignment.
1861 QualType FromType = From->getType();
1862 AssignConvertType ConvTy =
1863 CheckSingleAssignmentConstraints(ToType, From);
1864
1865 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1866 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001867 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001868
1869 if (ToType->isReferenceType())
1870 return CheckReferenceInit(From, ToType);
1871
Douglas Gregor45920e82008-12-19 17:40:08 +00001872 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001873 return false;
1874
1875 return Diag(From->getSourceRange().getBegin(),
1876 diag::err_typecheck_convert_incompatible)
1877 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001878}
1879
Douglas Gregor96176b32008-11-18 23:14:02 +00001880/// TryObjectArgumentInitialization - Try to initialize the object
1881/// parameter of the given member function (@c Method) from the
1882/// expression @p From.
1883ImplicitConversionSequence
1884Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1885 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1886 unsigned MethodQuals = Method->getTypeQualifiers();
1887 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1888
1889 // Set up the conversion sequence as a "bad" conversion, to allow us
1890 // to exit early.
1891 ImplicitConversionSequence ICS;
1892 ICS.Standard.setAsIdentityConversion();
1893 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1894
1895 // We need to have an object of class type.
1896 QualType FromType = From->getType();
1897 if (!FromType->isRecordType())
1898 return ICS;
1899
1900 // The implicit object parmeter is has the type "reference to cv X",
1901 // where X is the class of which the function is a member
1902 // (C++ [over.match.funcs]p4). However, when finding an implicit
1903 // conversion sequence for the argument, we are not allowed to
1904 // create temporaries or perform user-defined conversions
1905 // (C++ [over.match.funcs]p5). We perform a simplified version of
1906 // reference binding here, that allows class rvalues to bind to
1907 // non-constant references.
1908
1909 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1910 // with the implicit object parameter (C++ [over.match.funcs]p5).
1911 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1912 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1913 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1914 return ICS;
1915
1916 // Check that we have either the same type or a derived type. It
1917 // affects the conversion rank.
1918 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1919 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1920 ICS.Standard.Second = ICK_Identity;
1921 else if (IsDerivedFrom(FromType, ClassType))
1922 ICS.Standard.Second = ICK_Derived_To_Base;
1923 else
1924 return ICS;
1925
1926 // Success. Mark this as a reference binding.
1927 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1928 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1929 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1930 ICS.Standard.ReferenceBinding = true;
1931 ICS.Standard.DirectBinding = true;
1932 return ICS;
1933}
1934
1935/// PerformObjectArgumentInitialization - Perform initialization of
1936/// the implicit object parameter for the given Method with the given
1937/// expression.
1938bool
1939Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1940 QualType ImplicitParamType
1941 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1942 ImplicitConversionSequence ICS
1943 = TryObjectArgumentInitialization(From, Method);
1944 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1945 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001946 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001947 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001948
1949 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1950 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1951 From->getSourceRange().getBegin(),
1952 From->getSourceRange()))
1953 return true;
1954
1955 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1956 return false;
1957}
1958
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001959/// TryContextuallyConvertToBool - Attempt to contextually convert the
1960/// expression From to bool (C++0x [conv]p3).
1961ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1962 return TryImplicitConversion(From, Context.BoolTy, false, true);
1963}
1964
1965/// PerformContextuallyConvertToBool - Perform a contextual conversion
1966/// of the expression From to bool (C++0x [conv]p3).
1967bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1968 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1969 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1970 return false;
1971
1972 return Diag(From->getSourceRange().getBegin(),
1973 diag::err_typecheck_bool_condition)
1974 << From->getType() << From->getSourceRange();
1975}
1976
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001977/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001978/// candidate functions, using the given function call arguments. If
1979/// @p SuppressUserConversions, then don't allow user-defined
1980/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001981void
1982Sema::AddOverloadCandidate(FunctionDecl *Function,
1983 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001984 OverloadCandidateSet& CandidateSet,
1985 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001986{
1987 const FunctionTypeProto* Proto
1988 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1989 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001990 assert(!isa<CXXConversionDecl>(Function) &&
1991 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001992
Douglas Gregor88a35142008-12-22 05:46:06 +00001993 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
1994 // If we get here, it's because we're calling a member function
1995 // that is named without a member access expression (e.g.,
1996 // "this->f") that was either written explicitly or created
1997 // implicitly. This can happen with a qualified call to a member
1998 // function, e.g., X::f(). We use a NULL object as the implied
1999 // object argument (C++ [over.call.func]p3).
2000 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2001 SuppressUserConversions);
2002 return;
2003 }
2004
2005
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002006 // Add this candidate
2007 CandidateSet.push_back(OverloadCandidate());
2008 OverloadCandidate& Candidate = CandidateSet.back();
2009 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002010 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002011 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002012 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002013
2014 unsigned NumArgsInProto = Proto->getNumArgs();
2015
2016 // (C++ 13.3.2p2): A candidate function having fewer than m
2017 // parameters is viable only if it has an ellipsis in its parameter
2018 // list (8.3.5).
2019 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2020 Candidate.Viable = false;
2021 return;
2022 }
2023
2024 // (C++ 13.3.2p2): A candidate function having more than m parameters
2025 // is viable only if the (m+1)st parameter has a default argument
2026 // (8.3.6). For the purposes of overload resolution, the
2027 // parameter list is truncated on the right, so that there are
2028 // exactly m parameters.
2029 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2030 if (NumArgs < MinRequiredArgs) {
2031 // Not enough arguments.
2032 Candidate.Viable = false;
2033 return;
2034 }
2035
2036 // Determine the implicit conversion sequences for each of the
2037 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002038 Candidate.Conversions.resize(NumArgs);
2039 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2040 if (ArgIdx < NumArgsInProto) {
2041 // (C++ 13.3.2p3): for F to be a viable function, there shall
2042 // exist for each argument an implicit conversion sequence
2043 // (13.3.3.1) that converts that argument to the corresponding
2044 // parameter of F.
2045 QualType ParamType = Proto->getArgType(ArgIdx);
2046 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00002047 = TryCopyInitialization(Args[ArgIdx], ParamType,
2048 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002049 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002050 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002051 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002052 break;
2053 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002054 } else {
2055 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2056 // argument for which there is no corresponding parameter is
2057 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2058 Candidate.Conversions[ArgIdx].ConversionKind
2059 = ImplicitConversionSequence::EllipsisConversion;
2060 }
2061 }
2062}
2063
Douglas Gregor96176b32008-11-18 23:14:02 +00002064/// AddMethodCandidate - Adds the given C++ member function to the set
2065/// of candidate functions, using the given function call arguments
2066/// and the object argument (@c Object). For example, in a call
2067/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2068/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2069/// allow user-defined conversions via constructors or conversion
2070/// operators.
2071void
2072Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2073 Expr **Args, unsigned NumArgs,
2074 OverloadCandidateSet& CandidateSet,
2075 bool SuppressUserConversions)
2076{
2077 const FunctionTypeProto* Proto
2078 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
2079 assert(Proto && "Methods without a prototype cannot be overloaded");
2080 assert(!isa<CXXConversionDecl>(Method) &&
2081 "Use AddConversionCandidate for conversion functions");
2082
2083 // Add this candidate
2084 CandidateSet.push_back(OverloadCandidate());
2085 OverloadCandidate& Candidate = CandidateSet.back();
2086 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002087 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002088 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002089
2090 unsigned NumArgsInProto = Proto->getNumArgs();
2091
2092 // (C++ 13.3.2p2): A candidate function having fewer than m
2093 // parameters is viable only if it has an ellipsis in its parameter
2094 // list (8.3.5).
2095 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2096 Candidate.Viable = false;
2097 return;
2098 }
2099
2100 // (C++ 13.3.2p2): A candidate function having more than m parameters
2101 // is viable only if the (m+1)st parameter has a default argument
2102 // (8.3.6). For the purposes of overload resolution, the
2103 // parameter list is truncated on the right, so that there are
2104 // exactly m parameters.
2105 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2106 if (NumArgs < MinRequiredArgs) {
2107 // Not enough arguments.
2108 Candidate.Viable = false;
2109 return;
2110 }
2111
2112 Candidate.Viable = true;
2113 Candidate.Conversions.resize(NumArgs + 1);
2114
Douglas Gregor88a35142008-12-22 05:46:06 +00002115 if (Method->isStatic() || !Object)
2116 // The implicit object argument is ignored.
2117 Candidate.IgnoreObjectArgument = true;
2118 else {
2119 // Determine the implicit conversion sequence for the object
2120 // parameter.
2121 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2122 if (Candidate.Conversions[0].ConversionKind
2123 == ImplicitConversionSequence::BadConversion) {
2124 Candidate.Viable = false;
2125 return;
2126 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002127 }
2128
2129 // Determine the implicit conversion sequences for each of the
2130 // arguments.
2131 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2132 if (ArgIdx < NumArgsInProto) {
2133 // (C++ 13.3.2p3): for F to be a viable function, there shall
2134 // exist for each argument an implicit conversion sequence
2135 // (13.3.3.1) that converts that argument to the corresponding
2136 // parameter of F.
2137 QualType ParamType = Proto->getArgType(ArgIdx);
2138 Candidate.Conversions[ArgIdx + 1]
2139 = TryCopyInitialization(Args[ArgIdx], ParamType,
2140 SuppressUserConversions);
2141 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2142 == ImplicitConversionSequence::BadConversion) {
2143 Candidate.Viable = false;
2144 break;
2145 }
2146 } else {
2147 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2148 // argument for which there is no corresponding parameter is
2149 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2150 Candidate.Conversions[ArgIdx + 1].ConversionKind
2151 = ImplicitConversionSequence::EllipsisConversion;
2152 }
2153 }
2154}
2155
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002156/// AddConversionCandidate - Add a C++ conversion function as a
2157/// candidate in the candidate set (C++ [over.match.conv],
2158/// C++ [over.match.copy]). From is the expression we're converting from,
2159/// and ToType is the type that we're eventually trying to convert to
2160/// (which may or may not be the same type as the type that the
2161/// conversion function produces).
2162void
2163Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2164 Expr *From, QualType ToType,
2165 OverloadCandidateSet& CandidateSet) {
2166 // Add this candidate
2167 CandidateSet.push_back(OverloadCandidate());
2168 OverloadCandidate& Candidate = CandidateSet.back();
2169 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002170 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002171 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002172 Candidate.FinalConversion.setAsIdentityConversion();
2173 Candidate.FinalConversion.FromTypePtr
2174 = Conversion->getConversionType().getAsOpaquePtr();
2175 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2176
Douglas Gregor96176b32008-11-18 23:14:02 +00002177 // Determine the implicit conversion sequence for the implicit
2178 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002179 Candidate.Viable = true;
2180 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002181 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002182
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002183 if (Candidate.Conversions[0].ConversionKind
2184 == ImplicitConversionSequence::BadConversion) {
2185 Candidate.Viable = false;
2186 return;
2187 }
2188
2189 // To determine what the conversion from the result of calling the
2190 // conversion function to the type we're eventually trying to
2191 // convert to (ToType), we need to synthesize a call to the
2192 // conversion function and attempt copy initialization from it. This
2193 // makes sure that we get the right semantics with respect to
2194 // lvalues/rvalues and the type. Fortunately, we can allocate this
2195 // call on the stack and we don't need its arguments to be
2196 // well-formed.
2197 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2198 SourceLocation());
2199 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002200 &ConversionRef, false);
Ted Kremenek668bf912009-02-09 20:51:47 +00002201
2202 // Note that it is safe to allocate CallExpr on the stack here because
2203 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2204 // allocator).
2205 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002206 Conversion->getConversionType().getNonReferenceType(),
2207 SourceLocation());
2208 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2209 switch (ICS.ConversionKind) {
2210 case ImplicitConversionSequence::StandardConversion:
2211 Candidate.FinalConversion = ICS.Standard;
2212 break;
2213
2214 case ImplicitConversionSequence::BadConversion:
2215 Candidate.Viable = false;
2216 break;
2217
2218 default:
2219 assert(false &&
2220 "Can only end up with a standard conversion sequence or failure");
2221 }
2222}
2223
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002224/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2225/// converts the given @c Object to a function pointer via the
2226/// conversion function @c Conversion, and then attempts to call it
2227/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2228/// the type of function that we'll eventually be calling.
2229void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2230 const FunctionTypeProto *Proto,
2231 Expr *Object, Expr **Args, unsigned NumArgs,
2232 OverloadCandidateSet& CandidateSet) {
2233 CandidateSet.push_back(OverloadCandidate());
2234 OverloadCandidate& Candidate = CandidateSet.back();
2235 Candidate.Function = 0;
2236 Candidate.Surrogate = Conversion;
2237 Candidate.Viable = true;
2238 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002239 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002240 Candidate.Conversions.resize(NumArgs + 1);
2241
2242 // Determine the implicit conversion sequence for the implicit
2243 // object parameter.
2244 ImplicitConversionSequence ObjectInit
2245 = TryObjectArgumentInitialization(Object, Conversion);
2246 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2247 Candidate.Viable = false;
2248 return;
2249 }
2250
2251 // The first conversion is actually a user-defined conversion whose
2252 // first conversion is ObjectInit's standard conversion (which is
2253 // effectively a reference binding). Record it as such.
2254 Candidate.Conversions[0].ConversionKind
2255 = ImplicitConversionSequence::UserDefinedConversion;
2256 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2257 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2258 Candidate.Conversions[0].UserDefined.After
2259 = Candidate.Conversions[0].UserDefined.Before;
2260 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2261
2262 // Find the
2263 unsigned NumArgsInProto = Proto->getNumArgs();
2264
2265 // (C++ 13.3.2p2): A candidate function having fewer than m
2266 // parameters is viable only if it has an ellipsis in its parameter
2267 // list (8.3.5).
2268 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2269 Candidate.Viable = false;
2270 return;
2271 }
2272
2273 // Function types don't have any default arguments, so just check if
2274 // we have enough arguments.
2275 if (NumArgs < NumArgsInProto) {
2276 // Not enough arguments.
2277 Candidate.Viable = false;
2278 return;
2279 }
2280
2281 // Determine the implicit conversion sequences for each of the
2282 // arguments.
2283 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2284 if (ArgIdx < NumArgsInProto) {
2285 // (C++ 13.3.2p3): for F to be a viable function, there shall
2286 // exist for each argument an implicit conversion sequence
2287 // (13.3.3.1) that converts that argument to the corresponding
2288 // parameter of F.
2289 QualType ParamType = Proto->getArgType(ArgIdx);
2290 Candidate.Conversions[ArgIdx + 1]
2291 = TryCopyInitialization(Args[ArgIdx], ParamType,
2292 /*SuppressUserConversions=*/false);
2293 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2294 == ImplicitConversionSequence::BadConversion) {
2295 Candidate.Viable = false;
2296 break;
2297 }
2298 } else {
2299 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2300 // argument for which there is no corresponding parameter is
2301 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2302 Candidate.Conversions[ArgIdx + 1].ConversionKind
2303 = ImplicitConversionSequence::EllipsisConversion;
2304 }
2305 }
2306}
2307
Douglas Gregor447b69e2008-11-19 03:25:36 +00002308/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2309/// an acceptable non-member overloaded operator for a call whose
2310/// arguments have types T1 (and, if non-empty, T2). This routine
2311/// implements the check in C++ [over.match.oper]p3b2 concerning
2312/// enumeration types.
2313static bool
2314IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2315 QualType T1, QualType T2,
2316 ASTContext &Context) {
2317 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2318 return true;
2319
2320 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
2321 if (Proto->getNumArgs() < 1)
2322 return false;
2323
2324 if (T1->isEnumeralType()) {
2325 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2326 if (Context.getCanonicalType(T1).getUnqualifiedType()
2327 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2328 return true;
2329 }
2330
2331 if (Proto->getNumArgs() < 2)
2332 return false;
2333
2334 if (!T2.isNull() && T2->isEnumeralType()) {
2335 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2336 if (Context.getCanonicalType(T2).getUnqualifiedType()
2337 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2338 return true;
2339 }
2340
2341 return false;
2342}
2343
Douglas Gregor96176b32008-11-18 23:14:02 +00002344/// AddOperatorCandidates - Add the overloaded operator candidates for
2345/// the operator Op that was used in an operator expression such as "x
2346/// Op y". S is the scope in which the expression occurred (used for
2347/// name lookup of the operator), Args/NumArgs provides the operator
2348/// arguments, and CandidateSet will store the added overload
2349/// candidates. (C++ [over.match.oper]).
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002350bool Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2351 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002352 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002353 OverloadCandidateSet& CandidateSet,
2354 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002355 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2356
2357 // C++ [over.match.oper]p3:
2358 // For a unary operator @ with an operand of a type whose
2359 // cv-unqualified version is T1, and for a binary operator @ with
2360 // a left operand of a type whose cv-unqualified version is T1 and
2361 // a right operand of a type whose cv-unqualified version is T2,
2362 // three sets of candidate functions, designated member
2363 // candidates, non-member candidates and built-in candidates, are
2364 // constructed as follows:
2365 QualType T1 = Args[0]->getType();
2366 QualType T2;
2367 if (NumArgs > 1)
2368 T2 = Args[1]->getType();
2369
2370 // -- If T1 is a class type, the set of member candidates is the
2371 // result of the qualified lookup of T1::operator@
2372 // (13.3.1.1.1); otherwise, the set of member candidates is
2373 // empty.
2374 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002375 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00002376 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002377 Oper != OperEnd; ++Oper)
2378 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2379 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002380 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002381 }
2382
2383 // -- The set of non-member candidates is the result of the
2384 // unqualified lookup of operator@ in the context of the
2385 // expression according to the usual rules for name lookup in
2386 // unqualified function calls (3.4.2) except that all member
2387 // functions are ignored. However, if no operand has a class
2388 // type, only those non-member functions in the lookup set
2389 // that have a first parameter of type T1 or “reference to
2390 // (possibly cv-qualified) T1”, when T1 is an enumeration
2391 // type, or (if there is a right operand) a second parameter
2392 // of type T2 or “reference to (possibly cv-qualified) T2”,
2393 // when T2 is an enumeration type, are candidate functions.
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002394 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
2395
2396 if (Operators.isAmbiguous())
2397 return DiagnoseAmbiguousLookup(Operators, OpName, OpLoc, OpRange);
2398 else if (Operators) {
2399 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2400 Op != OpEnd; ++Op) {
2401 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
2402 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2403 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2404 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002405 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002406 }
2407
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002408 // Since the set of non-member candidates corresponds to
2409 // *unqualified* lookup of the operator name, we also perform
2410 // argument-dependent lookup (C++ [basic.lookup.argdep]).
2411 AddArgumentDependentLookupCandidates(OpName, Args, NumArgs, CandidateSet);
2412
Douglas Gregor96176b32008-11-18 23:14:02 +00002413 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00002414 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002415
2416 return false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002417}
2418
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002419/// AddBuiltinCandidate - Add a candidate for a built-in
2420/// operator. ResultTy and ParamTys are the result and parameter types
2421/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002422/// arguments being passed to the candidate. IsAssignmentOperator
2423/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002424/// operator. NumContextualBoolArguments is the number of arguments
2425/// (at the beginning of the argument list) that will be contextually
2426/// converted to bool.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002427void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2428 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002429 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002430 bool IsAssignmentOperator,
2431 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002432 // Add this candidate
2433 CandidateSet.push_back(OverloadCandidate());
2434 OverloadCandidate& Candidate = CandidateSet.back();
2435 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002436 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002437 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002438 Candidate.BuiltinTypes.ResultTy = ResultTy;
2439 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2440 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2441
2442 // Determine the implicit conversion sequences for each of the
2443 // arguments.
2444 Candidate.Viable = true;
2445 Candidate.Conversions.resize(NumArgs);
2446 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002447 // C++ [over.match.oper]p4:
2448 // For the built-in assignment operators, conversions of the
2449 // left operand are restricted as follows:
2450 // -- no temporaries are introduced to hold the left operand, and
2451 // -- no user-defined conversions are applied to the left
2452 // operand to achieve a type match with the left-most
2453 // parameter of a built-in candidate.
2454 //
2455 // We block these conversions by turning off user-defined
2456 // conversions, since that is the only way that initialization of
2457 // a reference to a non-class type can occur from something that
2458 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002459 if (ArgIdx < NumContextualBoolArguments) {
2460 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2461 "Contextual conversion to bool requires bool type");
2462 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2463 } else {
2464 Candidate.Conversions[ArgIdx]
2465 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2466 ArgIdx == 0 && IsAssignmentOperator);
2467 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002468 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002469 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002470 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002471 break;
2472 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002473 }
2474}
2475
2476/// BuiltinCandidateTypeSet - A set of types that will be used for the
2477/// candidate operator functions for built-in operators (C++
2478/// [over.built]). The types are separated into pointer types and
2479/// enumeration types.
2480class BuiltinCandidateTypeSet {
2481 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002482 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002483
2484 /// PointerTypes - The set of pointer types that will be used in the
2485 /// built-in candidates.
2486 TypeSet PointerTypes;
2487
2488 /// EnumerationTypes - The set of enumeration types that will be
2489 /// used in the built-in candidates.
2490 TypeSet EnumerationTypes;
2491
2492 /// Context - The AST context in which we will build the type sets.
2493 ASTContext &Context;
2494
2495 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2496
2497public:
2498 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002499 class iterator {
2500 TypeSet::iterator Base;
2501
2502 public:
2503 typedef QualType value_type;
2504 typedef QualType reference;
2505 typedef QualType pointer;
2506 typedef std::ptrdiff_t difference_type;
2507 typedef std::input_iterator_tag iterator_category;
2508
2509 iterator(TypeSet::iterator B) : Base(B) { }
2510
2511 iterator& operator++() {
2512 ++Base;
2513 return *this;
2514 }
2515
2516 iterator operator++(int) {
2517 iterator tmp(*this);
2518 ++(*this);
2519 return tmp;
2520 }
2521
2522 reference operator*() const {
2523 return QualType::getFromOpaquePtr(*Base);
2524 }
2525
2526 pointer operator->() const {
2527 return **this;
2528 }
2529
2530 friend bool operator==(iterator LHS, iterator RHS) {
2531 return LHS.Base == RHS.Base;
2532 }
2533
2534 friend bool operator!=(iterator LHS, iterator RHS) {
2535 return LHS.Base != RHS.Base;
2536 }
2537 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002538
2539 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2540
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002541 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2542 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002543
2544 /// pointer_begin - First pointer type found;
2545 iterator pointer_begin() { return PointerTypes.begin(); }
2546
2547 /// pointer_end - Last pointer type found;
2548 iterator pointer_end() { return PointerTypes.end(); }
2549
2550 /// enumeration_begin - First enumeration type found;
2551 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2552
2553 /// enumeration_end - Last enumeration type found;
2554 iterator enumeration_end() { return EnumerationTypes.end(); }
2555};
2556
2557/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2558/// the set of pointer types along with any more-qualified variants of
2559/// that type. For example, if @p Ty is "int const *", this routine
2560/// will add "int const *", "int const volatile *", "int const
2561/// restrict *", and "int const volatile restrict *" to the set of
2562/// pointer types. Returns true if the add of @p Ty itself succeeded,
2563/// false otherwise.
2564bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2565 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002566 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002567 return false;
2568
2569 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2570 QualType PointeeTy = PointerTy->getPointeeType();
2571 // FIXME: Optimize this so that we don't keep trying to add the same types.
2572
2573 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2574 // with all pointer conversions that don't cast away constness?
2575 if (!PointeeTy.isConstQualified())
2576 AddWithMoreQualifiedTypeVariants
2577 (Context.getPointerType(PointeeTy.withConst()));
2578 if (!PointeeTy.isVolatileQualified())
2579 AddWithMoreQualifiedTypeVariants
2580 (Context.getPointerType(PointeeTy.withVolatile()));
2581 if (!PointeeTy.isRestrictQualified())
2582 AddWithMoreQualifiedTypeVariants
2583 (Context.getPointerType(PointeeTy.withRestrict()));
2584 }
2585
2586 return true;
2587}
2588
2589/// AddTypesConvertedFrom - Add each of the types to which the type @p
2590/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002591/// primarily interested in pointer types and enumeration types.
2592/// AllowUserConversions is true if we should look at the conversion
2593/// functions of a class type, and AllowExplicitConversions if we
2594/// should also include the explicit conversion functions of a class
2595/// type.
2596void
2597BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2598 bool AllowUserConversions,
2599 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002600 // Only deal with canonical types.
2601 Ty = Context.getCanonicalType(Ty);
2602
2603 // Look through reference types; they aren't part of the type of an
2604 // expression for the purposes of conversions.
2605 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2606 Ty = RefTy->getPointeeType();
2607
2608 // We don't care about qualifiers on the type.
2609 Ty = Ty.getUnqualifiedType();
2610
2611 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2612 QualType PointeeTy = PointerTy->getPointeeType();
2613
2614 // Insert our type, and its more-qualified variants, into the set
2615 // of types.
2616 if (!AddWithMoreQualifiedTypeVariants(Ty))
2617 return;
2618
2619 // Add 'cv void*' to our set of types.
2620 if (!Ty->isVoidType()) {
2621 QualType QualVoid
2622 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2623 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2624 }
2625
2626 // If this is a pointer to a class type, add pointers to its bases
2627 // (with the same level of cv-qualification as the original
2628 // derived class, of course).
2629 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2630 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2631 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2632 Base != ClassDecl->bases_end(); ++Base) {
2633 QualType BaseTy = Context.getCanonicalType(Base->getType());
2634 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2635
2636 // Add the pointer type, recursively, so that we get all of
2637 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002638 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002639 }
2640 }
2641 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002642 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002643 } else if (AllowUserConversions) {
2644 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2645 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2646 // FIXME: Visit conversion functions in the base classes, too.
2647 OverloadedFunctionDecl *Conversions
2648 = ClassDecl->getConversionFunctions();
2649 for (OverloadedFunctionDecl::function_iterator Func
2650 = Conversions->function_begin();
2651 Func != Conversions->function_end(); ++Func) {
2652 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002653 if (AllowExplicitConversions || !Conv->isExplicit())
2654 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002655 }
2656 }
2657 }
2658}
2659
Douglas Gregor74253732008-11-19 15:42:04 +00002660/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2661/// operator overloads to the candidate set (C++ [over.built]), based
2662/// on the operator @p Op and the arguments given. For example, if the
2663/// operator is a binary '+', this routine might add "int
2664/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002665void
Douglas Gregor74253732008-11-19 15:42:04 +00002666Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2667 Expr **Args, unsigned NumArgs,
2668 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002669 // The set of "promoted arithmetic types", which are the arithmetic
2670 // types are that preserved by promotion (C++ [over.built]p2). Note
2671 // that the first few of these types are the promoted integral
2672 // types; these types need to be first.
2673 // FIXME: What about complex?
2674 const unsigned FirstIntegralType = 0;
2675 const unsigned LastIntegralType = 13;
2676 const unsigned FirstPromotedIntegralType = 7,
2677 LastPromotedIntegralType = 13;
2678 const unsigned FirstPromotedArithmeticType = 7,
2679 LastPromotedArithmeticType = 16;
2680 const unsigned NumArithmeticTypes = 16;
2681 QualType ArithmeticTypes[NumArithmeticTypes] = {
2682 Context.BoolTy, Context.CharTy, Context.WCharTy,
2683 Context.SignedCharTy, Context.ShortTy,
2684 Context.UnsignedCharTy, Context.UnsignedShortTy,
2685 Context.IntTy, Context.LongTy, Context.LongLongTy,
2686 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2687 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2688 };
2689
2690 // Find all of the types that the arguments can convert to, but only
2691 // if the operator we're looking at has built-in operator candidates
2692 // that make use of these types.
2693 BuiltinCandidateTypeSet CandidateTypes(Context);
2694 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2695 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002696 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002697 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002698 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2699 (Op == OO_Star && NumArgs == 1)) {
2700 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002701 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2702 true,
2703 (Op == OO_Exclaim ||
2704 Op == OO_AmpAmp ||
2705 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002706 }
2707
2708 bool isComparison = false;
2709 switch (Op) {
2710 case OO_None:
2711 case NUM_OVERLOADED_OPERATORS:
2712 assert(false && "Expected an overloaded operator");
2713 break;
2714
Douglas Gregor74253732008-11-19 15:42:04 +00002715 case OO_Star: // '*' is either unary or binary
2716 if (NumArgs == 1)
2717 goto UnaryStar;
2718 else
2719 goto BinaryStar;
2720 break;
2721
2722 case OO_Plus: // '+' is either unary or binary
2723 if (NumArgs == 1)
2724 goto UnaryPlus;
2725 else
2726 goto BinaryPlus;
2727 break;
2728
2729 case OO_Minus: // '-' is either unary or binary
2730 if (NumArgs == 1)
2731 goto UnaryMinus;
2732 else
2733 goto BinaryMinus;
2734 break;
2735
2736 case OO_Amp: // '&' is either unary or binary
2737 if (NumArgs == 1)
2738 goto UnaryAmp;
2739 else
2740 goto BinaryAmp;
2741
2742 case OO_PlusPlus:
2743 case OO_MinusMinus:
2744 // C++ [over.built]p3:
2745 //
2746 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2747 // is either volatile or empty, there exist candidate operator
2748 // functions of the form
2749 //
2750 // VQ T& operator++(VQ T&);
2751 // T operator++(VQ T&, int);
2752 //
2753 // C++ [over.built]p4:
2754 //
2755 // For every pair (T, VQ), where T is an arithmetic type other
2756 // than bool, and VQ is either volatile or empty, there exist
2757 // candidate operator functions of the form
2758 //
2759 // VQ T& operator--(VQ T&);
2760 // T operator--(VQ T&, int);
2761 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2762 Arith < NumArithmeticTypes; ++Arith) {
2763 QualType ArithTy = ArithmeticTypes[Arith];
2764 QualType ParamTypes[2]
2765 = { Context.getReferenceType(ArithTy), Context.IntTy };
2766
2767 // Non-volatile version.
2768 if (NumArgs == 1)
2769 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2770 else
2771 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2772
2773 // Volatile version
2774 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2775 if (NumArgs == 1)
2776 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2777 else
2778 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2779 }
2780
2781 // C++ [over.built]p5:
2782 //
2783 // For every pair (T, VQ), where T is a cv-qualified or
2784 // cv-unqualified object type, and VQ is either volatile or
2785 // empty, there exist candidate operator functions of the form
2786 //
2787 // T*VQ& operator++(T*VQ&);
2788 // T*VQ& operator--(T*VQ&);
2789 // T* operator++(T*VQ&, int);
2790 // T* operator--(T*VQ&, int);
2791 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2792 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2793 // Skip pointer types that aren't pointers to object types.
Douglas Gregorcb7de522008-11-26 23:31:11 +00002794 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002795 continue;
2796
2797 QualType ParamTypes[2] = {
2798 Context.getReferenceType(*Ptr), Context.IntTy
2799 };
2800
2801 // Without volatile
2802 if (NumArgs == 1)
2803 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2804 else
2805 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2806
2807 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2808 // With volatile
2809 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2810 if (NumArgs == 1)
2811 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2812 else
2813 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2814 }
2815 }
2816 break;
2817
2818 UnaryStar:
2819 // C++ [over.built]p6:
2820 // For every cv-qualified or cv-unqualified object type T, there
2821 // exist candidate operator functions of the form
2822 //
2823 // T& operator*(T*);
2824 //
2825 // C++ [over.built]p7:
2826 // For every function type T, there exist candidate operator
2827 // functions of the form
2828 // T& operator*(T*);
2829 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2830 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2831 QualType ParamTy = *Ptr;
2832 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2833 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2834 &ParamTy, Args, 1, CandidateSet);
2835 }
2836 break;
2837
2838 UnaryPlus:
2839 // C++ [over.built]p8:
2840 // For every type T, there exist candidate operator functions of
2841 // the form
2842 //
2843 // T* operator+(T*);
2844 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2845 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2846 QualType ParamTy = *Ptr;
2847 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2848 }
2849
2850 // Fall through
2851
2852 UnaryMinus:
2853 // C++ [over.built]p9:
2854 // For every promoted arithmetic type T, there exist candidate
2855 // operator functions of the form
2856 //
2857 // T operator+(T);
2858 // T operator-(T);
2859 for (unsigned Arith = FirstPromotedArithmeticType;
2860 Arith < LastPromotedArithmeticType; ++Arith) {
2861 QualType ArithTy = ArithmeticTypes[Arith];
2862 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2863 }
2864 break;
2865
2866 case OO_Tilde:
2867 // C++ [over.built]p10:
2868 // For every promoted integral type T, there exist candidate
2869 // operator functions of the form
2870 //
2871 // T operator~(T);
2872 for (unsigned Int = FirstPromotedIntegralType;
2873 Int < LastPromotedIntegralType; ++Int) {
2874 QualType IntTy = ArithmeticTypes[Int];
2875 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2876 }
2877 break;
2878
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002879 case OO_New:
2880 case OO_Delete:
2881 case OO_Array_New:
2882 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002883 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002884 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002885 break;
2886
2887 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002888 UnaryAmp:
2889 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002890 // C++ [over.match.oper]p3:
2891 // -- For the operator ',', the unary operator '&', or the
2892 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002893 break;
2894
2895 case OO_Less:
2896 case OO_Greater:
2897 case OO_LessEqual:
2898 case OO_GreaterEqual:
2899 case OO_EqualEqual:
2900 case OO_ExclaimEqual:
2901 // C++ [over.built]p15:
2902 //
2903 // For every pointer or enumeration type T, there exist
2904 // candidate operator functions of the form
2905 //
2906 // bool operator<(T, T);
2907 // bool operator>(T, T);
2908 // bool operator<=(T, T);
2909 // bool operator>=(T, T);
2910 // bool operator==(T, T);
2911 // bool operator!=(T, T);
2912 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2913 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2914 QualType ParamTypes[2] = { *Ptr, *Ptr };
2915 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2916 }
2917 for (BuiltinCandidateTypeSet::iterator Enum
2918 = CandidateTypes.enumeration_begin();
2919 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2920 QualType ParamTypes[2] = { *Enum, *Enum };
2921 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2922 }
2923
2924 // Fall through.
2925 isComparison = true;
2926
Douglas Gregor74253732008-11-19 15:42:04 +00002927 BinaryPlus:
2928 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002929 if (!isComparison) {
2930 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2931
2932 // C++ [over.built]p13:
2933 //
2934 // For every cv-qualified or cv-unqualified object type T
2935 // there exist candidate operator functions of the form
2936 //
2937 // T* operator+(T*, ptrdiff_t);
2938 // T& operator[](T*, ptrdiff_t); [BELOW]
2939 // T* operator-(T*, ptrdiff_t);
2940 // T* operator+(ptrdiff_t, T*);
2941 // T& operator[](ptrdiff_t, T*); [BELOW]
2942 //
2943 // C++ [over.built]p14:
2944 //
2945 // For every T, where T is a pointer to object type, there
2946 // exist candidate operator functions of the form
2947 //
2948 // ptrdiff_t operator-(T, T);
2949 for (BuiltinCandidateTypeSet::iterator Ptr
2950 = CandidateTypes.pointer_begin();
2951 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2952 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2953
2954 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2955 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2956
2957 if (Op == OO_Plus) {
2958 // T* operator+(ptrdiff_t, T*);
2959 ParamTypes[0] = ParamTypes[1];
2960 ParamTypes[1] = *Ptr;
2961 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2962 } else {
2963 // ptrdiff_t operator-(T, T);
2964 ParamTypes[1] = *Ptr;
2965 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2966 Args, 2, CandidateSet);
2967 }
2968 }
2969 }
2970 // Fall through
2971
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002972 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002973 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002974 // C++ [over.built]p12:
2975 //
2976 // For every pair of promoted arithmetic types L and R, there
2977 // exist candidate operator functions of the form
2978 //
2979 // LR operator*(L, R);
2980 // LR operator/(L, R);
2981 // LR operator+(L, R);
2982 // LR operator-(L, R);
2983 // bool operator<(L, R);
2984 // bool operator>(L, R);
2985 // bool operator<=(L, R);
2986 // bool operator>=(L, R);
2987 // bool operator==(L, R);
2988 // bool operator!=(L, R);
2989 //
2990 // where LR is the result of the usual arithmetic conversions
2991 // between types L and R.
2992 for (unsigned Left = FirstPromotedArithmeticType;
2993 Left < LastPromotedArithmeticType; ++Left) {
2994 for (unsigned Right = FirstPromotedArithmeticType;
2995 Right < LastPromotedArithmeticType; ++Right) {
2996 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2997 QualType Result
2998 = isComparison? Context.BoolTy
2999 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3000 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3001 }
3002 }
3003 break;
3004
3005 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003006 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003007 case OO_Caret:
3008 case OO_Pipe:
3009 case OO_LessLess:
3010 case OO_GreaterGreater:
3011 // C++ [over.built]p17:
3012 //
3013 // For every pair of promoted integral types L and R, there
3014 // exist candidate operator functions of the form
3015 //
3016 // LR operator%(L, R);
3017 // LR operator&(L, R);
3018 // LR operator^(L, R);
3019 // LR operator|(L, R);
3020 // L operator<<(L, R);
3021 // L operator>>(L, R);
3022 //
3023 // where LR is the result of the usual arithmetic conversions
3024 // between types L and R.
3025 for (unsigned Left = FirstPromotedIntegralType;
3026 Left < LastPromotedIntegralType; ++Left) {
3027 for (unsigned Right = FirstPromotedIntegralType;
3028 Right < LastPromotedIntegralType; ++Right) {
3029 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3030 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3031 ? LandR[0]
3032 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3033 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3034 }
3035 }
3036 break;
3037
3038 case OO_Equal:
3039 // C++ [over.built]p20:
3040 //
3041 // For every pair (T, VQ), where T is an enumeration or
3042 // (FIXME:) pointer to member type and VQ is either volatile or
3043 // empty, there exist candidate operator functions of the form
3044 //
3045 // VQ T& operator=(VQ T&, T);
3046 for (BuiltinCandidateTypeSet::iterator Enum
3047 = CandidateTypes.enumeration_begin();
3048 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3049 QualType ParamTypes[2];
3050
3051 // T& operator=(T&, T)
3052 ParamTypes[0] = Context.getReferenceType(*Enum);
3053 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003054 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003055 /*IsAssignmentOperator=*/false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003056
Douglas Gregor74253732008-11-19 15:42:04 +00003057 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3058 // volatile T& operator=(volatile T&, T)
3059 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
3060 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003061 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003062 /*IsAssignmentOperator=*/false);
Douglas Gregor74253732008-11-19 15:42:04 +00003063 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003064 }
3065 // Fall through.
3066
3067 case OO_PlusEqual:
3068 case OO_MinusEqual:
3069 // C++ [over.built]p19:
3070 //
3071 // For every pair (T, VQ), where T is any type and VQ is either
3072 // volatile or empty, there exist candidate operator functions
3073 // of the form
3074 //
3075 // T*VQ& operator=(T*VQ&, T*);
3076 //
3077 // C++ [over.built]p21:
3078 //
3079 // For every pair (T, VQ), where T is a cv-qualified or
3080 // cv-unqualified object type and VQ is either volatile or
3081 // empty, there exist candidate operator functions of the form
3082 //
3083 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3084 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3085 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3086 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3087 QualType ParamTypes[2];
3088 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3089
3090 // non-volatile version
3091 ParamTypes[0] = Context.getReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003092 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3093 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003094
Douglas Gregor74253732008-11-19 15:42:04 +00003095 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3096 // volatile version
3097 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003098 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3099 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003100 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003101 }
3102 // Fall through.
3103
3104 case OO_StarEqual:
3105 case OO_SlashEqual:
3106 // C++ [over.built]p18:
3107 //
3108 // For every triple (L, VQ, R), where L is an arithmetic type,
3109 // VQ is either volatile or empty, and R is a promoted
3110 // arithmetic type, there exist candidate operator functions of
3111 // the form
3112 //
3113 // VQ L& operator=(VQ L&, R);
3114 // VQ L& operator*=(VQ L&, R);
3115 // VQ L& operator/=(VQ L&, R);
3116 // VQ L& operator+=(VQ L&, R);
3117 // VQ L& operator-=(VQ L&, R);
3118 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3119 for (unsigned Right = FirstPromotedArithmeticType;
3120 Right < LastPromotedArithmeticType; ++Right) {
3121 QualType ParamTypes[2];
3122 ParamTypes[1] = ArithmeticTypes[Right];
3123
3124 // Add this built-in operator as a candidate (VQ is empty).
3125 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003126 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3127 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003128
3129 // Add this built-in operator as a candidate (VQ is 'volatile').
3130 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
3131 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003132 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3133 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003134 }
3135 }
3136 break;
3137
3138 case OO_PercentEqual:
3139 case OO_LessLessEqual:
3140 case OO_GreaterGreaterEqual:
3141 case OO_AmpEqual:
3142 case OO_CaretEqual:
3143 case OO_PipeEqual:
3144 // C++ [over.built]p22:
3145 //
3146 // For every triple (L, VQ, R), where L is an integral type, VQ
3147 // is either volatile or empty, and R is a promoted integral
3148 // type, there exist candidate operator functions of the form
3149 //
3150 // VQ L& operator%=(VQ L&, R);
3151 // VQ L& operator<<=(VQ L&, R);
3152 // VQ L& operator>>=(VQ L&, R);
3153 // VQ L& operator&=(VQ L&, R);
3154 // VQ L& operator^=(VQ L&, R);
3155 // VQ L& operator|=(VQ L&, R);
3156 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3157 for (unsigned Right = FirstPromotedIntegralType;
3158 Right < LastPromotedIntegralType; ++Right) {
3159 QualType ParamTypes[2];
3160 ParamTypes[1] = ArithmeticTypes[Right];
3161
3162 // Add this built-in operator as a candidate (VQ is empty).
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003163 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
3164 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3165
3166 // Add this built-in operator as a candidate (VQ is 'volatile').
3167 ParamTypes[0] = ArithmeticTypes[Left];
3168 ParamTypes[0].addVolatile();
3169 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
3170 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3171 }
3172 }
3173 break;
3174
Douglas Gregor74253732008-11-19 15:42:04 +00003175 case OO_Exclaim: {
3176 // C++ [over.operator]p23:
3177 //
3178 // There also exist candidate operator functions of the form
3179 //
3180 // bool operator!(bool);
3181 // bool operator&&(bool, bool); [BELOW]
3182 // bool operator||(bool, bool); [BELOW]
3183 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003184 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3185 /*IsAssignmentOperator=*/false,
3186 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003187 break;
3188 }
3189
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003190 case OO_AmpAmp:
3191 case OO_PipePipe: {
3192 // C++ [over.operator]p23:
3193 //
3194 // There also exist candidate operator functions of the form
3195 //
Douglas Gregor74253732008-11-19 15:42:04 +00003196 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003197 // bool operator&&(bool, bool);
3198 // bool operator||(bool, bool);
3199 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003200 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3201 /*IsAssignmentOperator=*/false,
3202 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003203 break;
3204 }
3205
3206 case OO_Subscript:
3207 // C++ [over.built]p13:
3208 //
3209 // For every cv-qualified or cv-unqualified object type T there
3210 // exist candidate operator functions of the form
3211 //
3212 // T* operator+(T*, ptrdiff_t); [ABOVE]
3213 // T& operator[](T*, ptrdiff_t);
3214 // T* operator-(T*, ptrdiff_t); [ABOVE]
3215 // T* operator+(ptrdiff_t, T*); [ABOVE]
3216 // T& operator[](ptrdiff_t, T*);
3217 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3218 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3219 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3220 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
3221 QualType ResultTy = Context.getReferenceType(PointeeType);
3222
3223 // T& operator[](T*, ptrdiff_t)
3224 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3225
3226 // T& operator[](ptrdiff_t, T*);
3227 ParamTypes[0] = ParamTypes[1];
3228 ParamTypes[1] = *Ptr;
3229 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3230 }
3231 break;
3232
3233 case OO_ArrowStar:
3234 // FIXME: No support for pointer-to-members yet.
3235 break;
3236 }
3237}
3238
Douglas Gregorfa047642009-02-04 00:32:51 +00003239/// \brief Add function candidates found via argument-dependent lookup
3240/// to the set of overloading candidates.
3241///
3242/// This routine performs argument-dependent name lookup based on the
3243/// given function name (which may also be an operator name) and adds
3244/// all of the overload candidates found by ADL to the overload
3245/// candidate set (C++ [basic.lookup.argdep]).
3246void
3247Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3248 Expr **Args, unsigned NumArgs,
3249 OverloadCandidateSet& CandidateSet) {
3250 // Find all of the associated namespaces and classes based on the
3251 // arguments we have.
3252 AssociatedNamespaceSet AssociatedNamespaces;
3253 AssociatedClassSet AssociatedClasses;
3254 FindAssociatedClassesAndNamespaces(Args, NumArgs,
3255 AssociatedNamespaces, AssociatedClasses);
3256
3257 // C++ [basic.lookup.argdep]p3:
3258 //
3259 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3260 // and let Y be the lookup set produced by argument dependent
3261 // lookup (defined as follows). If X contains [...] then Y is
3262 // empty. Otherwise Y is the set of declarations found in the
3263 // namespaces associated with the argument types as described
3264 // below. The set of declarations found by the lookup of the name
3265 // is the union of X and Y.
3266 //
3267 // Here, we compute Y and add its members to the overloaded
3268 // candidate set.
3269 llvm::SmallPtrSet<FunctionDecl *, 16> KnownCandidates;
3270 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
3271 NSEnd = AssociatedNamespaces.end();
3272 NS != NSEnd; ++NS) {
3273 // When considering an associated namespace, the lookup is the
3274 // same as the lookup performed when the associated namespace is
3275 // used as a qualifier (3.4.3.2) except that:
3276 //
3277 // -- Any using-directives in the associated namespace are
3278 // ignored.
3279 //
3280 // -- FIXME: Any namespace-scope friend functions declared in
3281 // associated classes are visible within their respective
3282 // namespaces even if they are not visible during an ordinary
3283 // lookup (11.4).
3284 DeclContext::lookup_iterator I, E;
3285 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
3286 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
3287 if (!Func)
3288 break;
3289
3290 if (KnownCandidates.empty()) {
3291 // Record all of the function candidates that we've already
3292 // added to the overload set, so that we don't add those same
3293 // candidates a second time.
3294 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3295 CandEnd = CandidateSet.end();
3296 Cand != CandEnd; ++Cand)
3297 KnownCandidates.insert(Cand->Function);
3298 }
3299
3300 // If we haven't seen this function before, add it as a
3301 // candidate.
3302 if (KnownCandidates.insert(Func))
3303 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3304 }
3305 }
3306}
3307
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003308/// isBetterOverloadCandidate - Determines whether the first overload
3309/// candidate is a better candidate than the second (C++ 13.3.3p1).
3310bool
3311Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3312 const OverloadCandidate& Cand2)
3313{
3314 // Define viable functions to be better candidates than non-viable
3315 // functions.
3316 if (!Cand2.Viable)
3317 return Cand1.Viable;
3318 else if (!Cand1.Viable)
3319 return false;
3320
Douglas Gregor88a35142008-12-22 05:46:06 +00003321 // C++ [over.match.best]p1:
3322 //
3323 // -- if F is a static member function, ICS1(F) is defined such
3324 // that ICS1(F) is neither better nor worse than ICS1(G) for
3325 // any function G, and, symmetrically, ICS1(G) is neither
3326 // better nor worse than ICS1(F).
3327 unsigned StartArg = 0;
3328 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3329 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003330
3331 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3332 // function than another viable function F2 if for all arguments i,
3333 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3334 // then...
3335 unsigned NumArgs = Cand1.Conversions.size();
3336 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3337 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003338 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003339 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3340 Cand2.Conversions[ArgIdx])) {
3341 case ImplicitConversionSequence::Better:
3342 // Cand1 has a better conversion sequence.
3343 HasBetterConversion = true;
3344 break;
3345
3346 case ImplicitConversionSequence::Worse:
3347 // Cand1 can't be better than Cand2.
3348 return false;
3349
3350 case ImplicitConversionSequence::Indistinguishable:
3351 // Do nothing.
3352 break;
3353 }
3354 }
3355
3356 if (HasBetterConversion)
3357 return true;
3358
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003359 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3360 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003361
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003362 // C++ [over.match.best]p1b4:
3363 //
3364 // -- the context is an initialization by user-defined conversion
3365 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3366 // from the return type of F1 to the destination type (i.e.,
3367 // the type of the entity being initialized) is a better
3368 // conversion sequence than the standard conversion sequence
3369 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003370 if (Cand1.Function && Cand2.Function &&
3371 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003372 isa<CXXConversionDecl>(Cand2.Function)) {
3373 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3374 Cand2.FinalConversion)) {
3375 case ImplicitConversionSequence::Better:
3376 // Cand1 has a better conversion sequence.
3377 return true;
3378
3379 case ImplicitConversionSequence::Worse:
3380 // Cand1 can't be better than Cand2.
3381 return false;
3382
3383 case ImplicitConversionSequence::Indistinguishable:
3384 // Do nothing
3385 break;
3386 }
3387 }
3388
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003389 return false;
3390}
3391
3392/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3393/// within an overload candidate set. If overloading is successful,
3394/// the result will be OR_Success and Best will be set to point to the
3395/// best viable function within the candidate set. Otherwise, one of
3396/// several kinds of errors will be returned; see
3397/// Sema::OverloadingResult.
3398Sema::OverloadingResult
3399Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3400 OverloadCandidateSet::iterator& Best)
3401{
3402 // Find the best viable function.
3403 Best = CandidateSet.end();
3404 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3405 Cand != CandidateSet.end(); ++Cand) {
3406 if (Cand->Viable) {
3407 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3408 Best = Cand;
3409 }
3410 }
3411
3412 // If we didn't find any viable functions, abort.
3413 if (Best == CandidateSet.end())
3414 return OR_No_Viable_Function;
3415
3416 // Make sure that this function is better than every other viable
3417 // function. If not, we have an ambiguity.
3418 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3419 Cand != CandidateSet.end(); ++Cand) {
3420 if (Cand->Viable &&
3421 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003422 !isBetterOverloadCandidate(*Best, *Cand)) {
3423 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003424 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003425 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003426 }
3427
3428 // Best is the best viable function.
3429 return OR_Success;
3430}
3431
3432/// PrintOverloadCandidates - When overload resolution fails, prints
3433/// diagnostic messages containing the candidates in the candidate
3434/// set. If OnlyViable is true, only viable candidates will be printed.
3435void
3436Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3437 bool OnlyViable)
3438{
3439 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3440 LastCand = CandidateSet.end();
3441 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003442 if (Cand->Viable || !OnlyViable) {
3443 if (Cand->Function) {
3444 // Normal function
3445 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003446 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003447 // Desugar the type of the surrogate down to a function type,
3448 // retaining as many typedefs as possible while still showing
3449 // the function type (and, therefore, its parameter types).
3450 QualType FnType = Cand->Surrogate->getConversionType();
3451 bool isReference = false;
3452 bool isPointer = false;
3453 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
3454 FnType = FnTypeRef->getPointeeType();
3455 isReference = true;
3456 }
3457 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3458 FnType = FnTypePtr->getPointeeType();
3459 isPointer = true;
3460 }
3461 // Desugar down to a function type.
3462 FnType = QualType(FnType->getAsFunctionType(), 0);
3463 // Reconstruct the pointer/reference as appropriate.
3464 if (isPointer) FnType = Context.getPointerType(FnType);
3465 if (isReference) FnType = Context.getReferenceType(FnType);
3466
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003467 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003468 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003469 } else {
3470 // FIXME: We need to get the identifier in here
3471 // FIXME: Do we want the error message to point at the
3472 // operator? (built-ins won't have a location)
3473 QualType FnType
3474 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3475 Cand->BuiltinTypes.ParamTypes,
3476 Cand->Conversions.size(),
3477 false, 0);
3478
Chris Lattnerd1625842008-11-24 06:25:27 +00003479 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003480 }
3481 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003482 }
3483}
3484
Douglas Gregor904eed32008-11-10 20:40:00 +00003485/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3486/// an overloaded function (C++ [over.over]), where @p From is an
3487/// expression with overloaded function type and @p ToType is the type
3488/// we're trying to resolve to. For example:
3489///
3490/// @code
3491/// int f(double);
3492/// int f(int);
3493///
3494/// int (*pfd)(double) = f; // selects f(double)
3495/// @endcode
3496///
3497/// This routine returns the resulting FunctionDecl if it could be
3498/// resolved, and NULL otherwise. When @p Complain is true, this
3499/// routine will emit diagnostics if there is an error.
3500FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00003501Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003502 bool Complain) {
3503 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003504 bool IsMember = false;
Douglas Gregor904eed32008-11-10 20:40:00 +00003505 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3506 FunctionType = ToTypePtr->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00003507 else if (const MemberPointerType *MemTypePtr =
3508 ToType->getAsMemberPointerType()) {
3509 FunctionType = MemTypePtr->getPointeeType();
3510 IsMember = true;
3511 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003512
3513 // We only look at pointers or references to functions.
3514 if (!FunctionType->isFunctionType())
3515 return 0;
3516
3517 // Find the actual overloaded function declaration.
3518 OverloadedFunctionDecl *Ovl = 0;
3519
3520 // C++ [over.over]p1:
3521 // [...] [Note: any redundant set of parentheses surrounding the
3522 // overloaded function name is ignored (5.1). ]
3523 Expr *OvlExpr = From->IgnoreParens();
3524
3525 // C++ [over.over]p1:
3526 // [...] The overloaded function name can be preceded by the &
3527 // operator.
3528 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3529 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3530 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3531 }
3532
3533 // Try to dig out the overloaded function.
3534 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3535 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3536
3537 // If there's no overloaded function declaration, we're done.
3538 if (!Ovl)
3539 return 0;
3540
3541 // Look through all of the overloaded functions, searching for one
3542 // whose type matches exactly.
3543 // FIXME: When templates or using declarations come along, we'll actually
3544 // have to deal with duplicates, partial ordering, etc. For now, we
3545 // can just do a simple search.
3546 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3547 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3548 Fun != Ovl->function_end(); ++Fun) {
3549 // C++ [over.over]p3:
3550 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00003551 // targets of type "pointer-to-function" or "reference-to-function."
3552 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00003553 // type "pointer-to-member-function."
3554 // Note that according to DR 247, the containing class does not matter.
3555 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3556 // Skip non-static functions when converting to pointer, and static
3557 // when converting to member pointer.
3558 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00003559 continue;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003560 } else if (IsMember)
3561 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00003562
3563 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3564 return *Fun;
3565 }
3566
3567 return 0;
3568}
3569
Douglas Gregorf6b89692008-11-26 05:54:23 +00003570/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00003571/// (which eventually refers to the declaration Func) and the call
3572/// arguments Args/NumArgs, attempt to resolve the function call down
3573/// to a specific function. If overload resolution succeeds, returns
3574/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00003575/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003576/// arguments and Fn, and returns NULL.
Douglas Gregorfa047642009-02-04 00:32:51 +00003577FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor17330012009-02-04 15:01:18 +00003578 DeclarationName UnqualifiedName,
Douglas Gregor0a396682008-11-26 06:01:48 +00003579 SourceLocation LParenLoc,
3580 Expr **Args, unsigned NumArgs,
3581 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003582 SourceLocation RParenLoc,
Douglas Gregor17330012009-02-04 15:01:18 +00003583 bool &ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003584 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00003585
3586 // Add the functions denoted by Callee to the set of candidate
3587 // functions. While we're doing so, track whether argument-dependent
3588 // lookup still applies, per:
3589 //
3590 // C++0x [basic.lookup.argdep]p3:
3591 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3592 // and let Y be the lookup set produced by argument dependent
3593 // lookup (defined as follows). If X contains
3594 //
3595 // -- a declaration of a class member, or
3596 //
3597 // -- a block-scope function declaration that is not a
3598 // using-declaration, or
3599 //
3600 // -- a declaration that is neither a function or a function
3601 // template
3602 //
3603 // then Y is empty.
Douglas Gregorfa047642009-02-04 00:32:51 +00003604 if (OverloadedFunctionDecl *Ovl
Douglas Gregor17330012009-02-04 15:01:18 +00003605 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3606 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3607 FuncEnd = Ovl->function_end();
3608 Func != FuncEnd; ++Func) {
3609 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3610
3611 if ((*Func)->getDeclContext()->isRecord() ||
3612 (*Func)->getDeclContext()->isFunctionOrMethod())
3613 ArgumentDependentLookup = false;
3614 }
3615 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3616 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3617
3618 if (Func->getDeclContext()->isRecord() ||
3619 Func->getDeclContext()->isFunctionOrMethod())
3620 ArgumentDependentLookup = false;
3621 }
3622
3623 if (Callee)
3624 UnqualifiedName = Callee->getDeclName();
3625
Douglas Gregorfa047642009-02-04 00:32:51 +00003626 if (ArgumentDependentLookup)
Douglas Gregor17330012009-02-04 15:01:18 +00003627 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003628 CandidateSet);
3629
Douglas Gregorf6b89692008-11-26 05:54:23 +00003630 OverloadCandidateSet::iterator Best;
3631 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003632 case OR_Success:
3633 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003634
3635 case OR_No_Viable_Function:
3636 Diag(Fn->getSourceRange().getBegin(),
3637 diag::err_ovl_no_viable_function_in_call)
Douglas Gregor17330012009-02-04 15:01:18 +00003638 << UnqualifiedName << (unsigned)CandidateSet.size()
Douglas Gregorf6b89692008-11-26 05:54:23 +00003639 << Fn->getSourceRange();
3640 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3641 break;
3642
3643 case OR_Ambiguous:
3644 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00003645 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00003646 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3647 break;
3648 }
3649
3650 // Overload resolution failed. Destroy all of the subexpressions and
3651 // return NULL.
3652 Fn->Destroy(Context);
3653 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3654 Args[Arg]->Destroy(Context);
3655 return 0;
3656}
3657
Douglas Gregor88a35142008-12-22 05:46:06 +00003658/// BuildCallToMemberFunction - Build a call to a member
3659/// function. MemExpr is the expression that refers to the member
3660/// function (and includes the object parameter), Args/NumArgs are the
3661/// arguments to the function call (not including the object
3662/// parameter). The caller needs to validate that the member
3663/// expression refers to a member function or an overloaded member
3664/// function.
3665Sema::ExprResult
3666Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3667 SourceLocation LParenLoc, Expr **Args,
3668 unsigned NumArgs, SourceLocation *CommaLocs,
3669 SourceLocation RParenLoc) {
3670 // Dig out the member expression. This holds both the object
3671 // argument and the member function we're referring to.
3672 MemberExpr *MemExpr = 0;
3673 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3674 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3675 else
3676 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3677 assert(MemExpr && "Building member call without member expression");
3678
3679 // Extract the object argument.
3680 Expr *ObjectArg = MemExpr->getBase();
3681 if (MemExpr->isArrow())
Ted Kremenek8189cde2009-02-07 01:47:29 +00003682 ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref,
3683 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
3684 SourceLocation());
Douglas Gregor88a35142008-12-22 05:46:06 +00003685 CXXMethodDecl *Method = 0;
3686 if (OverloadedFunctionDecl *Ovl
3687 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3688 // Add overload candidates
3689 OverloadCandidateSet CandidateSet;
3690 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3691 FuncEnd = Ovl->function_end();
3692 Func != FuncEnd; ++Func) {
3693 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3694 Method = cast<CXXMethodDecl>(*Func);
3695 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3696 /*SuppressUserConversions=*/false);
3697 }
3698
3699 OverloadCandidateSet::iterator Best;
3700 switch (BestViableFunction(CandidateSet, Best)) {
3701 case OR_Success:
3702 Method = cast<CXXMethodDecl>(Best->Function);
3703 break;
3704
3705 case OR_No_Viable_Function:
3706 Diag(MemExpr->getSourceRange().getBegin(),
3707 diag::err_ovl_no_viable_member_function_in_call)
3708 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3709 << MemExprE->getSourceRange();
3710 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3711 // FIXME: Leaking incoming expressions!
3712 return true;
3713
3714 case OR_Ambiguous:
3715 Diag(MemExpr->getSourceRange().getBegin(),
3716 diag::err_ovl_ambiguous_member_call)
3717 << Ovl->getDeclName() << MemExprE->getSourceRange();
3718 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3719 // FIXME: Leaking incoming expressions!
3720 return true;
3721 }
3722
3723 FixOverloadedFunctionReference(MemExpr, Method);
3724 } else {
3725 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3726 }
3727
3728 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek8189cde2009-02-07 01:47:29 +00003729 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00003730 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
3731 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003732 Method->getResultType().getNonReferenceType(),
3733 RParenLoc));
3734
3735 // Convert the object argument (for a non-static member function call).
3736 if (!Method->isStatic() &&
3737 PerformObjectArgumentInitialization(ObjectArg, Method))
3738 return true;
3739 MemExpr->setBase(ObjectArg);
3740
3741 // Convert the rest of the arguments
3742 const FunctionTypeProto *Proto = cast<FunctionTypeProto>(Method->getType());
3743 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
3744 RParenLoc))
3745 return true;
3746
Sebastian Redl0eb23302009-01-19 00:08:26 +00003747 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00003748}
3749
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003750/// BuildCallToObjectOfClassType - Build a call to an object of class
3751/// type (C++ [over.call.object]), which can end up invoking an
3752/// overloaded function call operator (@c operator()) or performing a
3753/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00003754Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00003755Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3756 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003757 Expr **Args, unsigned NumArgs,
3758 SourceLocation *CommaLocs,
3759 SourceLocation RParenLoc) {
3760 assert(Object->getType()->isRecordType() && "Requires object type argument");
3761 const RecordType *Record = Object->getType()->getAsRecordType();
3762
3763 // C++ [over.call.object]p1:
3764 // If the primary-expression E in the function call syntax
3765 // evaluates to a class object of type “cv T”, then the set of
3766 // candidate functions includes at least the function call
3767 // operators of T. The function call operators of T are obtained by
3768 // ordinary lookup of the name operator() in the context of
3769 // (E).operator().
3770 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00003771 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003772 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00003773 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003774 Oper != OperEnd; ++Oper)
3775 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
3776 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003777
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003778 // C++ [over.call.object]p2:
3779 // In addition, for each conversion function declared in T of the
3780 // form
3781 //
3782 // operator conversion-type-id () cv-qualifier;
3783 //
3784 // where cv-qualifier is the same cv-qualification as, or a
3785 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003786 // denotes the type "pointer to function of (P1,...,Pn) returning
3787 // R", or the type "reference to pointer to function of
3788 // (P1,...,Pn) returning R", or the type "reference to function
3789 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003790 // is also considered as a candidate function. Similarly,
3791 // surrogate call functions are added to the set of candidate
3792 // functions for each conversion function declared in an
3793 // accessible base class provided the function is not hidden
3794 // within T by another intervening declaration.
3795 //
3796 // FIXME: Look in base classes for more conversion operators!
3797 OverloadedFunctionDecl *Conversions
3798 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003799 for (OverloadedFunctionDecl::function_iterator
3800 Func = Conversions->function_begin(),
3801 FuncEnd = Conversions->function_end();
3802 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003803 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3804
3805 // Strip the reference type (if any) and then the pointer type (if
3806 // any) to get down to what might be a function type.
3807 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3808 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3809 ConvType = ConvPtrType->getPointeeType();
3810
3811 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3812 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3813 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003814
3815 // Perform overload resolution.
3816 OverloadCandidateSet::iterator Best;
3817 switch (BestViableFunction(CandidateSet, Best)) {
3818 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003819 // Overload resolution succeeded; we'll build the appropriate call
3820 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003821 break;
3822
3823 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003824 Diag(Object->getSourceRange().getBegin(),
3825 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003826 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003827 << Object->getSourceRange();
3828 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003829 break;
3830
3831 case OR_Ambiguous:
3832 Diag(Object->getSourceRange().getBegin(),
3833 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003834 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003835 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3836 break;
3837 }
3838
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003839 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003840 // We had an error; delete all of the subexpressions and return
3841 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003842 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003843 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00003844 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003845 return true;
3846 }
3847
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003848 if (Best->Function == 0) {
3849 // Since there is no function declaration, this is one of the
3850 // surrogate candidates. Dig out the conversion function.
3851 CXXConversionDecl *Conv
3852 = cast<CXXConversionDecl>(
3853 Best->Conversions[0].UserDefined.ConversionFunction);
3854
3855 // We selected one of the surrogate functions that converts the
3856 // object parameter to a function pointer. Perform the conversion
3857 // on the object argument, then let ActOnCallExpr finish the job.
3858 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00003859 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003860 Conv->getConversionType().getNonReferenceType(),
3861 Conv->getConversionType()->isReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003862 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
3863 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
3864 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003865 }
3866
3867 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3868 // that calls this method, using Object for the implicit object
3869 // parameter and passing along the remaining arguments.
3870 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003871 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3872
3873 unsigned NumArgsInProto = Proto->getNumArgs();
3874 unsigned NumArgsToCheck = NumArgs;
3875
3876 // Build the full argument list for the method call (the
3877 // implicit object parameter is placed at the beginning of the
3878 // list).
3879 Expr **MethodArgs;
3880 if (NumArgs < NumArgsInProto) {
3881 NumArgsToCheck = NumArgsInProto;
3882 MethodArgs = new Expr*[NumArgsInProto + 1];
3883 } else {
3884 MethodArgs = new Expr*[NumArgs + 1];
3885 }
3886 MethodArgs[0] = Object;
3887 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3888 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3889
Ted Kremenek8189cde2009-02-07 01:47:29 +00003890 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
3891 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003892 UsualUnaryConversions(NewFn);
3893
3894 // Once we've built TheCall, all of the expressions are properly
3895 // owned.
3896 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003897 ExprOwningPtr<CXXOperatorCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00003898 TheCall(this, new (Context) CXXOperatorCallExpr(Context, NewFn, MethodArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +00003899 NumArgs + 1,
3900 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003901 delete [] MethodArgs;
3902
Douglas Gregor518fda12009-01-13 05:10:00 +00003903 // We may have default arguments. If so, we need to allocate more
3904 // slots in the call for them.
3905 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00003906 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00003907 else if (NumArgs > NumArgsInProto)
3908 NumArgsToCheck = NumArgsInProto;
3909
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003910 // Initialize the implicit object parameter.
Douglas Gregor518fda12009-01-13 05:10:00 +00003911 if (PerformObjectArgumentInitialization(Object, Method))
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003912 return true;
3913 TheCall->setArg(0, Object);
3914
3915 // Check the argument types.
3916 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003917 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00003918 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003919 Arg = Args[i];
Douglas Gregor518fda12009-01-13 05:10:00 +00003920
3921 // Pass the argument.
3922 QualType ProtoArgType = Proto->getArgType(i);
3923 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3924 return true;
3925 } else {
Ted Kremenek8189cde2009-02-07 01:47:29 +00003926 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00003927 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003928
3929 TheCall->setArg(i + 1, Arg);
3930 }
3931
3932 // If this is a variadic call, handle args passed through "...".
3933 if (Proto->isVariadic()) {
3934 // Promote the arguments (C99 6.5.2.2p7).
3935 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3936 Expr *Arg = Args[i];
Anders Carlsson906fed02009-01-13 05:48:52 +00003937
Anders Carlssondce5e2c2009-01-16 16:48:51 +00003938 DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003939 TheCall->setArg(i + 1, Arg);
3940 }
3941 }
3942
Sebastian Redl0eb23302009-01-19 00:08:26 +00003943 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003944}
3945
Douglas Gregor8ba10742008-11-20 16:27:02 +00003946/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3947/// (if one exists), where @c Base is an expression of class type and
3948/// @c Member is the name of the member we're trying to find.
3949Action::ExprResult
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003950Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003951 SourceLocation MemberLoc,
3952 IdentifierInfo &Member) {
3953 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3954
3955 // C++ [over.ref]p1:
3956 //
3957 // [...] An expression x->m is interpreted as (x.operator->())->m
3958 // for a class object x of type T if T::operator->() exists and if
3959 // the operator is selected as the best match function by the
3960 // overload resolution mechanism (13.3).
3961 // FIXME: look in base classes.
3962 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3963 OverloadCandidateSet CandidateSet;
3964 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003965
3966 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00003967 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003968 Oper != OperEnd; ++Oper)
3969 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003970 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003971
Ted Kremenek8189cde2009-02-07 01:47:29 +00003972 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003973
Douglas Gregor8ba10742008-11-20 16:27:02 +00003974 // Perform overload resolution.
3975 OverloadCandidateSet::iterator Best;
3976 switch (BestViableFunction(CandidateSet, Best)) {
3977 case OR_Success:
3978 // Overload resolution succeeded; we'll build the call below.
3979 break;
3980
3981 case OR_No_Viable_Function:
3982 if (CandidateSet.empty())
3983 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003984 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003985 else
3986 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003987 << "operator->" << (unsigned)CandidateSet.size()
3988 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003989 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003990 return true;
3991
3992 case OR_Ambiguous:
3993 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003994 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003995 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003996 return true;
3997 }
3998
3999 // Convert the object parameter.
4000 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004001 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00004002 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004003
4004 // No concerns about early exits now.
4005 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004006
4007 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004008 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4009 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004010 UsualUnaryConversions(FnExpr);
Ted Kremenek668bf912009-02-09 20:51:47 +00004011 Base = new (Context) CXXOperatorCallExpr(Context, FnExpr, &Base, 1,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004012 Method->getResultType().getNonReferenceType(),
4013 OpLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004014 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
4015 MemberLoc, Member).release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004016}
4017
Douglas Gregor904eed32008-11-10 20:40:00 +00004018/// FixOverloadedFunctionReference - E is an expression that refers to
4019/// a C++ overloaded function (possibly with some parentheses and
4020/// perhaps a '&' around it). We have resolved the overloaded function
4021/// to the function declaration Fn, so patch up the expression E to
4022/// refer (possibly indirectly) to Fn.
4023void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4024 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4025 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4026 E->setType(PE->getSubExpr()->getType());
4027 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4028 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4029 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00004030 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4031 if (Method->isStatic()) {
4032 // Do nothing: static member functions aren't any different
4033 // from non-member functions.
4034 }
4035 else if (QualifiedDeclRefExpr *DRE
4036 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4037 // We have taken the address of a pointer to member
4038 // function. Perform the computation here so that we get the
4039 // appropriate pointer to member type.
4040 DRE->setDecl(Fn);
4041 DRE->setType(Fn->getType());
4042 QualType ClassType
4043 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4044 E->setType(Context.getMemberPointerType(Fn->getType(),
4045 ClassType.getTypePtr()));
4046 return;
4047 }
4048 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004049 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00004050 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor904eed32008-11-10 20:40:00 +00004051 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4052 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4053 "Expected overloaded function");
4054 DR->setDecl(Fn);
4055 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004056 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4057 MemExpr->setMemberDecl(Fn);
4058 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00004059 } else {
4060 assert(false && "Invalid reference to overloaded function");
4061 }
4062}
4063
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004064} // end namespace clang