blob: 673da1dd026edd8f9f03b0fec4232bd43fbf64de [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.
Douglas Gregor72564e72009-02-26 23:50:07 +0000313 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
314 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000315 return false;
316
Douglas Gregor72564e72009-02-26 23:50:07 +0000317 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType.getTypePtr());
318 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType.getTypePtr());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000319
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() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000471 Context.getCanonicalType(FromType) != Context.OverloadTy) {
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();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000522 if (ToType->isLValueReferenceType())
523 FromType = Context.getLValueReferenceType(FromType);
524 else if (ToType->isRValueReferenceType())
525 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000526 else if (ToType->isMemberPointerType()) {
527 // Resolve address only succeeds if both sides are member pointers,
528 // but it doesn't have to be the same class. See DR 247.
529 // Note that this means that the type of &Derived::fn can be
530 // Ret (Base::*)(Args) if the fn overload actually found is from the
531 // base class, even if it was brought into the derived class via a
532 // using declaration. The standard isn't clear on this issue at all.
533 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
534 FromType = Context.getMemberPointerType(FromType,
535 Context.getTypeDeclType(M->getParent()).getTypePtr());
536 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000537 FromType = Context.getPointerType(FromType);
538 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000539 // We don't require any conversions for the first step.
540 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000541 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000542 }
543
544 // The second conversion can be an integral promotion, floating
545 // point promotion, integral conversion, floating point conversion,
546 // floating-integral conversion, pointer conversion,
547 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000548 // For overloading in C, this can also be a "compatible-type"
549 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000550 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000551 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000552 // The unqualified versions of the types are the same: there's no
553 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000554 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000555 }
556 // Integral promotion (C++ 4.5).
557 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000558 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000559 FromType = ToType.getUnqualifiedType();
560 }
561 // Floating point promotion (C++ 4.6).
562 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000563 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000564 FromType = ToType.getUnqualifiedType();
565 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000566 // Complex promotion (Clang extension)
567 else if (IsComplexPromotion(FromType, ToType)) {
568 SCS.Second = ICK_Complex_Promotion;
569 FromType = ToType.getUnqualifiedType();
570 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000571 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000572 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000573 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000574 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000575 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000576 FromType = ToType.getUnqualifiedType();
577 }
578 // Floating point conversions (C++ 4.8).
579 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000580 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000581 FromType = ToType.getUnqualifiedType();
582 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000583 // Complex conversions (C99 6.3.1.6)
584 else if (FromType->isComplexType() && ToType->isComplexType()) {
585 SCS.Second = ICK_Complex_Conversion;
586 FromType = ToType.getUnqualifiedType();
587 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000588 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000589 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000590 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000591 ToType->isIntegralType() && !ToType->isBooleanType() &&
592 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000593 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
594 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000595 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000596 FromType = ToType.getUnqualifiedType();
597 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000598 // Complex-real conversions (C99 6.3.1.7)
599 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
600 (ToType->isComplexType() && FromType->isArithmeticType())) {
601 SCS.Second = ICK_Complex_Real;
602 FromType = ToType.getUnqualifiedType();
603 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000605 else if (IsPointerConversion(From, FromType, ToType, FromType,
606 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000607 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000608 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000609 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000610 // Pointer to member conversions (4.11).
611 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
612 SCS.Second = ICK_Pointer_Member;
613 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000614 // Boolean conversions (C++ 4.12).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000615 else if (ToType->isBooleanType() &&
616 (FromType->isArithmeticType() ||
617 FromType->isEnumeralType() ||
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000618 FromType->isPointerType() ||
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000619 FromType->isBlockPointerType() ||
620 FromType->isMemberPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000621 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000622 FromType = Context.BoolTy;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000623 }
624 // Compatible conversions (Clang extension for C function overloading)
625 else if (!getLangOptions().CPlusPlus &&
626 Context.typesAreCompatible(ToType, FromType)) {
627 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000628 } else {
629 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000630 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000631 }
632
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000633 QualType CanonFrom;
634 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000635 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000636 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000637 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000638 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000639 CanonFrom = Context.getCanonicalType(FromType);
640 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000641 } else {
642 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000643 SCS.Third = ICK_Identity;
644
645 // C++ [over.best.ics]p6:
646 // [...] Any difference in top-level cv-qualification is
647 // subsumed by the initialization itself and does not constitute
648 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000649 CanonFrom = Context.getCanonicalType(FromType);
650 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000651 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000652 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
653 FromType = ToType;
654 CanonFrom = CanonTo;
655 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000656 }
657
658 // If we have not converted the argument type to the parameter type,
659 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000660 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000661 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000662
Douglas Gregor60d62c22008-10-31 16:23:19 +0000663 SCS.ToTypePtr = FromType.getAsOpaquePtr();
664 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000665}
666
667/// IsIntegralPromotion - Determines whether the conversion from the
668/// expression From (whose potentially-adjusted type is FromType) to
669/// ToType is an integral promotion (C++ 4.5). If so, returns true and
670/// sets PromotedType to the promoted type.
671bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
672{
673 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000674 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000675 if (!To) {
676 return false;
677 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000678
679 // An rvalue of type char, signed char, unsigned char, short int, or
680 // unsigned short int can be converted to an rvalue of type int if
681 // int can represent all the values of the source type; otherwise,
682 // the source rvalue can be converted to an rvalue of type unsigned
683 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000684 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000685 if (// We can promote any signed, promotable integer type to an int
686 (FromType->isSignedIntegerType() ||
687 // We can promote any unsigned integer type whose size is
688 // less than int to an int.
689 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000690 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000691 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000692 }
693
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000694 return To->getKind() == BuiltinType::UInt;
695 }
696
697 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
698 // can be converted to an rvalue of the first of the following types
699 // that can represent all the values of its underlying type: int,
700 // unsigned int, long, or unsigned long (C++ 4.5p2).
701 if ((FromType->isEnumeralType() || FromType->isWideCharType())
702 && ToType->isIntegerType()) {
703 // Determine whether the type we're converting from is signed or
704 // unsigned.
705 bool FromIsSigned;
706 uint64_t FromSize = Context.getTypeSize(FromType);
707 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
708 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
709 FromIsSigned = UnderlyingType->isSignedIntegerType();
710 } else {
711 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
712 FromIsSigned = true;
713 }
714
715 // The types we'll try to promote to, in the appropriate
716 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000717 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000718 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000719 Context.LongTy, Context.UnsignedLongTy ,
720 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000721 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000722 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000723 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
724 if (FromSize < ToSize ||
725 (FromSize == ToSize &&
726 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
727 // We found the type that we can promote to. If this is the
728 // type we wanted, we have a promotion. Otherwise, no
729 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000730 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000731 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
732 }
733 }
734 }
735
736 // An rvalue for an integral bit-field (9.6) can be converted to an
737 // rvalue of type int if int can represent all the values of the
738 // bit-field; otherwise, it can be converted to unsigned int if
739 // unsigned int can represent all the values of the bit-field. If
740 // the bit-field is larger yet, no integral promotion applies to
741 // it. If the bit-field has an enumerated type, it is treated as any
742 // other value of that type for promotion purposes (C++ 4.5p3).
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000743 // FIXME: We should delay checking of bit-fields until we actually
744 // perform the conversion.
745 if (MemberExpr *MemRef = dyn_cast_or_null<MemberExpr>(From)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000746 using llvm::APSInt;
Douglas Gregor86f19402008-12-20 23:49:58 +0000747 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
748 APSInt BitWidth;
749 if (MemberDecl->isBitField() &&
750 FromType->isIntegralType() && !FromType->isEnumeralType() &&
751 From->isIntegerConstantExpr(BitWidth, Context)) {
752 APSInt ToSize(Context.getTypeSize(ToType));
753
754 // Are we promoting to an int from a bitfield that fits in an int?
755 if (BitWidth < ToSize ||
756 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
757 return To->getKind() == BuiltinType::Int;
758 }
759
760 // Are we promoting to an unsigned int from an unsigned bitfield
761 // that fits into an unsigned int?
762 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
763 return To->getKind() == BuiltinType::UInt;
764 }
765
766 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000767 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000768 }
769 }
770
771 // An rvalue of type bool can be converted to an rvalue of type int,
772 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000773 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000774 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000775 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000776
777 return false;
778}
779
780/// IsFloatingPointPromotion - Determines whether the conversion from
781/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
782/// returns true and sets PromotedType to the promoted type.
783bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
784{
785 /// An rvalue of type float can be converted to an rvalue of type
786 /// double. (C++ 4.6p1).
787 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000788 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000789 if (FromBuiltin->getKind() == BuiltinType::Float &&
790 ToBuiltin->getKind() == BuiltinType::Double)
791 return true;
792
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000793 // C99 6.3.1.5p1:
794 // When a float is promoted to double or long double, or a
795 // double is promoted to long double [...].
796 if (!getLangOptions().CPlusPlus &&
797 (FromBuiltin->getKind() == BuiltinType::Float ||
798 FromBuiltin->getKind() == BuiltinType::Double) &&
799 (ToBuiltin->getKind() == BuiltinType::LongDouble))
800 return true;
801 }
802
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000803 return false;
804}
805
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000806/// \brief Determine if a conversion is a complex promotion.
807///
808/// A complex promotion is defined as a complex -> complex conversion
809/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000810/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000811bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
812 const ComplexType *FromComplex = FromType->getAsComplexType();
813 if (!FromComplex)
814 return false;
815
816 const ComplexType *ToComplex = ToType->getAsComplexType();
817 if (!ToComplex)
818 return false;
819
820 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000821 ToComplex->getElementType()) ||
822 IsIntegralPromotion(0, FromComplex->getElementType(),
823 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000824}
825
Douglas Gregorcb7de522008-11-26 23:31:11 +0000826/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
827/// the pointer type FromPtr to a pointer to type ToPointee, with the
828/// same type qualifiers as FromPtr has on its pointee type. ToType,
829/// if non-empty, will be a pointer to ToType that may or may not have
830/// the right set of qualifiers on its pointee.
831static QualType
832BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
833 QualType ToPointee, QualType ToType,
834 ASTContext &Context) {
835 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
836 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
837 unsigned Quals = CanonFromPointee.getCVRQualifiers();
838
839 // Exact qualifier match -> return the pointer type we're converting to.
840 if (CanonToPointee.getCVRQualifiers() == Quals) {
841 // ToType is exactly what we need. Return it.
842 if (ToType.getTypePtr())
843 return ToType;
844
845 // Build a pointer to ToPointee. It has the right qualifiers
846 // already.
847 return Context.getPointerType(ToPointee);
848 }
849
850 // Just build a canonical type that has the right qualifiers.
851 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
852}
853
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000854/// IsPointerConversion - Determines whether the conversion of the
855/// expression From, which has the (possibly adjusted) type FromType,
856/// can be converted to the type ToType via a pointer conversion (C++
857/// 4.10). If so, returns true and places the converted type (that
858/// might differ from ToType in its cv-qualifiers at some level) into
859/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000860///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000861/// This routine also supports conversions to and from block pointers
862/// and conversions with Objective-C's 'id', 'id<protocols...>', and
863/// pointers to interfaces. FIXME: Once we've determined the
864/// appropriate overloading rules for Objective-C, we may want to
865/// split the Objective-C checks into a different routine; however,
866/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000867/// conversions, so for now they live here. IncompatibleObjC will be
868/// set if the conversion is an allowed Objective-C conversion that
869/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000870bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000871 QualType& ConvertedType,
872 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000873{
Douglas Gregor45920e82008-12-19 17:40:08 +0000874 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000875 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
876 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000877
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000878 // Conversion from a null pointer constant to any Objective-C pointer type.
879 if (Context.isObjCObjectPointerType(ToType) &&
880 From->isNullPointerConstant(Context)) {
881 ConvertedType = ToType;
882 return true;
883 }
884
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000885 // Blocks: Block pointers can be converted to void*.
886 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
887 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
888 ConvertedType = ToType;
889 return true;
890 }
891 // Blocks: A null pointer constant can be converted to a block
892 // pointer type.
893 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
894 ConvertedType = ToType;
895 return true;
896 }
897
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000898 const PointerType* ToTypePtr = ToType->getAsPointerType();
899 if (!ToTypePtr)
900 return false;
901
902 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
903 if (From->isNullPointerConstant(Context)) {
904 ConvertedType = ToType;
905 return true;
906 }
Sebastian Redl07779722008-10-31 14:43:28 +0000907
Douglas Gregorcb7de522008-11-26 23:31:11 +0000908 // Beyond this point, both types need to be pointers.
909 const PointerType *FromTypePtr = FromType->getAsPointerType();
910 if (!FromTypePtr)
911 return false;
912
913 QualType FromPointeeType = FromTypePtr->getPointeeType();
914 QualType ToPointeeType = ToTypePtr->getPointeeType();
915
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000916 // An rvalue of type "pointer to cv T," where T is an object type,
917 // can be converted to an rvalue of type "pointer to cv void" (C++
918 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +0000919 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000920 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
921 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000922 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000923 return true;
924 }
925
Douglas Gregorf9201e02009-02-11 23:02:49 +0000926 // When we're overloading in C, we allow a special kind of pointer
927 // conversion for compatible-but-not-identical pointee types.
928 if (!getLangOptions().CPlusPlus &&
929 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
930 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
931 ToPointeeType,
932 ToType, Context);
933 return true;
934 }
935
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000936 // C++ [conv.ptr]p3:
937 //
938 // An rvalue of type "pointer to cv D," where D is a class type,
939 // can be converted to an rvalue of type "pointer to cv B," where
940 // B is a base class (clause 10) of D. If B is an inaccessible
941 // (clause 11) or ambiguous (10.2) base class of D, a program that
942 // necessitates this conversion is ill-formed. The result of the
943 // conversion is a pointer to the base class sub-object of the
944 // derived class object. The null pointer value is converted to
945 // the null pointer value of the destination type.
946 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000947 // Note that we do not check for ambiguity or inaccessibility
948 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +0000949 if (getLangOptions().CPlusPlus &&
950 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorcb7de522008-11-26 23:31:11 +0000951 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000952 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
953 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000954 ToType, Context);
955 return true;
956 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000957
Douglas Gregorc7887512008-12-19 19:13:09 +0000958 return false;
959}
960
961/// isObjCPointerConversion - Determines whether this is an
962/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
963/// with the same arguments and return values.
964bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
965 QualType& ConvertedType,
966 bool &IncompatibleObjC) {
967 if (!getLangOptions().ObjC1)
968 return false;
969
970 // Conversions with Objective-C's id<...>.
971 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
972 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
973 ConvertedType = ToType;
974 return true;
975 }
976
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000977 // Beyond this point, both types need to be pointers or block pointers.
978 QualType ToPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000979 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000980 if (ToTypePtr)
981 ToPointeeType = ToTypePtr->getPointeeType();
982 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
983 ToPointeeType = ToBlockPtr->getPointeeType();
984 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000985 return false;
986
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000987 QualType FromPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000988 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000989 if (FromTypePtr)
990 FromPointeeType = FromTypePtr->getPointeeType();
991 else if (const BlockPointerType *FromBlockPtr
992 = FromType->getAsBlockPointerType())
993 FromPointeeType = FromBlockPtr->getPointeeType();
994 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000995 return false;
996
Douglas Gregorcb7de522008-11-26 23:31:11 +0000997 // Objective C++: We're able to convert from a pointer to an
998 // interface to a pointer to a different interface.
999 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
1000 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1001 if (FromIface && ToIface &&
1002 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001003 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001004 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001005 ToType, Context);
1006 return true;
1007 }
1008
Douglas Gregor45920e82008-12-19 17:40:08 +00001009 if (FromIface && ToIface &&
1010 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1011 // Okay: this is some kind of implicit downcast of Objective-C
1012 // interfaces, which is permitted. However, we're going to
1013 // complain about it.
1014 IncompatibleObjC = true;
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001015 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor45920e82008-12-19 17:40:08 +00001016 ToPointeeType,
1017 ToType, Context);
1018 return true;
1019 }
1020
Douglas Gregorcb7de522008-11-26 23:31:11 +00001021 // Objective C++: We're able to convert between "id" and a pointer
1022 // to any interface (in both directions).
Steve Naroff389bf462009-02-12 17:52:19 +00001023 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1024 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +00001025 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1026 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001027 ToType, Context);
1028 return true;
1029 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001030
Douglas Gregordda78892008-12-18 23:43:31 +00001031 // Objective C++: Allow conversions between the Objective-C "id" and
1032 // "Class", in either direction.
Steve Naroff389bf462009-02-12 17:52:19 +00001033 if ((Context.isObjCIdStructType(FromPointeeType) &&
1034 Context.isObjCClassStructType(ToPointeeType)) ||
1035 (Context.isObjCClassStructType(FromPointeeType) &&
1036 Context.isObjCIdStructType(ToPointeeType))) {
Douglas Gregordda78892008-12-18 23:43:31 +00001037 ConvertedType = ToType;
1038 return true;
1039 }
1040
Douglas Gregorc7887512008-12-19 19:13:09 +00001041 // If we have pointers to pointers, recursively check whether this
1042 // is an Objective-C conversion.
1043 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1044 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1045 IncompatibleObjC)) {
1046 // We always complain about this conversion.
1047 IncompatibleObjC = true;
1048 ConvertedType = ToType;
1049 return true;
1050 }
1051
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001052 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001053 // differences in the argument and result types are in Objective-C
1054 // pointer conversions. If so, we permit the conversion (but
1055 // complain about it).
Douglas Gregor72564e72009-02-26 23:50:07 +00001056 const FunctionProtoType *FromFunctionType
1057 = FromPointeeType->getAsFunctionProtoType();
1058 const FunctionProtoType *ToFunctionType
1059 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregorc7887512008-12-19 19:13:09 +00001060 if (FromFunctionType && ToFunctionType) {
1061 // If the function types are exactly the same, this isn't an
1062 // Objective-C pointer conversion.
1063 if (Context.getCanonicalType(FromPointeeType)
1064 == Context.getCanonicalType(ToPointeeType))
1065 return false;
1066
1067 // Perform the quick checks that will tell us whether these
1068 // function types are obviously different.
1069 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1070 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1071 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1072 return false;
1073
1074 bool HasObjCConversion = false;
1075 if (Context.getCanonicalType(FromFunctionType->getResultType())
1076 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1077 // Okay, the types match exactly. Nothing to do.
1078 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1079 ToFunctionType->getResultType(),
1080 ConvertedType, IncompatibleObjC)) {
1081 // Okay, we have an Objective-C pointer conversion.
1082 HasObjCConversion = true;
1083 } else {
1084 // Function types are too different. Abort.
1085 return false;
1086 }
1087
1088 // Check argument types.
1089 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1090 ArgIdx != NumArgs; ++ArgIdx) {
1091 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1092 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1093 if (Context.getCanonicalType(FromArgType)
1094 == Context.getCanonicalType(ToArgType)) {
1095 // Okay, the types match exactly. Nothing to do.
1096 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1097 ConvertedType, IncompatibleObjC)) {
1098 // Okay, we have an Objective-C pointer conversion.
1099 HasObjCConversion = true;
1100 } else {
1101 // Argument types are too different. Abort.
1102 return false;
1103 }
1104 }
1105
1106 if (HasObjCConversion) {
1107 // We had an Objective-C conversion. Allow this pointer
1108 // conversion, but complain about it.
1109 ConvertedType = ToType;
1110 IncompatibleObjC = true;
1111 return true;
1112 }
1113 }
1114
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001115 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001116}
1117
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001118/// CheckPointerConversion - Check the pointer conversion from the
1119/// expression From to the type ToType. This routine checks for
1120/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1121/// conversions for which IsPointerConversion has already returned
1122/// true. It returns true and produces a diagnostic if there was an
1123/// error, or returns false otherwise.
1124bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1125 QualType FromType = From->getType();
1126
1127 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1128 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001129 QualType FromPointeeType = FromPtrType->getPointeeType(),
1130 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001131
1132 // Objective-C++ conversions are always okay.
1133 // FIXME: We should have a different class of conversions for
1134 // the Objective-C++ implicit conversions.
Steve Naroff389bf462009-02-12 17:52:19 +00001135 if (Context.isObjCIdStructType(FromPointeeType) ||
1136 Context.isObjCIdStructType(ToPointeeType) ||
1137 Context.isObjCClassStructType(FromPointeeType) ||
1138 Context.isObjCClassStructType(ToPointeeType))
Douglas Gregordda78892008-12-18 23:43:31 +00001139 return false;
1140
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001141 if (FromPointeeType->isRecordType() &&
1142 ToPointeeType->isRecordType()) {
1143 // We must have a derived-to-base conversion. Check an
1144 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001145 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1146 From->getExprLoc(),
1147 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001148 }
1149 }
1150
1151 return false;
1152}
1153
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001154/// IsMemberPointerConversion - Determines whether the conversion of the
1155/// expression From, which has the (possibly adjusted) type FromType, can be
1156/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1157/// If so, returns true and places the converted type (that might differ from
1158/// ToType in its cv-qualifiers at some level) into ConvertedType.
1159bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1160 QualType ToType, QualType &ConvertedType)
1161{
1162 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1163 if (!ToTypePtr)
1164 return false;
1165
1166 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1167 if (From->isNullPointerConstant(Context)) {
1168 ConvertedType = ToType;
1169 return true;
1170 }
1171
1172 // Otherwise, both types have to be member pointers.
1173 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1174 if (!FromTypePtr)
1175 return false;
1176
1177 // A pointer to member of B can be converted to a pointer to member of D,
1178 // where D is derived from B (C++ 4.11p2).
1179 QualType FromClass(FromTypePtr->getClass(), 0);
1180 QualType ToClass(ToTypePtr->getClass(), 0);
1181 // FIXME: What happens when these are dependent? Is this function even called?
1182
1183 if (IsDerivedFrom(ToClass, FromClass)) {
1184 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1185 ToClass.getTypePtr());
1186 return true;
1187 }
1188
1189 return false;
1190}
1191
1192/// CheckMemberPointerConversion - Check the member pointer conversion from the
1193/// expression From to the type ToType. This routine checks for ambiguous or
1194/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1195/// for which IsMemberPointerConversion has already returned true. It returns
1196/// true and produces a diagnostic if there was an error, or returns false
1197/// otherwise.
1198bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1199 QualType FromType = From->getType();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001200 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1201 if (!FromPtrType)
1202 return false;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001203
Sebastian Redl21593ac2009-01-28 18:33:18 +00001204 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1205 assert(ToPtrType && "No member pointer cast has a target type "
1206 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001207
Sebastian Redl21593ac2009-01-28 18:33:18 +00001208 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1209 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001210
Sebastian Redl21593ac2009-01-28 18:33:18 +00001211 // FIXME: What about dependent types?
1212 assert(FromClass->isRecordType() && "Pointer into non-class.");
1213 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001214
Sebastian Redl21593ac2009-01-28 18:33:18 +00001215 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1216 /*DetectVirtual=*/true);
1217 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1218 assert(DerivationOkay &&
1219 "Should not have been called if derivation isn't OK.");
1220 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001221
Sebastian Redl21593ac2009-01-28 18:33:18 +00001222 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1223 getUnqualifiedType())) {
1224 // Derivation is ambiguous. Redo the check to find the exact paths.
1225 Paths.clear();
1226 Paths.setRecordingPaths(true);
1227 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1228 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1229 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001230
Sebastian Redl21593ac2009-01-28 18:33:18 +00001231 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1232 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1233 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1234 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001235 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001236
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001237 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001238 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1239 << FromClass << ToClass << QualType(VBase, 0)
1240 << From->getSourceRange();
1241 return true;
1242 }
1243
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001244 return false;
1245}
1246
Douglas Gregor98cd5992008-10-21 23:43:52 +00001247/// IsQualificationConversion - Determines whether the conversion from
1248/// an rvalue of type FromType to ToType is a qualification conversion
1249/// (C++ 4.4).
1250bool
1251Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1252{
1253 FromType = Context.getCanonicalType(FromType);
1254 ToType = Context.getCanonicalType(ToType);
1255
1256 // If FromType and ToType are the same type, this is not a
1257 // qualification conversion.
1258 if (FromType == ToType)
1259 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001260
Douglas Gregor98cd5992008-10-21 23:43:52 +00001261 // (C++ 4.4p4):
1262 // A conversion can add cv-qualifiers at levels other than the first
1263 // in multi-level pointers, subject to the following rules: [...]
1264 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001265 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001266 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001267 // Within each iteration of the loop, we check the qualifiers to
1268 // determine if this still looks like a qualification
1269 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001270 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001271 // until there are no more pointers or pointers-to-members left to
1272 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001273 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001274
1275 // -- for every j > 0, if const is in cv 1,j then const is in cv
1276 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001277 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001278 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001279
Douglas Gregor98cd5992008-10-21 23:43:52 +00001280 // -- if the cv 1,j and cv 2,j are different, then const is in
1281 // every cv for 0 < k < j.
1282 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001283 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001284 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001285
Douglas Gregor98cd5992008-10-21 23:43:52 +00001286 // Keep track of whether all prior cv-qualifiers in the "to" type
1287 // include const.
1288 PreviousToQualsIncludeConst
1289 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001290 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001291
1292 // We are left with FromType and ToType being the pointee types
1293 // after unwrapping the original FromType and ToType the same number
1294 // of types. If we unwrapped any pointers, and if FromType and
1295 // ToType have the same unqualified type (since we checked
1296 // qualifiers above), then this is a qualification conversion.
1297 return UnwrappedAnyPointer &&
1298 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1299}
1300
Douglas Gregor734d9862009-01-30 23:27:23 +00001301/// Determines whether there is a user-defined conversion sequence
1302/// (C++ [over.ics.user]) that converts expression From to the type
1303/// ToType. If such a conversion exists, User will contain the
1304/// user-defined conversion sequence that performs such a conversion
1305/// and this routine will return true. Otherwise, this routine returns
1306/// false and User is unspecified.
1307///
1308/// \param AllowConversionFunctions true if the conversion should
1309/// consider conversion functions at all. If false, only constructors
1310/// will be considered.
1311///
1312/// \param AllowExplicit true if the conversion should consider C++0x
1313/// "explicit" conversion functions as well as non-explicit conversion
1314/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001315bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001316 UserDefinedConversionSequence& User,
Douglas Gregor734d9862009-01-30 23:27:23 +00001317 bool AllowConversionFunctions,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001318 bool AllowExplicit)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001319{
1320 OverloadCandidateSet CandidateSet;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001321 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1322 if (CXXRecordDecl *ToRecordDecl
1323 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1324 // C++ [over.match.ctor]p1:
1325 // When objects of class type are direct-initialized (8.5), or
1326 // copy-initialized from an expression of the same or a
1327 // derived class type (8.5), overload resolution selects the
1328 // constructor. [...] For copy-initialization, the candidate
1329 // functions are all the converting constructors (12.3.1) of
1330 // that class. The argument list is the expression-list within
1331 // the parentheses of the initializer.
1332 DeclarationName ConstructorName
1333 = Context.DeclarationNames.getCXXConstructorName(
1334 Context.getCanonicalType(ToType).getUnqualifiedType());
1335 DeclContext::lookup_iterator Con, ConEnd;
1336 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName);
1337 Con != ConEnd; ++Con) {
1338 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1339 if (Constructor->isConvertingConstructor())
1340 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1341 /*SuppressUserConversions=*/true);
1342 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001343 }
1344 }
1345
Douglas Gregor734d9862009-01-30 23:27:23 +00001346 if (!AllowConversionFunctions) {
1347 // Don't allow any conversion functions to enter the overload set.
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001348 } else if (const RecordType *FromRecordType
1349 = From->getType()->getAsRecordType()) {
1350 if (CXXRecordDecl *FromRecordDecl
1351 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1352 // Add all of the conversion functions as candidates.
1353 // FIXME: Look for conversions in base classes!
1354 OverloadedFunctionDecl *Conversions
1355 = FromRecordDecl->getConversionFunctions();
1356 for (OverloadedFunctionDecl::function_iterator Func
1357 = Conversions->function_begin();
1358 Func != Conversions->function_end(); ++Func) {
1359 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1360 if (AllowExplicit || !Conv->isExplicit())
1361 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1362 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001363 }
1364 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001365
1366 OverloadCandidateSet::iterator Best;
1367 switch (BestViableFunction(CandidateSet, Best)) {
1368 case OR_Success:
1369 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001370 if (CXXConstructorDecl *Constructor
1371 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1372 // C++ [over.ics.user]p1:
1373 // If the user-defined conversion is specified by a
1374 // constructor (12.3.1), the initial standard conversion
1375 // sequence converts the source type to the type required by
1376 // the argument of the constructor.
1377 //
1378 // FIXME: What about ellipsis conversions?
1379 QualType ThisType = Constructor->getThisType(Context);
1380 User.Before = Best->Conversions[0].Standard;
1381 User.ConversionFunction = Constructor;
1382 User.After.setAsIdentityConversion();
1383 User.After.FromTypePtr
1384 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1385 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1386 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001387 } else if (CXXConversionDecl *Conversion
1388 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1389 // C++ [over.ics.user]p1:
1390 //
1391 // [...] If the user-defined conversion is specified by a
1392 // conversion function (12.3.2), the initial standard
1393 // conversion sequence converts the source type to the
1394 // implicit object parameter of the conversion function.
1395 User.Before = Best->Conversions[0].Standard;
1396 User.ConversionFunction = Conversion;
1397
1398 // C++ [over.ics.user]p2:
1399 // The second standard conversion sequence converts the
1400 // result of the user-defined conversion to the target type
1401 // for the sequence. Since an implicit conversion sequence
1402 // is an initialization, the special rules for
1403 // initialization by user-defined conversion apply when
1404 // selecting the best user-defined conversion for a
1405 // user-defined conversion sequence (see 13.3.3 and
1406 // 13.3.3.1).
1407 User.After = Best->FinalConversion;
1408 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001409 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001410 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001411 return false;
1412 }
1413
1414 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001415 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001416 // No conversion here! We're done.
1417 return false;
1418
1419 case OR_Ambiguous:
1420 // FIXME: See C++ [over.best.ics]p10 for the handling of
1421 // ambiguous conversion sequences.
1422 return false;
1423 }
1424
1425 return false;
1426}
1427
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001428/// CompareImplicitConversionSequences - Compare two implicit
1429/// conversion sequences to determine whether one is better than the
1430/// other or if they are indistinguishable (C++ 13.3.3.2).
1431ImplicitConversionSequence::CompareKind
1432Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1433 const ImplicitConversionSequence& ICS2)
1434{
1435 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1436 // conversion sequences (as defined in 13.3.3.1)
1437 // -- a standard conversion sequence (13.3.3.1.1) is a better
1438 // conversion sequence than a user-defined conversion sequence or
1439 // an ellipsis conversion sequence, and
1440 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1441 // conversion sequence than an ellipsis conversion sequence
1442 // (13.3.3.1.3).
1443 //
1444 if (ICS1.ConversionKind < ICS2.ConversionKind)
1445 return ImplicitConversionSequence::Better;
1446 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1447 return ImplicitConversionSequence::Worse;
1448
1449 // Two implicit conversion sequences of the same form are
1450 // indistinguishable conversion sequences unless one of the
1451 // following rules apply: (C++ 13.3.3.2p3):
1452 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1453 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1454 else if (ICS1.ConversionKind ==
1455 ImplicitConversionSequence::UserDefinedConversion) {
1456 // User-defined conversion sequence U1 is a better conversion
1457 // sequence than another user-defined conversion sequence U2 if
1458 // they contain the same user-defined conversion function or
1459 // constructor and if the second standard conversion sequence of
1460 // U1 is better than the second standard conversion sequence of
1461 // U2 (C++ 13.3.3.2p3).
1462 if (ICS1.UserDefined.ConversionFunction ==
1463 ICS2.UserDefined.ConversionFunction)
1464 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1465 ICS2.UserDefined.After);
1466 }
1467
1468 return ImplicitConversionSequence::Indistinguishable;
1469}
1470
1471/// CompareStandardConversionSequences - Compare two standard
1472/// conversion sequences to determine whether one is better than the
1473/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1474ImplicitConversionSequence::CompareKind
1475Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1476 const StandardConversionSequence& SCS2)
1477{
1478 // Standard conversion sequence S1 is a better conversion sequence
1479 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1480
1481 // -- S1 is a proper subsequence of S2 (comparing the conversion
1482 // sequences in the canonical form defined by 13.3.3.1.1,
1483 // excluding any Lvalue Transformation; the identity conversion
1484 // sequence is considered to be a subsequence of any
1485 // non-identity conversion sequence) or, if not that,
1486 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1487 // Neither is a proper subsequence of the other. Do nothing.
1488 ;
1489 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1490 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1491 (SCS1.Second == ICK_Identity &&
1492 SCS1.Third == ICK_Identity))
1493 // SCS1 is a proper subsequence of SCS2.
1494 return ImplicitConversionSequence::Better;
1495 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1496 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1497 (SCS2.Second == ICK_Identity &&
1498 SCS2.Third == ICK_Identity))
1499 // SCS2 is a proper subsequence of SCS1.
1500 return ImplicitConversionSequence::Worse;
1501
1502 // -- the rank of S1 is better than the rank of S2 (by the rules
1503 // defined below), or, if not that,
1504 ImplicitConversionRank Rank1 = SCS1.getRank();
1505 ImplicitConversionRank Rank2 = SCS2.getRank();
1506 if (Rank1 < Rank2)
1507 return ImplicitConversionSequence::Better;
1508 else if (Rank2 < Rank1)
1509 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001510
Douglas Gregor57373262008-10-22 14:17:15 +00001511 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1512 // are indistinguishable unless one of the following rules
1513 // applies:
1514
1515 // A conversion that is not a conversion of a pointer, or
1516 // pointer to member, to bool is better than another conversion
1517 // that is such a conversion.
1518 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1519 return SCS2.isPointerConversionToBool()
1520 ? ImplicitConversionSequence::Better
1521 : ImplicitConversionSequence::Worse;
1522
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001523 // C++ [over.ics.rank]p4b2:
1524 //
1525 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001526 // conversion of B* to A* is better than conversion of B* to
1527 // void*, and conversion of A* to void* is better than conversion
1528 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001529 bool SCS1ConvertsToVoid
1530 = SCS1.isPointerConversionToVoidPointer(Context);
1531 bool SCS2ConvertsToVoid
1532 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001533 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1534 // Exactly one of the conversion sequences is a conversion to
1535 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001536 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1537 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001538 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1539 // Neither conversion sequence converts to a void pointer; compare
1540 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001541 if (ImplicitConversionSequence::CompareKind DerivedCK
1542 = CompareDerivedToBaseConversions(SCS1, SCS2))
1543 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001544 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1545 // Both conversion sequences are conversions to void
1546 // pointers. Compare the source types to determine if there's an
1547 // inheritance relationship in their sources.
1548 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1549 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1550
1551 // Adjust the types we're converting from via the array-to-pointer
1552 // conversion, if we need to.
1553 if (SCS1.First == ICK_Array_To_Pointer)
1554 FromType1 = Context.getArrayDecayedType(FromType1);
1555 if (SCS2.First == ICK_Array_To_Pointer)
1556 FromType2 = Context.getArrayDecayedType(FromType2);
1557
1558 QualType FromPointee1
1559 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1560 QualType FromPointee2
1561 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1562
1563 if (IsDerivedFrom(FromPointee2, FromPointee1))
1564 return ImplicitConversionSequence::Better;
1565 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1566 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001567
1568 // Objective-C++: If one interface is more specific than the
1569 // other, it is the better one.
1570 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1571 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1572 if (FromIface1 && FromIface1) {
1573 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1574 return ImplicitConversionSequence::Better;
1575 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1576 return ImplicitConversionSequence::Worse;
1577 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001578 }
Douglas Gregor57373262008-10-22 14:17:15 +00001579
1580 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1581 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001582 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001583 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001584 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001585
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001586 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Anders Carlsson14734f72009-03-28 04:17:27 +00001587 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1588 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001589 // C++0x [over.ics.rank]p3b4:
1590 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1591 // implicit object parameter of a non-static member function declared
1592 // without a ref-qualifier, and S1 binds an rvalue reference to an
1593 // rvalue and S2 binds an lvalue reference.
Anders Carlsson14734f72009-03-28 04:17:27 +00001594 // FIXME: We have far too little information for this check. We don't know
1595 // if the bound object is an rvalue. We don't know if the binding type is
1596 // an rvalue or lvalue reference. We don't know if we're dealing with the
1597 // implicit object parameter, or if the member function in this case has
1598 // a ref qualifier.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001599
1600 // C++ [over.ics.rank]p3b4:
1601 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1602 // which the references refer are the same type except for
1603 // top-level cv-qualifiers, and the type to which the reference
1604 // initialized by S2 refers is more cv-qualified than the type
1605 // to which the reference initialized by S1 refers.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001606 T1 = Context.getCanonicalType(T1);
1607 T2 = Context.getCanonicalType(T2);
1608 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1609 if (T2.isMoreQualifiedThan(T1))
1610 return ImplicitConversionSequence::Better;
1611 else if (T1.isMoreQualifiedThan(T2))
1612 return ImplicitConversionSequence::Worse;
1613 }
1614 }
Douglas Gregor57373262008-10-22 14:17:15 +00001615
1616 return ImplicitConversionSequence::Indistinguishable;
1617}
1618
1619/// CompareQualificationConversions - Compares two standard conversion
1620/// sequences to determine whether they can be ranked based on their
1621/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1622ImplicitConversionSequence::CompareKind
1623Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1624 const StandardConversionSequence& SCS2)
1625{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001626 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001627 // -- S1 and S2 differ only in their qualification conversion and
1628 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1629 // cv-qualification signature of type T1 is a proper subset of
1630 // the cv-qualification signature of type T2, and S1 is not the
1631 // deprecated string literal array-to-pointer conversion (4.2).
1632 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1633 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1634 return ImplicitConversionSequence::Indistinguishable;
1635
1636 // FIXME: the example in the standard doesn't use a qualification
1637 // conversion (!)
1638 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1639 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1640 T1 = Context.getCanonicalType(T1);
1641 T2 = Context.getCanonicalType(T2);
1642
1643 // If the types are the same, we won't learn anything by unwrapped
1644 // them.
1645 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1646 return ImplicitConversionSequence::Indistinguishable;
1647
1648 ImplicitConversionSequence::CompareKind Result
1649 = ImplicitConversionSequence::Indistinguishable;
1650 while (UnwrapSimilarPointerTypes(T1, T2)) {
1651 // Within each iteration of the loop, we check the qualifiers to
1652 // determine if this still looks like a qualification
1653 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001654 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001655 // until there are no more pointers or pointers-to-members left
1656 // to unwrap. This essentially mimics what
1657 // IsQualificationConversion does, but here we're checking for a
1658 // strict subset of qualifiers.
1659 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1660 // The qualifiers are the same, so this doesn't tell us anything
1661 // about how the sequences rank.
1662 ;
1663 else if (T2.isMoreQualifiedThan(T1)) {
1664 // T1 has fewer qualifiers, so it could be the better sequence.
1665 if (Result == ImplicitConversionSequence::Worse)
1666 // Neither has qualifiers that are a subset of the other's
1667 // qualifiers.
1668 return ImplicitConversionSequence::Indistinguishable;
1669
1670 Result = ImplicitConversionSequence::Better;
1671 } else if (T1.isMoreQualifiedThan(T2)) {
1672 // T2 has fewer qualifiers, so it could be the better sequence.
1673 if (Result == ImplicitConversionSequence::Better)
1674 // Neither has qualifiers that are a subset of the other's
1675 // qualifiers.
1676 return ImplicitConversionSequence::Indistinguishable;
1677
1678 Result = ImplicitConversionSequence::Worse;
1679 } else {
1680 // Qualifiers are disjoint.
1681 return ImplicitConversionSequence::Indistinguishable;
1682 }
1683
1684 // If the types after this point are equivalent, we're done.
1685 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1686 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001687 }
1688
Douglas Gregor57373262008-10-22 14:17:15 +00001689 // Check that the winning standard conversion sequence isn't using
1690 // the deprecated string literal array to pointer conversion.
1691 switch (Result) {
1692 case ImplicitConversionSequence::Better:
1693 if (SCS1.Deprecated)
1694 Result = ImplicitConversionSequence::Indistinguishable;
1695 break;
1696
1697 case ImplicitConversionSequence::Indistinguishable:
1698 break;
1699
1700 case ImplicitConversionSequence::Worse:
1701 if (SCS2.Deprecated)
1702 Result = ImplicitConversionSequence::Indistinguishable;
1703 break;
1704 }
1705
1706 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001707}
1708
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001709/// CompareDerivedToBaseConversions - Compares two standard conversion
1710/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001711/// various kinds of derived-to-base conversions (C++
1712/// [over.ics.rank]p4b3). As part of these checks, we also look at
1713/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001714ImplicitConversionSequence::CompareKind
1715Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1716 const StandardConversionSequence& SCS2) {
1717 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1718 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1719 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1720 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1721
1722 // Adjust the types we're converting from via the array-to-pointer
1723 // conversion, if we need to.
1724 if (SCS1.First == ICK_Array_To_Pointer)
1725 FromType1 = Context.getArrayDecayedType(FromType1);
1726 if (SCS2.First == ICK_Array_To_Pointer)
1727 FromType2 = Context.getArrayDecayedType(FromType2);
1728
1729 // Canonicalize all of the types.
1730 FromType1 = Context.getCanonicalType(FromType1);
1731 ToType1 = Context.getCanonicalType(ToType1);
1732 FromType2 = Context.getCanonicalType(FromType2);
1733 ToType2 = Context.getCanonicalType(ToType2);
1734
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001735 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001736 //
1737 // If class B is derived directly or indirectly from class A and
1738 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001739 //
1740 // For Objective-C, we let A, B, and C also be Objective-C
1741 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001742
1743 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001744 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001745 SCS2.Second == ICK_Pointer_Conversion &&
1746 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1747 FromType1->isPointerType() && FromType2->isPointerType() &&
1748 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001749 QualType FromPointee1
1750 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1751 QualType ToPointee1
1752 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1753 QualType FromPointee2
1754 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1755 QualType ToPointee2
1756 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001757
1758 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1759 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1760 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1761 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1762
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001763 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001764 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1765 if (IsDerivedFrom(ToPointee1, ToPointee2))
1766 return ImplicitConversionSequence::Better;
1767 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1768 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001769
1770 if (ToIface1 && ToIface2) {
1771 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1772 return ImplicitConversionSequence::Better;
1773 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1774 return ImplicitConversionSequence::Worse;
1775 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001776 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001777
1778 // -- conversion of B* to A* is better than conversion of C* to A*,
1779 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1780 if (IsDerivedFrom(FromPointee2, FromPointee1))
1781 return ImplicitConversionSequence::Better;
1782 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1783 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001784
1785 if (FromIface1 && FromIface2) {
1786 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1787 return ImplicitConversionSequence::Better;
1788 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1789 return ImplicitConversionSequence::Worse;
1790 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001791 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001792 }
1793
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001794 // Compare based on reference bindings.
1795 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1796 SCS1.Second == ICK_Derived_To_Base) {
1797 // -- binding of an expression of type C to a reference of type
1798 // B& is better than binding an expression of type C to a
1799 // reference of type A&,
1800 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1801 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1802 if (IsDerivedFrom(ToType1, ToType2))
1803 return ImplicitConversionSequence::Better;
1804 else if (IsDerivedFrom(ToType2, ToType1))
1805 return ImplicitConversionSequence::Worse;
1806 }
1807
Douglas Gregor225c41e2008-11-03 19:09:14 +00001808 // -- binding of an expression of type B to a reference of type
1809 // A& is better than binding an expression of type C to a
1810 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001811 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1812 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1813 if (IsDerivedFrom(FromType2, FromType1))
1814 return ImplicitConversionSequence::Better;
1815 else if (IsDerivedFrom(FromType1, FromType2))
1816 return ImplicitConversionSequence::Worse;
1817 }
1818 }
1819
1820
1821 // FIXME: conversion of A::* to B::* is better than conversion of
1822 // A::* to C::*,
1823
1824 // FIXME: conversion of B::* to C::* is better than conversion of
1825 // A::* to C::*, and
1826
Douglas Gregor225c41e2008-11-03 19:09:14 +00001827 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1828 SCS1.Second == ICK_Derived_To_Base) {
1829 // -- conversion of C to B is better than conversion of C to A,
1830 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1831 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1832 if (IsDerivedFrom(ToType1, ToType2))
1833 return ImplicitConversionSequence::Better;
1834 else if (IsDerivedFrom(ToType2, ToType1))
1835 return ImplicitConversionSequence::Worse;
1836 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001837
Douglas Gregor225c41e2008-11-03 19:09:14 +00001838 // -- conversion of B to A is better than conversion of C to A.
1839 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1840 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1841 if (IsDerivedFrom(FromType2, FromType1))
1842 return ImplicitConversionSequence::Better;
1843 else if (IsDerivedFrom(FromType1, FromType2))
1844 return ImplicitConversionSequence::Worse;
1845 }
1846 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001847
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001848 return ImplicitConversionSequence::Indistinguishable;
1849}
1850
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001851/// TryCopyInitialization - Try to copy-initialize a value of type
1852/// ToType from the expression From. Return the implicit conversion
1853/// sequence required to pass this argument, which may be a bad
1854/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001855/// a parameter of this type). If @p SuppressUserConversions, then we
1856/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001857ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001858Sema::TryCopyInitialization(Expr *From, QualType ToType,
1859 bool SuppressUserConversions) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001860 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001861 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001862 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001863 return ICS;
1864 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001865 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001866 }
1867}
1868
1869/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1870/// type ToType. Returns true (and emits a diagnostic) if there was
1871/// an error, returns false if the initialization succeeded.
1872bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1873 const char* Flavor) {
1874 if (!getLangOptions().CPlusPlus) {
1875 // In C, argument passing is the same as performing an assignment.
1876 QualType FromType = From->getType();
1877 AssignConvertType ConvTy =
1878 CheckSingleAssignmentConstraints(ToType, From);
1879
1880 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1881 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001882 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001883
1884 if (ToType->isReferenceType())
1885 return CheckReferenceInit(From, ToType);
1886
Douglas Gregor45920e82008-12-19 17:40:08 +00001887 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001888 return false;
1889
1890 return Diag(From->getSourceRange().getBegin(),
1891 diag::err_typecheck_convert_incompatible)
1892 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001893}
1894
Douglas Gregor96176b32008-11-18 23:14:02 +00001895/// TryObjectArgumentInitialization - Try to initialize the object
1896/// parameter of the given member function (@c Method) from the
1897/// expression @p From.
1898ImplicitConversionSequence
1899Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1900 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1901 unsigned MethodQuals = Method->getTypeQualifiers();
1902 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1903
1904 // Set up the conversion sequence as a "bad" conversion, to allow us
1905 // to exit early.
1906 ImplicitConversionSequence ICS;
1907 ICS.Standard.setAsIdentityConversion();
1908 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1909
1910 // We need to have an object of class type.
1911 QualType FromType = From->getType();
1912 if (!FromType->isRecordType())
1913 return ICS;
1914
1915 // The implicit object parmeter is has the type "reference to cv X",
1916 // where X is the class of which the function is a member
1917 // (C++ [over.match.funcs]p4). However, when finding an implicit
1918 // conversion sequence for the argument, we are not allowed to
1919 // create temporaries or perform user-defined conversions
1920 // (C++ [over.match.funcs]p5). We perform a simplified version of
1921 // reference binding here, that allows class rvalues to bind to
1922 // non-constant references.
1923
1924 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1925 // with the implicit object parameter (C++ [over.match.funcs]p5).
1926 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1927 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1928 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1929 return ICS;
1930
1931 // Check that we have either the same type or a derived type. It
1932 // affects the conversion rank.
1933 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1934 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1935 ICS.Standard.Second = ICK_Identity;
1936 else if (IsDerivedFrom(FromType, ClassType))
1937 ICS.Standard.Second = ICK_Derived_To_Base;
1938 else
1939 return ICS;
1940
1941 // Success. Mark this as a reference binding.
1942 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1943 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1944 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1945 ICS.Standard.ReferenceBinding = true;
1946 ICS.Standard.DirectBinding = true;
1947 return ICS;
1948}
1949
1950/// PerformObjectArgumentInitialization - Perform initialization of
1951/// the implicit object parameter for the given Method with the given
1952/// expression.
1953bool
1954Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1955 QualType ImplicitParamType
1956 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1957 ImplicitConversionSequence ICS
1958 = TryObjectArgumentInitialization(From, Method);
1959 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1960 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001961 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001962 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001963
1964 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1965 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1966 From->getSourceRange().getBegin(),
1967 From->getSourceRange()))
1968 return true;
1969
1970 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1971 return false;
1972}
1973
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001974/// TryContextuallyConvertToBool - Attempt to contextually convert the
1975/// expression From to bool (C++0x [conv]p3).
1976ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1977 return TryImplicitConversion(From, Context.BoolTy, false, true);
1978}
1979
1980/// PerformContextuallyConvertToBool - Perform a contextual conversion
1981/// of the expression From to bool (C++0x [conv]p3).
1982bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1983 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1984 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1985 return false;
1986
1987 return Diag(From->getSourceRange().getBegin(),
1988 diag::err_typecheck_bool_condition)
1989 << From->getType() << From->getSourceRange();
1990}
1991
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001992/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001993/// candidate functions, using the given function call arguments. If
1994/// @p SuppressUserConversions, then don't allow user-defined
1995/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001996void
1997Sema::AddOverloadCandidate(FunctionDecl *Function,
1998 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001999 OverloadCandidateSet& CandidateSet,
2000 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002001{
Douglas Gregor72564e72009-02-26 23:50:07 +00002002 const FunctionProtoType* Proto
2003 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002004 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002005 assert(!isa<CXXConversionDecl>(Function) &&
2006 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002007
Douglas Gregor88a35142008-12-22 05:46:06 +00002008 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2009 // If we get here, it's because we're calling a member function
2010 // that is named without a member access expression (e.g.,
2011 // "this->f") that was either written explicitly or created
2012 // implicitly. This can happen with a qualified call to a member
2013 // function, e.g., X::f(). We use a NULL object as the implied
2014 // object argument (C++ [over.call.func]p3).
2015 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2016 SuppressUserConversions);
2017 return;
2018 }
2019
2020
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002021 // Add this candidate
2022 CandidateSet.push_back(OverloadCandidate());
2023 OverloadCandidate& Candidate = CandidateSet.back();
2024 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002025 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002026 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002027 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002028
2029 unsigned NumArgsInProto = Proto->getNumArgs();
2030
2031 // (C++ 13.3.2p2): A candidate function having fewer than m
2032 // parameters is viable only if it has an ellipsis in its parameter
2033 // list (8.3.5).
2034 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2035 Candidate.Viable = false;
2036 return;
2037 }
2038
2039 // (C++ 13.3.2p2): A candidate function having more than m parameters
2040 // is viable only if the (m+1)st parameter has a default argument
2041 // (8.3.6). For the purposes of overload resolution, the
2042 // parameter list is truncated on the right, so that there are
2043 // exactly m parameters.
2044 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2045 if (NumArgs < MinRequiredArgs) {
2046 // Not enough arguments.
2047 Candidate.Viable = false;
2048 return;
2049 }
2050
2051 // Determine the implicit conversion sequences for each of the
2052 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002053 Candidate.Conversions.resize(NumArgs);
2054 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2055 if (ArgIdx < NumArgsInProto) {
2056 // (C++ 13.3.2p3): for F to be a viable function, there shall
2057 // exist for each argument an implicit conversion sequence
2058 // (13.3.3.1) that converts that argument to the corresponding
2059 // parameter of F.
2060 QualType ParamType = Proto->getArgType(ArgIdx);
2061 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00002062 = TryCopyInitialization(Args[ArgIdx], ParamType,
2063 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002064 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002065 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002066 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002067 break;
2068 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002069 } else {
2070 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2071 // argument for which there is no corresponding parameter is
2072 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2073 Candidate.Conversions[ArgIdx].ConversionKind
2074 = ImplicitConversionSequence::EllipsisConversion;
2075 }
2076 }
2077}
2078
Douglas Gregor063daf62009-03-13 18:40:31 +00002079/// \brief Add all of the function declarations in the given function set to
2080/// the overload canddiate set.
2081void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2082 Expr **Args, unsigned NumArgs,
2083 OverloadCandidateSet& CandidateSet,
2084 bool SuppressUserConversions) {
2085 for (FunctionSet::const_iterator F = Functions.begin(),
2086 FEnd = Functions.end();
2087 F != FEnd; ++F)
2088 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2089 SuppressUserConversions);
2090}
2091
Douglas Gregor96176b32008-11-18 23:14:02 +00002092/// AddMethodCandidate - Adds the given C++ member function to the set
2093/// of candidate functions, using the given function call arguments
2094/// and the object argument (@c Object). For example, in a call
2095/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2096/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2097/// allow user-defined conversions via constructors or conversion
2098/// operators.
2099void
2100Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2101 Expr **Args, unsigned NumArgs,
2102 OverloadCandidateSet& CandidateSet,
2103 bool SuppressUserConversions)
2104{
Douglas Gregor72564e72009-02-26 23:50:07 +00002105 const FunctionProtoType* Proto
2106 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002107 assert(Proto && "Methods without a prototype cannot be overloaded");
2108 assert(!isa<CXXConversionDecl>(Method) &&
2109 "Use AddConversionCandidate for conversion functions");
2110
2111 // Add this candidate
2112 CandidateSet.push_back(OverloadCandidate());
2113 OverloadCandidate& Candidate = CandidateSet.back();
2114 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002115 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002116 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002117
2118 unsigned NumArgsInProto = Proto->getNumArgs();
2119
2120 // (C++ 13.3.2p2): A candidate function having fewer than m
2121 // parameters is viable only if it has an ellipsis in its parameter
2122 // list (8.3.5).
2123 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2124 Candidate.Viable = false;
2125 return;
2126 }
2127
2128 // (C++ 13.3.2p2): A candidate function having more than m parameters
2129 // is viable only if the (m+1)st parameter has a default argument
2130 // (8.3.6). For the purposes of overload resolution, the
2131 // parameter list is truncated on the right, so that there are
2132 // exactly m parameters.
2133 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2134 if (NumArgs < MinRequiredArgs) {
2135 // Not enough arguments.
2136 Candidate.Viable = false;
2137 return;
2138 }
2139
2140 Candidate.Viable = true;
2141 Candidate.Conversions.resize(NumArgs + 1);
2142
Douglas Gregor88a35142008-12-22 05:46:06 +00002143 if (Method->isStatic() || !Object)
2144 // The implicit object argument is ignored.
2145 Candidate.IgnoreObjectArgument = true;
2146 else {
2147 // Determine the implicit conversion sequence for the object
2148 // parameter.
2149 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2150 if (Candidate.Conversions[0].ConversionKind
2151 == ImplicitConversionSequence::BadConversion) {
2152 Candidate.Viable = false;
2153 return;
2154 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002155 }
2156
2157 // Determine the implicit conversion sequences for each of the
2158 // arguments.
2159 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2160 if (ArgIdx < NumArgsInProto) {
2161 // (C++ 13.3.2p3): for F to be a viable function, there shall
2162 // exist for each argument an implicit conversion sequence
2163 // (13.3.3.1) that converts that argument to the corresponding
2164 // parameter of F.
2165 QualType ParamType = Proto->getArgType(ArgIdx);
2166 Candidate.Conversions[ArgIdx + 1]
2167 = TryCopyInitialization(Args[ArgIdx], ParamType,
2168 SuppressUserConversions);
2169 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2170 == ImplicitConversionSequence::BadConversion) {
2171 Candidate.Viable = false;
2172 break;
2173 }
2174 } else {
2175 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2176 // argument for which there is no corresponding parameter is
2177 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2178 Candidate.Conversions[ArgIdx + 1].ConversionKind
2179 = ImplicitConversionSequence::EllipsisConversion;
2180 }
2181 }
2182}
2183
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002184/// AddConversionCandidate - Add a C++ conversion function as a
2185/// candidate in the candidate set (C++ [over.match.conv],
2186/// C++ [over.match.copy]). From is the expression we're converting from,
2187/// and ToType is the type that we're eventually trying to convert to
2188/// (which may or may not be the same type as the type that the
2189/// conversion function produces).
2190void
2191Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2192 Expr *From, QualType ToType,
2193 OverloadCandidateSet& CandidateSet) {
2194 // Add this candidate
2195 CandidateSet.push_back(OverloadCandidate());
2196 OverloadCandidate& Candidate = CandidateSet.back();
2197 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002198 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002199 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002200 Candidate.FinalConversion.setAsIdentityConversion();
2201 Candidate.FinalConversion.FromTypePtr
2202 = Conversion->getConversionType().getAsOpaquePtr();
2203 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2204
Douglas Gregor96176b32008-11-18 23:14:02 +00002205 // Determine the implicit conversion sequence for the implicit
2206 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002207 Candidate.Viable = true;
2208 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002209 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002210
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002211 if (Candidate.Conversions[0].ConversionKind
2212 == ImplicitConversionSequence::BadConversion) {
2213 Candidate.Viable = false;
2214 return;
2215 }
2216
2217 // To determine what the conversion from the result of calling the
2218 // conversion function to the type we're eventually trying to
2219 // convert to (ToType), we need to synthesize a call to the
2220 // conversion function and attempt copy initialization from it. This
2221 // makes sure that we get the right semantics with respect to
2222 // lvalues/rvalues and the type. Fortunately, we can allocate this
2223 // call on the stack and we don't need its arguments to be
2224 // well-formed.
2225 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2226 SourceLocation());
2227 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002228 &ConversionRef, false);
Ted Kremenek668bf912009-02-09 20:51:47 +00002229
2230 // Note that it is safe to allocate CallExpr on the stack here because
2231 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2232 // allocator).
2233 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002234 Conversion->getConversionType().getNonReferenceType(),
2235 SourceLocation());
2236 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2237 switch (ICS.ConversionKind) {
2238 case ImplicitConversionSequence::StandardConversion:
2239 Candidate.FinalConversion = ICS.Standard;
2240 break;
2241
2242 case ImplicitConversionSequence::BadConversion:
2243 Candidate.Viable = false;
2244 break;
2245
2246 default:
2247 assert(false &&
2248 "Can only end up with a standard conversion sequence or failure");
2249 }
2250}
2251
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002252/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2253/// converts the given @c Object to a function pointer via the
2254/// conversion function @c Conversion, and then attempts to call it
2255/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2256/// the type of function that we'll eventually be calling.
2257void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor72564e72009-02-26 23:50:07 +00002258 const FunctionProtoType *Proto,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002259 Expr *Object, Expr **Args, unsigned NumArgs,
2260 OverloadCandidateSet& CandidateSet) {
2261 CandidateSet.push_back(OverloadCandidate());
2262 OverloadCandidate& Candidate = CandidateSet.back();
2263 Candidate.Function = 0;
2264 Candidate.Surrogate = Conversion;
2265 Candidate.Viable = true;
2266 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002267 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002268 Candidate.Conversions.resize(NumArgs + 1);
2269
2270 // Determine the implicit conversion sequence for the implicit
2271 // object parameter.
2272 ImplicitConversionSequence ObjectInit
2273 = TryObjectArgumentInitialization(Object, Conversion);
2274 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2275 Candidate.Viable = false;
2276 return;
2277 }
2278
2279 // The first conversion is actually a user-defined conversion whose
2280 // first conversion is ObjectInit's standard conversion (which is
2281 // effectively a reference binding). Record it as such.
2282 Candidate.Conversions[0].ConversionKind
2283 = ImplicitConversionSequence::UserDefinedConversion;
2284 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2285 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2286 Candidate.Conversions[0].UserDefined.After
2287 = Candidate.Conversions[0].UserDefined.Before;
2288 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2289
2290 // Find the
2291 unsigned NumArgsInProto = Proto->getNumArgs();
2292
2293 // (C++ 13.3.2p2): A candidate function having fewer than m
2294 // parameters is viable only if it has an ellipsis in its parameter
2295 // list (8.3.5).
2296 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2297 Candidate.Viable = false;
2298 return;
2299 }
2300
2301 // Function types don't have any default arguments, so just check if
2302 // we have enough arguments.
2303 if (NumArgs < NumArgsInProto) {
2304 // Not enough arguments.
2305 Candidate.Viable = false;
2306 return;
2307 }
2308
2309 // Determine the implicit conversion sequences for each of the
2310 // arguments.
2311 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2312 if (ArgIdx < NumArgsInProto) {
2313 // (C++ 13.3.2p3): for F to be a viable function, there shall
2314 // exist for each argument an implicit conversion sequence
2315 // (13.3.3.1) that converts that argument to the corresponding
2316 // parameter of F.
2317 QualType ParamType = Proto->getArgType(ArgIdx);
2318 Candidate.Conversions[ArgIdx + 1]
2319 = TryCopyInitialization(Args[ArgIdx], ParamType,
2320 /*SuppressUserConversions=*/false);
2321 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2322 == ImplicitConversionSequence::BadConversion) {
2323 Candidate.Viable = false;
2324 break;
2325 }
2326 } else {
2327 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2328 // argument for which there is no corresponding parameter is
2329 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2330 Candidate.Conversions[ArgIdx + 1].ConversionKind
2331 = ImplicitConversionSequence::EllipsisConversion;
2332 }
2333 }
2334}
2335
Douglas Gregor063daf62009-03-13 18:40:31 +00002336// FIXME: This will eventually be removed, once we've migrated all of
2337// the operator overloading logic over to the scheme used by binary
2338// operators, which works for template instantiation.
2339void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002340 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002341 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002342 OverloadCandidateSet& CandidateSet,
2343 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002344
2345 FunctionSet Functions;
2346
2347 QualType T1 = Args[0]->getType();
2348 QualType T2;
2349 if (NumArgs > 1)
2350 T2 = Args[1]->getType();
2351
2352 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2353 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2354 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2355 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2356 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2357 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2358}
2359
2360/// \brief Add overload candidates for overloaded operators that are
2361/// member functions.
2362///
2363/// Add the overloaded operator candidates that are member functions
2364/// for the operator Op that was used in an operator expression such
2365/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2366/// CandidateSet will store the added overload candidates. (C++
2367/// [over.match.oper]).
2368void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2369 SourceLocation OpLoc,
2370 Expr **Args, unsigned NumArgs,
2371 OverloadCandidateSet& CandidateSet,
2372 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002373 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2374
2375 // C++ [over.match.oper]p3:
2376 // For a unary operator @ with an operand of a type whose
2377 // cv-unqualified version is T1, and for a binary operator @ with
2378 // a left operand of a type whose cv-unqualified version is T1 and
2379 // a right operand of a type whose cv-unqualified version is T2,
2380 // three sets of candidate functions, designated member
2381 // candidates, non-member candidates and built-in candidates, are
2382 // constructed as follows:
2383 QualType T1 = Args[0]->getType();
2384 QualType T2;
2385 if (NumArgs > 1)
2386 T2 = Args[1]->getType();
2387
2388 // -- If T1 is a class type, the set of member candidates is the
2389 // result of the qualified lookup of T1::operator@
2390 // (13.3.1.1.1); otherwise, the set of member candidates is
2391 // empty.
Douglas Gregor063daf62009-03-13 18:40:31 +00002392 // FIXME: Lookup in base classes, too!
Douglas Gregor96176b32008-11-18 23:14:02 +00002393 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002394 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00002395 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002396 Oper != OperEnd; ++Oper)
2397 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2398 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002399 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002400 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002401}
2402
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002403/// AddBuiltinCandidate - Add a candidate for a built-in
2404/// operator. ResultTy and ParamTys are the result and parameter types
2405/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002406/// arguments being passed to the candidate. IsAssignmentOperator
2407/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002408/// operator. NumContextualBoolArguments is the number of arguments
2409/// (at the beginning of the argument list) that will be contextually
2410/// converted to bool.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002411void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2412 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002413 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002414 bool IsAssignmentOperator,
2415 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002416 // Add this candidate
2417 CandidateSet.push_back(OverloadCandidate());
2418 OverloadCandidate& Candidate = CandidateSet.back();
2419 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002420 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002421 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002422 Candidate.BuiltinTypes.ResultTy = ResultTy;
2423 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2424 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2425
2426 // Determine the implicit conversion sequences for each of the
2427 // arguments.
2428 Candidate.Viable = true;
2429 Candidate.Conversions.resize(NumArgs);
2430 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002431 // C++ [over.match.oper]p4:
2432 // For the built-in assignment operators, conversions of the
2433 // left operand are restricted as follows:
2434 // -- no temporaries are introduced to hold the left operand, and
2435 // -- no user-defined conversions are applied to the left
2436 // operand to achieve a type match with the left-most
2437 // parameter of a built-in candidate.
2438 //
2439 // We block these conversions by turning off user-defined
2440 // conversions, since that is the only way that initialization of
2441 // a reference to a non-class type can occur from something that
2442 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002443 if (ArgIdx < NumContextualBoolArguments) {
2444 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2445 "Contextual conversion to bool requires bool type");
2446 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2447 } else {
2448 Candidate.Conversions[ArgIdx]
2449 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2450 ArgIdx == 0 && IsAssignmentOperator);
2451 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002452 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002453 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002454 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002455 break;
2456 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002457 }
2458}
2459
2460/// BuiltinCandidateTypeSet - A set of types that will be used for the
2461/// candidate operator functions for built-in operators (C++
2462/// [over.built]). The types are separated into pointer types and
2463/// enumeration types.
2464class BuiltinCandidateTypeSet {
2465 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002466 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002467
2468 /// PointerTypes - The set of pointer types that will be used in the
2469 /// built-in candidates.
2470 TypeSet PointerTypes;
2471
2472 /// EnumerationTypes - The set of enumeration types that will be
2473 /// used in the built-in candidates.
2474 TypeSet EnumerationTypes;
2475
2476 /// Context - The AST context in which we will build the type sets.
2477 ASTContext &Context;
2478
2479 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2480
2481public:
2482 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002483 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002484
2485 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2486
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002487 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2488 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002489
2490 /// pointer_begin - First pointer type found;
2491 iterator pointer_begin() { return PointerTypes.begin(); }
2492
2493 /// pointer_end - Last pointer type found;
2494 iterator pointer_end() { return PointerTypes.end(); }
2495
2496 /// enumeration_begin - First enumeration type found;
2497 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2498
2499 /// enumeration_end - Last enumeration type found;
2500 iterator enumeration_end() { return EnumerationTypes.end(); }
2501};
2502
2503/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2504/// the set of pointer types along with any more-qualified variants of
2505/// that type. For example, if @p Ty is "int const *", this routine
2506/// will add "int const *", "int const volatile *", "int const
2507/// restrict *", and "int const volatile restrict *" to the set of
2508/// pointer types. Returns true if the add of @p Ty itself succeeded,
2509/// false otherwise.
2510bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2511 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002512 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002513 return false;
2514
2515 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2516 QualType PointeeTy = PointerTy->getPointeeType();
2517 // FIXME: Optimize this so that we don't keep trying to add the same types.
2518
2519 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2520 // with all pointer conversions that don't cast away constness?
2521 if (!PointeeTy.isConstQualified())
2522 AddWithMoreQualifiedTypeVariants
2523 (Context.getPointerType(PointeeTy.withConst()));
2524 if (!PointeeTy.isVolatileQualified())
2525 AddWithMoreQualifiedTypeVariants
2526 (Context.getPointerType(PointeeTy.withVolatile()));
2527 if (!PointeeTy.isRestrictQualified())
2528 AddWithMoreQualifiedTypeVariants
2529 (Context.getPointerType(PointeeTy.withRestrict()));
2530 }
2531
2532 return true;
2533}
2534
2535/// AddTypesConvertedFrom - Add each of the types to which the type @p
2536/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002537/// primarily interested in pointer types and enumeration types.
2538/// AllowUserConversions is true if we should look at the conversion
2539/// functions of a class type, and AllowExplicitConversions if we
2540/// should also include the explicit conversion functions of a class
2541/// type.
2542void
2543BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2544 bool AllowUserConversions,
2545 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002546 // Only deal with canonical types.
2547 Ty = Context.getCanonicalType(Ty);
2548
2549 // Look through reference types; they aren't part of the type of an
2550 // expression for the purposes of conversions.
2551 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2552 Ty = RefTy->getPointeeType();
2553
2554 // We don't care about qualifiers on the type.
2555 Ty = Ty.getUnqualifiedType();
2556
2557 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2558 QualType PointeeTy = PointerTy->getPointeeType();
2559
2560 // Insert our type, and its more-qualified variants, into the set
2561 // of types.
2562 if (!AddWithMoreQualifiedTypeVariants(Ty))
2563 return;
2564
2565 // Add 'cv void*' to our set of types.
2566 if (!Ty->isVoidType()) {
2567 QualType QualVoid
2568 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2569 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2570 }
2571
2572 // If this is a pointer to a class type, add pointers to its bases
2573 // (with the same level of cv-qualification as the original
2574 // derived class, of course).
2575 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2576 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2577 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2578 Base != ClassDecl->bases_end(); ++Base) {
2579 QualType BaseTy = Context.getCanonicalType(Base->getType());
2580 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2581
2582 // Add the pointer type, recursively, so that we get all of
2583 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002584 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002585 }
2586 }
2587 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00002588 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002589 } else if (AllowUserConversions) {
2590 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2591 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2592 // FIXME: Visit conversion functions in the base classes, too.
2593 OverloadedFunctionDecl *Conversions
2594 = ClassDecl->getConversionFunctions();
2595 for (OverloadedFunctionDecl::function_iterator Func
2596 = Conversions->function_begin();
2597 Func != Conversions->function_end(); ++Func) {
2598 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002599 if (AllowExplicitConversions || !Conv->isExplicit())
2600 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002601 }
2602 }
2603 }
2604}
2605
Douglas Gregor74253732008-11-19 15:42:04 +00002606/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2607/// operator overloads to the candidate set (C++ [over.built]), based
2608/// on the operator @p Op and the arguments given. For example, if the
2609/// operator is a binary '+', this routine might add "int
2610/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002611void
Douglas Gregor74253732008-11-19 15:42:04 +00002612Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2613 Expr **Args, unsigned NumArgs,
2614 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002615 // The set of "promoted arithmetic types", which are the arithmetic
2616 // types are that preserved by promotion (C++ [over.built]p2). Note
2617 // that the first few of these types are the promoted integral
2618 // types; these types need to be first.
2619 // FIXME: What about complex?
2620 const unsigned FirstIntegralType = 0;
2621 const unsigned LastIntegralType = 13;
2622 const unsigned FirstPromotedIntegralType = 7,
2623 LastPromotedIntegralType = 13;
2624 const unsigned FirstPromotedArithmeticType = 7,
2625 LastPromotedArithmeticType = 16;
2626 const unsigned NumArithmeticTypes = 16;
2627 QualType ArithmeticTypes[NumArithmeticTypes] = {
2628 Context.BoolTy, Context.CharTy, Context.WCharTy,
2629 Context.SignedCharTy, Context.ShortTy,
2630 Context.UnsignedCharTy, Context.UnsignedShortTy,
2631 Context.IntTy, Context.LongTy, Context.LongLongTy,
2632 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2633 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2634 };
2635
2636 // Find all of the types that the arguments can convert to, but only
2637 // if the operator we're looking at has built-in operator candidates
2638 // that make use of these types.
2639 BuiltinCandidateTypeSet CandidateTypes(Context);
2640 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2641 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002642 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002643 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002644 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2645 (Op == OO_Star && NumArgs == 1)) {
2646 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002647 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2648 true,
2649 (Op == OO_Exclaim ||
2650 Op == OO_AmpAmp ||
2651 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002652 }
2653
2654 bool isComparison = false;
2655 switch (Op) {
2656 case OO_None:
2657 case NUM_OVERLOADED_OPERATORS:
2658 assert(false && "Expected an overloaded operator");
2659 break;
2660
Douglas Gregor74253732008-11-19 15:42:04 +00002661 case OO_Star: // '*' is either unary or binary
2662 if (NumArgs == 1)
2663 goto UnaryStar;
2664 else
2665 goto BinaryStar;
2666 break;
2667
2668 case OO_Plus: // '+' is either unary or binary
2669 if (NumArgs == 1)
2670 goto UnaryPlus;
2671 else
2672 goto BinaryPlus;
2673 break;
2674
2675 case OO_Minus: // '-' is either unary or binary
2676 if (NumArgs == 1)
2677 goto UnaryMinus;
2678 else
2679 goto BinaryMinus;
2680 break;
2681
2682 case OO_Amp: // '&' is either unary or binary
2683 if (NumArgs == 1)
2684 goto UnaryAmp;
2685 else
2686 goto BinaryAmp;
2687
2688 case OO_PlusPlus:
2689 case OO_MinusMinus:
2690 // C++ [over.built]p3:
2691 //
2692 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2693 // is either volatile or empty, there exist candidate operator
2694 // functions of the form
2695 //
2696 // VQ T& operator++(VQ T&);
2697 // T operator++(VQ T&, int);
2698 //
2699 // C++ [over.built]p4:
2700 //
2701 // For every pair (T, VQ), where T is an arithmetic type other
2702 // than bool, and VQ is either volatile or empty, there exist
2703 // candidate operator functions of the form
2704 //
2705 // VQ T& operator--(VQ T&);
2706 // T operator--(VQ T&, int);
2707 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2708 Arith < NumArithmeticTypes; ++Arith) {
2709 QualType ArithTy = ArithmeticTypes[Arith];
2710 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002711 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00002712
2713 // Non-volatile version.
2714 if (NumArgs == 1)
2715 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2716 else
2717 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2718
2719 // Volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002720 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00002721 if (NumArgs == 1)
2722 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2723 else
2724 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2725 }
2726
2727 // C++ [over.built]p5:
2728 //
2729 // For every pair (T, VQ), where T is a cv-qualified or
2730 // cv-unqualified object type, and VQ is either volatile or
2731 // empty, there exist candidate operator functions of the form
2732 //
2733 // T*VQ& operator++(T*VQ&);
2734 // T*VQ& operator--(T*VQ&);
2735 // T* operator++(T*VQ&, int);
2736 // T* operator--(T*VQ&, int);
2737 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2738 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2739 // Skip pointer types that aren't pointers to object types.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002740 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002741 continue;
2742
2743 QualType ParamTypes[2] = {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002744 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00002745 };
2746
2747 // Without volatile
2748 if (NumArgs == 1)
2749 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2750 else
2751 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2752
2753 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2754 // With volatile
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002755 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00002756 if (NumArgs == 1)
2757 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2758 else
2759 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2760 }
2761 }
2762 break;
2763
2764 UnaryStar:
2765 // C++ [over.built]p6:
2766 // For every cv-qualified or cv-unqualified object type T, there
2767 // exist candidate operator functions of the form
2768 //
2769 // T& operator*(T*);
2770 //
2771 // C++ [over.built]p7:
2772 // For every function type T, there exist candidate operator
2773 // functions of the form
2774 // T& operator*(T*);
2775 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2776 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2777 QualType ParamTy = *Ptr;
2778 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002779 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00002780 &ParamTy, Args, 1, CandidateSet);
2781 }
2782 break;
2783
2784 UnaryPlus:
2785 // C++ [over.built]p8:
2786 // For every type T, there exist candidate operator functions of
2787 // the form
2788 //
2789 // T* operator+(T*);
2790 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2791 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2792 QualType ParamTy = *Ptr;
2793 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2794 }
2795
2796 // Fall through
2797
2798 UnaryMinus:
2799 // C++ [over.built]p9:
2800 // For every promoted arithmetic type T, there exist candidate
2801 // operator functions of the form
2802 //
2803 // T operator+(T);
2804 // T operator-(T);
2805 for (unsigned Arith = FirstPromotedArithmeticType;
2806 Arith < LastPromotedArithmeticType; ++Arith) {
2807 QualType ArithTy = ArithmeticTypes[Arith];
2808 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2809 }
2810 break;
2811
2812 case OO_Tilde:
2813 // C++ [over.built]p10:
2814 // For every promoted integral type T, there exist candidate
2815 // operator functions of the form
2816 //
2817 // T operator~(T);
2818 for (unsigned Int = FirstPromotedIntegralType;
2819 Int < LastPromotedIntegralType; ++Int) {
2820 QualType IntTy = ArithmeticTypes[Int];
2821 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2822 }
2823 break;
2824
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002825 case OO_New:
2826 case OO_Delete:
2827 case OO_Array_New:
2828 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002829 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002830 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002831 break;
2832
2833 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002834 UnaryAmp:
2835 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002836 // C++ [over.match.oper]p3:
2837 // -- For the operator ',', the unary operator '&', or the
2838 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002839 break;
2840
2841 case OO_Less:
2842 case OO_Greater:
2843 case OO_LessEqual:
2844 case OO_GreaterEqual:
2845 case OO_EqualEqual:
2846 case OO_ExclaimEqual:
2847 // C++ [over.built]p15:
2848 //
2849 // For every pointer or enumeration type T, there exist
2850 // candidate operator functions of the form
2851 //
2852 // bool operator<(T, T);
2853 // bool operator>(T, T);
2854 // bool operator<=(T, T);
2855 // bool operator>=(T, T);
2856 // bool operator==(T, T);
2857 // bool operator!=(T, T);
2858 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2859 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2860 QualType ParamTypes[2] = { *Ptr, *Ptr };
2861 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2862 }
2863 for (BuiltinCandidateTypeSet::iterator Enum
2864 = CandidateTypes.enumeration_begin();
2865 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2866 QualType ParamTypes[2] = { *Enum, *Enum };
2867 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2868 }
2869
2870 // Fall through.
2871 isComparison = true;
2872
Douglas Gregor74253732008-11-19 15:42:04 +00002873 BinaryPlus:
2874 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002875 if (!isComparison) {
2876 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2877
2878 // C++ [over.built]p13:
2879 //
2880 // For every cv-qualified or cv-unqualified object type T
2881 // there exist candidate operator functions of the form
2882 //
2883 // T* operator+(T*, ptrdiff_t);
2884 // T& operator[](T*, ptrdiff_t); [BELOW]
2885 // T* operator-(T*, ptrdiff_t);
2886 // T* operator+(ptrdiff_t, T*);
2887 // T& operator[](ptrdiff_t, T*); [BELOW]
2888 //
2889 // C++ [over.built]p14:
2890 //
2891 // For every T, where T is a pointer to object type, there
2892 // exist candidate operator functions of the form
2893 //
2894 // ptrdiff_t operator-(T, T);
2895 for (BuiltinCandidateTypeSet::iterator Ptr
2896 = CandidateTypes.pointer_begin();
2897 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2898 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2899
2900 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2901 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2902
2903 if (Op == OO_Plus) {
2904 // T* operator+(ptrdiff_t, T*);
2905 ParamTypes[0] = ParamTypes[1];
2906 ParamTypes[1] = *Ptr;
2907 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2908 } else {
2909 // ptrdiff_t operator-(T, T);
2910 ParamTypes[1] = *Ptr;
2911 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2912 Args, 2, CandidateSet);
2913 }
2914 }
2915 }
2916 // Fall through
2917
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002918 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002919 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002920 // C++ [over.built]p12:
2921 //
2922 // For every pair of promoted arithmetic types L and R, there
2923 // exist candidate operator functions of the form
2924 //
2925 // LR operator*(L, R);
2926 // LR operator/(L, R);
2927 // LR operator+(L, R);
2928 // LR operator-(L, R);
2929 // bool operator<(L, R);
2930 // bool operator>(L, R);
2931 // bool operator<=(L, R);
2932 // bool operator>=(L, R);
2933 // bool operator==(L, R);
2934 // bool operator!=(L, R);
2935 //
2936 // where LR is the result of the usual arithmetic conversions
2937 // between types L and R.
2938 for (unsigned Left = FirstPromotedArithmeticType;
2939 Left < LastPromotedArithmeticType; ++Left) {
2940 for (unsigned Right = FirstPromotedArithmeticType;
2941 Right < LastPromotedArithmeticType; ++Right) {
2942 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2943 QualType Result
2944 = isComparison? Context.BoolTy
2945 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2946 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2947 }
2948 }
2949 break;
2950
2951 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002952 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002953 case OO_Caret:
2954 case OO_Pipe:
2955 case OO_LessLess:
2956 case OO_GreaterGreater:
2957 // C++ [over.built]p17:
2958 //
2959 // For every pair of promoted integral types L and R, there
2960 // exist candidate operator functions of the form
2961 //
2962 // LR operator%(L, R);
2963 // LR operator&(L, R);
2964 // LR operator^(L, R);
2965 // LR operator|(L, R);
2966 // L operator<<(L, R);
2967 // L operator>>(L, R);
2968 //
2969 // where LR is the result of the usual arithmetic conversions
2970 // between types L and R.
2971 for (unsigned Left = FirstPromotedIntegralType;
2972 Left < LastPromotedIntegralType; ++Left) {
2973 for (unsigned Right = FirstPromotedIntegralType;
2974 Right < LastPromotedIntegralType; ++Right) {
2975 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2976 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2977 ? LandR[0]
2978 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2979 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2980 }
2981 }
2982 break;
2983
2984 case OO_Equal:
2985 // C++ [over.built]p20:
2986 //
2987 // For every pair (T, VQ), where T is an enumeration or
2988 // (FIXME:) pointer to member type and VQ is either volatile or
2989 // empty, there exist candidate operator functions of the form
2990 //
2991 // VQ T& operator=(VQ T&, T);
2992 for (BuiltinCandidateTypeSet::iterator Enum
2993 = CandidateTypes.enumeration_begin();
2994 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2995 QualType ParamTypes[2];
2996
2997 // T& operator=(T&, T)
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002998 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002999 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003000 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003001 /*IsAssignmentOperator=*/false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003002
Douglas Gregor74253732008-11-19 15:42:04 +00003003 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3004 // volatile T& operator=(volatile T&, T)
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003005 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00003006 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003007 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003008 /*IsAssignmentOperator=*/false);
Douglas Gregor74253732008-11-19 15:42:04 +00003009 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003010 }
3011 // Fall through.
3012
3013 case OO_PlusEqual:
3014 case OO_MinusEqual:
3015 // C++ [over.built]p19:
3016 //
3017 // For every pair (T, VQ), where T is any type and VQ is either
3018 // volatile or empty, there exist candidate operator functions
3019 // of the form
3020 //
3021 // T*VQ& operator=(T*VQ&, T*);
3022 //
3023 // C++ [over.built]p21:
3024 //
3025 // For every pair (T, VQ), where T is a cv-qualified or
3026 // cv-unqualified object type and VQ is either volatile or
3027 // empty, there exist candidate operator functions of the form
3028 //
3029 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3030 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3031 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3032 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3033 QualType ParamTypes[2];
3034 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3035
3036 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003037 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003038 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3039 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003040
Douglas Gregor74253732008-11-19 15:42:04 +00003041 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3042 // volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003043 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003044 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3045 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003046 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003047 }
3048 // Fall through.
3049
3050 case OO_StarEqual:
3051 case OO_SlashEqual:
3052 // C++ [over.built]p18:
3053 //
3054 // For every triple (L, VQ, R), where L is an arithmetic type,
3055 // VQ is either volatile or empty, and R is a promoted
3056 // arithmetic type, there exist candidate operator functions of
3057 // the form
3058 //
3059 // VQ L& operator=(VQ L&, R);
3060 // VQ L& operator*=(VQ L&, R);
3061 // VQ L& operator/=(VQ L&, R);
3062 // VQ L& operator+=(VQ L&, R);
3063 // VQ L& operator-=(VQ L&, R);
3064 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3065 for (unsigned Right = FirstPromotedArithmeticType;
3066 Right < LastPromotedArithmeticType; ++Right) {
3067 QualType ParamTypes[2];
3068 ParamTypes[1] = ArithmeticTypes[Right];
3069
3070 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003071 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003072 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3073 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003074
3075 // Add this built-in operator as a candidate (VQ is 'volatile').
3076 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003077 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003078 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3079 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003080 }
3081 }
3082 break;
3083
3084 case OO_PercentEqual:
3085 case OO_LessLessEqual:
3086 case OO_GreaterGreaterEqual:
3087 case OO_AmpEqual:
3088 case OO_CaretEqual:
3089 case OO_PipeEqual:
3090 // C++ [over.built]p22:
3091 //
3092 // For every triple (L, VQ, R), where L is an integral type, VQ
3093 // is either volatile or empty, and R is a promoted integral
3094 // type, there exist candidate operator functions of the form
3095 //
3096 // VQ L& operator%=(VQ L&, R);
3097 // VQ L& operator<<=(VQ L&, R);
3098 // VQ L& operator>>=(VQ L&, R);
3099 // VQ L& operator&=(VQ L&, R);
3100 // VQ L& operator^=(VQ L&, R);
3101 // VQ L& operator|=(VQ L&, R);
3102 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3103 for (unsigned Right = FirstPromotedIntegralType;
3104 Right < LastPromotedIntegralType; ++Right) {
3105 QualType ParamTypes[2];
3106 ParamTypes[1] = ArithmeticTypes[Right];
3107
3108 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003109 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003110 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3111
3112 // Add this built-in operator as a candidate (VQ is 'volatile').
3113 ParamTypes[0] = ArithmeticTypes[Left];
3114 ParamTypes[0].addVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003115 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003116 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3117 }
3118 }
3119 break;
3120
Douglas Gregor74253732008-11-19 15:42:04 +00003121 case OO_Exclaim: {
3122 // C++ [over.operator]p23:
3123 //
3124 // There also exist candidate operator functions of the form
3125 //
3126 // bool operator!(bool);
3127 // bool operator&&(bool, bool); [BELOW]
3128 // bool operator||(bool, bool); [BELOW]
3129 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003130 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3131 /*IsAssignmentOperator=*/false,
3132 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003133 break;
3134 }
3135
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003136 case OO_AmpAmp:
3137 case OO_PipePipe: {
3138 // C++ [over.operator]p23:
3139 //
3140 // There also exist candidate operator functions of the form
3141 //
Douglas Gregor74253732008-11-19 15:42:04 +00003142 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003143 // bool operator&&(bool, bool);
3144 // bool operator||(bool, bool);
3145 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003146 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3147 /*IsAssignmentOperator=*/false,
3148 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003149 break;
3150 }
3151
3152 case OO_Subscript:
3153 // C++ [over.built]p13:
3154 //
3155 // For every cv-qualified or cv-unqualified object type T there
3156 // exist candidate operator functions of the form
3157 //
3158 // T* operator+(T*, ptrdiff_t); [ABOVE]
3159 // T& operator[](T*, ptrdiff_t);
3160 // T* operator-(T*, ptrdiff_t); [ABOVE]
3161 // T* operator+(ptrdiff_t, T*); [ABOVE]
3162 // T& operator[](ptrdiff_t, T*);
3163 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3164 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3165 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3166 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003167 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003168
3169 // T& operator[](T*, ptrdiff_t)
3170 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3171
3172 // T& operator[](ptrdiff_t, T*);
3173 ParamTypes[0] = ParamTypes[1];
3174 ParamTypes[1] = *Ptr;
3175 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3176 }
3177 break;
3178
3179 case OO_ArrowStar:
3180 // FIXME: No support for pointer-to-members yet.
3181 break;
3182 }
3183}
3184
Douglas Gregorfa047642009-02-04 00:32:51 +00003185/// \brief Add function candidates found via argument-dependent lookup
3186/// to the set of overloading candidates.
3187///
3188/// This routine performs argument-dependent name lookup based on the
3189/// given function name (which may also be an operator name) and adds
3190/// all of the overload candidates found by ADL to the overload
3191/// candidate set (C++ [basic.lookup.argdep]).
3192void
3193Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3194 Expr **Args, unsigned NumArgs,
3195 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003196 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00003197
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003198 // Record all of the function candidates that we've already
3199 // added to the overload set, so that we don't add those same
3200 // candidates a second time.
3201 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3202 CandEnd = CandidateSet.end();
3203 Cand != CandEnd; ++Cand)
3204 if (Cand->Function)
3205 Functions.insert(Cand->Function);
Douglas Gregorfa047642009-02-04 00:32:51 +00003206
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003207 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00003208
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003209 // Erase all of the candidates we already knew about.
3210 // FIXME: This is suboptimal. Is there a better way?
3211 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3212 CandEnd = CandidateSet.end();
3213 Cand != CandEnd; ++Cand)
3214 if (Cand->Function)
3215 Functions.erase(Cand->Function);
3216
3217 // For each of the ADL candidates we found, add it to the overload
3218 // set.
3219 for (FunctionSet::iterator Func = Functions.begin(),
3220 FuncEnd = Functions.end();
3221 Func != FuncEnd; ++Func)
3222 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
Douglas Gregorfa047642009-02-04 00:32:51 +00003223}
3224
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003225/// isBetterOverloadCandidate - Determines whether the first overload
3226/// candidate is a better candidate than the second (C++ 13.3.3p1).
3227bool
3228Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3229 const OverloadCandidate& Cand2)
3230{
3231 // Define viable functions to be better candidates than non-viable
3232 // functions.
3233 if (!Cand2.Viable)
3234 return Cand1.Viable;
3235 else if (!Cand1.Viable)
3236 return false;
3237
Douglas Gregor88a35142008-12-22 05:46:06 +00003238 // C++ [over.match.best]p1:
3239 //
3240 // -- if F is a static member function, ICS1(F) is defined such
3241 // that ICS1(F) is neither better nor worse than ICS1(G) for
3242 // any function G, and, symmetrically, ICS1(G) is neither
3243 // better nor worse than ICS1(F).
3244 unsigned StartArg = 0;
3245 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3246 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003247
3248 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3249 // function than another viable function F2 if for all arguments i,
3250 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3251 // then...
3252 unsigned NumArgs = Cand1.Conversions.size();
3253 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3254 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003255 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003256 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3257 Cand2.Conversions[ArgIdx])) {
3258 case ImplicitConversionSequence::Better:
3259 // Cand1 has a better conversion sequence.
3260 HasBetterConversion = true;
3261 break;
3262
3263 case ImplicitConversionSequence::Worse:
3264 // Cand1 can't be better than Cand2.
3265 return false;
3266
3267 case ImplicitConversionSequence::Indistinguishable:
3268 // Do nothing.
3269 break;
3270 }
3271 }
3272
3273 if (HasBetterConversion)
3274 return true;
3275
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003276 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3277 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003278
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003279 // C++ [over.match.best]p1b4:
3280 //
3281 // -- the context is an initialization by user-defined conversion
3282 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3283 // from the return type of F1 to the destination type (i.e.,
3284 // the type of the entity being initialized) is a better
3285 // conversion sequence than the standard conversion sequence
3286 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003287 if (Cand1.Function && Cand2.Function &&
3288 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003289 isa<CXXConversionDecl>(Cand2.Function)) {
3290 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3291 Cand2.FinalConversion)) {
3292 case ImplicitConversionSequence::Better:
3293 // Cand1 has a better conversion sequence.
3294 return true;
3295
3296 case ImplicitConversionSequence::Worse:
3297 // Cand1 can't be better than Cand2.
3298 return false;
3299
3300 case ImplicitConversionSequence::Indistinguishable:
3301 // Do nothing
3302 break;
3303 }
3304 }
3305
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003306 return false;
3307}
3308
3309/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3310/// within an overload candidate set. If overloading is successful,
3311/// the result will be OR_Success and Best will be set to point to the
3312/// best viable function within the candidate set. Otherwise, one of
3313/// several kinds of errors will be returned; see
3314/// Sema::OverloadingResult.
3315Sema::OverloadingResult
3316Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3317 OverloadCandidateSet::iterator& Best)
3318{
3319 // Find the best viable function.
3320 Best = CandidateSet.end();
3321 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3322 Cand != CandidateSet.end(); ++Cand) {
3323 if (Cand->Viable) {
3324 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3325 Best = Cand;
3326 }
3327 }
3328
3329 // If we didn't find any viable functions, abort.
3330 if (Best == CandidateSet.end())
3331 return OR_No_Viable_Function;
3332
3333 // Make sure that this function is better than every other viable
3334 // function. If not, we have an ambiguity.
3335 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3336 Cand != CandidateSet.end(); ++Cand) {
3337 if (Cand->Viable &&
3338 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003339 !isBetterOverloadCandidate(*Best, *Cand)) {
3340 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003341 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003342 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003343 }
3344
3345 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003346 if (Best->Function &&
3347 (Best->Function->isDeleted() ||
3348 Best->Function->getAttr<UnavailableAttr>()))
3349 return OR_Deleted;
3350
3351 // If Best refers to a function that is either deleted (C++0x) or
3352 // unavailable (Clang extension) report an error.
3353
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003354 return OR_Success;
3355}
3356
3357/// PrintOverloadCandidates - When overload resolution fails, prints
3358/// diagnostic messages containing the candidates in the candidate
3359/// set. If OnlyViable is true, only viable candidates will be printed.
3360void
3361Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3362 bool OnlyViable)
3363{
3364 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3365 LastCand = CandidateSet.end();
3366 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003367 if (Cand->Viable || !OnlyViable) {
3368 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003369 if (Cand->Function->isDeleted() ||
3370 Cand->Function->getAttr<UnavailableAttr>()) {
3371 // Deleted or "unavailable" function.
3372 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3373 << Cand->Function->isDeleted();
3374 } else {
3375 // Normal function
3376 // FIXME: Give a better reason!
3377 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3378 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003379 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003380 // Desugar the type of the surrogate down to a function type,
3381 // retaining as many typedefs as possible while still showing
3382 // the function type (and, therefore, its parameter types).
3383 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003384 bool isLValueReference = false;
3385 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00003386 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003387 if (const LValueReferenceType *FnTypeRef =
3388 FnType->getAsLValueReferenceType()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003389 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003390 isLValueReference = true;
3391 } else if (const RValueReferenceType *FnTypeRef =
3392 FnType->getAsRValueReferenceType()) {
3393 FnType = FnTypeRef->getPointeeType();
3394 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00003395 }
3396 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3397 FnType = FnTypePtr->getPointeeType();
3398 isPointer = true;
3399 }
3400 // Desugar down to a function type.
3401 FnType = QualType(FnType->getAsFunctionType(), 0);
3402 // Reconstruct the pointer/reference as appropriate.
3403 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003404 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3405 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00003406
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003407 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003408 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003409 } else {
3410 // FIXME: We need to get the identifier in here
3411 // FIXME: Do we want the error message to point at the
3412 // operator? (built-ins won't have a location)
3413 QualType FnType
3414 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3415 Cand->BuiltinTypes.ParamTypes,
3416 Cand->Conversions.size(),
3417 false, 0);
3418
Chris Lattnerd1625842008-11-24 06:25:27 +00003419 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003420 }
3421 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003422 }
3423}
3424
Douglas Gregor904eed32008-11-10 20:40:00 +00003425/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3426/// an overloaded function (C++ [over.over]), where @p From is an
3427/// expression with overloaded function type and @p ToType is the type
3428/// we're trying to resolve to. For example:
3429///
3430/// @code
3431/// int f(double);
3432/// int f(int);
3433///
3434/// int (*pfd)(double) = f; // selects f(double)
3435/// @endcode
3436///
3437/// This routine returns the resulting FunctionDecl if it could be
3438/// resolved, and NULL otherwise. When @p Complain is true, this
3439/// routine will emit diagnostics if there is an error.
3440FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00003441Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003442 bool Complain) {
3443 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003444 bool IsMember = false;
Daniel Dunbarbb710012009-02-26 19:13:44 +00003445 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
Douglas Gregor904eed32008-11-10 20:40:00 +00003446 FunctionType = ToTypePtr->getPointeeType();
Daniel Dunbarbb710012009-02-26 19:13:44 +00003447 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3448 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00003449 else if (const MemberPointerType *MemTypePtr =
3450 ToType->getAsMemberPointerType()) {
3451 FunctionType = MemTypePtr->getPointeeType();
3452 IsMember = true;
3453 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003454
3455 // We only look at pointers or references to functions.
3456 if (!FunctionType->isFunctionType())
3457 return 0;
3458
3459 // Find the actual overloaded function declaration.
3460 OverloadedFunctionDecl *Ovl = 0;
3461
3462 // C++ [over.over]p1:
3463 // [...] [Note: any redundant set of parentheses surrounding the
3464 // overloaded function name is ignored (5.1). ]
3465 Expr *OvlExpr = From->IgnoreParens();
3466
3467 // C++ [over.over]p1:
3468 // [...] The overloaded function name can be preceded by the &
3469 // operator.
3470 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3471 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3472 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3473 }
3474
3475 // Try to dig out the overloaded function.
3476 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3477 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3478
3479 // If there's no overloaded function declaration, we're done.
3480 if (!Ovl)
3481 return 0;
3482
3483 // Look through all of the overloaded functions, searching for one
3484 // whose type matches exactly.
3485 // FIXME: When templates or using declarations come along, we'll actually
3486 // have to deal with duplicates, partial ordering, etc. For now, we
3487 // can just do a simple search.
3488 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3489 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3490 Fun != Ovl->function_end(); ++Fun) {
3491 // C++ [over.over]p3:
3492 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00003493 // targets of type "pointer-to-function" or "reference-to-function."
3494 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00003495 // type "pointer-to-member-function."
3496 // Note that according to DR 247, the containing class does not matter.
3497 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3498 // Skip non-static functions when converting to pointer, and static
3499 // when converting to member pointer.
3500 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00003501 continue;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003502 } else if (IsMember)
3503 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00003504
3505 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3506 return *Fun;
3507 }
3508
3509 return 0;
3510}
3511
Douglas Gregorf6b89692008-11-26 05:54:23 +00003512/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00003513/// (which eventually refers to the declaration Func) and the call
3514/// arguments Args/NumArgs, attempt to resolve the function call down
3515/// to a specific function. If overload resolution succeeds, returns
3516/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00003517/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003518/// arguments and Fn, and returns NULL.
Douglas Gregorfa047642009-02-04 00:32:51 +00003519FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor17330012009-02-04 15:01:18 +00003520 DeclarationName UnqualifiedName,
Douglas Gregor0a396682008-11-26 06:01:48 +00003521 SourceLocation LParenLoc,
3522 Expr **Args, unsigned NumArgs,
3523 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003524 SourceLocation RParenLoc,
Douglas Gregor17330012009-02-04 15:01:18 +00003525 bool &ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003526 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00003527
3528 // Add the functions denoted by Callee to the set of candidate
3529 // functions. While we're doing so, track whether argument-dependent
3530 // lookup still applies, per:
3531 //
3532 // C++0x [basic.lookup.argdep]p3:
3533 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3534 // and let Y be the lookup set produced by argument dependent
3535 // lookup (defined as follows). If X contains
3536 //
3537 // -- a declaration of a class member, or
3538 //
3539 // -- a block-scope function declaration that is not a
3540 // using-declaration, or
3541 //
3542 // -- a declaration that is neither a function or a function
3543 // template
3544 //
3545 // then Y is empty.
Douglas Gregorfa047642009-02-04 00:32:51 +00003546 if (OverloadedFunctionDecl *Ovl
Douglas Gregor17330012009-02-04 15:01:18 +00003547 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3548 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3549 FuncEnd = Ovl->function_end();
3550 Func != FuncEnd; ++Func) {
3551 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3552
3553 if ((*Func)->getDeclContext()->isRecord() ||
3554 (*Func)->getDeclContext()->isFunctionOrMethod())
3555 ArgumentDependentLookup = false;
3556 }
3557 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3558 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3559
3560 if (Func->getDeclContext()->isRecord() ||
3561 Func->getDeclContext()->isFunctionOrMethod())
3562 ArgumentDependentLookup = false;
3563 }
3564
3565 if (Callee)
3566 UnqualifiedName = Callee->getDeclName();
3567
Douglas Gregorfa047642009-02-04 00:32:51 +00003568 if (ArgumentDependentLookup)
Douglas Gregor17330012009-02-04 15:01:18 +00003569 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003570 CandidateSet);
3571
Douglas Gregorf6b89692008-11-26 05:54:23 +00003572 OverloadCandidateSet::iterator Best;
3573 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003574 case OR_Success:
3575 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003576
3577 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00003578 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00003579 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00003580 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00003581 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3582 break;
3583
3584 case OR_Ambiguous:
3585 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00003586 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00003587 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3588 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003589
3590 case OR_Deleted:
3591 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3592 << Best->Function->isDeleted()
3593 << UnqualifiedName
3594 << Fn->getSourceRange();
3595 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3596 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003597 }
3598
3599 // Overload resolution failed. Destroy all of the subexpressions and
3600 // return NULL.
3601 Fn->Destroy(Context);
3602 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3603 Args[Arg]->Destroy(Context);
3604 return 0;
3605}
3606
Douglas Gregorbc736fc2009-03-13 23:49:33 +00003607/// \brief Create a unary operation that may resolve to an overloaded
3608/// operator.
3609///
3610/// \param OpLoc The location of the operator itself (e.g., '*').
3611///
3612/// \param OpcIn The UnaryOperator::Opcode that describes this
3613/// operator.
3614///
3615/// \param Functions The set of non-member functions that will be
3616/// considered by overload resolution. The caller needs to build this
3617/// set based on the context using, e.g.,
3618/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3619/// set should not contain any member functions; those will be added
3620/// by CreateOverloadedUnaryOp().
3621///
3622/// \param input The input argument.
3623Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3624 unsigned OpcIn,
3625 FunctionSet &Functions,
3626 ExprArg input) {
3627 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3628 Expr *Input = (Expr *)input.get();
3629
3630 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3631 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3632 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3633
3634 Expr *Args[2] = { Input, 0 };
3635 unsigned NumArgs = 1;
3636
3637 // For post-increment and post-decrement, add the implicit '0' as
3638 // the second argument, so that we know this is a post-increment or
3639 // post-decrement.
3640 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3641 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3642 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3643 SourceLocation());
3644 NumArgs = 2;
3645 }
3646
3647 if (Input->isTypeDependent()) {
3648 OverloadedFunctionDecl *Overloads
3649 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3650 for (FunctionSet::iterator Func = Functions.begin(),
3651 FuncEnd = Functions.end();
3652 Func != FuncEnd; ++Func)
3653 Overloads->addOverload(*Func);
3654
3655 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3656 OpLoc, false, false);
3657
3658 input.release();
3659 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3660 &Args[0], NumArgs,
3661 Context.DependentTy,
3662 OpLoc));
3663 }
3664
3665 // Build an empty overload set.
3666 OverloadCandidateSet CandidateSet;
3667
3668 // Add the candidates from the given function set.
3669 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3670
3671 // Add operator candidates that are member functions.
3672 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3673
3674 // Add builtin operator candidates.
3675 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3676
3677 // Perform overload resolution.
3678 OverloadCandidateSet::iterator Best;
3679 switch (BestViableFunction(CandidateSet, Best)) {
3680 case OR_Success: {
3681 // We found a built-in operator or an overloaded operator.
3682 FunctionDecl *FnDecl = Best->Function;
3683
3684 if (FnDecl) {
3685 // We matched an overloaded operator. Build a call to that
3686 // operator.
3687
3688 // Convert the arguments.
3689 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3690 if (PerformObjectArgumentInitialization(Input, Method))
3691 return ExprError();
3692 } else {
3693 // Convert the arguments.
3694 if (PerformCopyInitialization(Input,
3695 FnDecl->getParamDecl(0)->getType(),
3696 "passing"))
3697 return ExprError();
3698 }
3699
3700 // Determine the result type
3701 QualType ResultTy
3702 = FnDecl->getType()->getAsFunctionType()->getResultType();
3703 ResultTy = ResultTy.getNonReferenceType();
3704
3705 // Build the actual expression node.
3706 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3707 SourceLocation());
3708 UsualUnaryConversions(FnExpr);
3709
3710 input.release();
3711 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3712 &Input, 1, ResultTy,
3713 OpLoc));
3714 } else {
3715 // We matched a built-in operator. Convert the arguments, then
3716 // break out so that we will build the appropriate built-in
3717 // operator node.
3718 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3719 Best->Conversions[0], "passing"))
3720 return ExprError();
3721
3722 break;
3723 }
3724 }
3725
3726 case OR_No_Viable_Function:
3727 // No viable function; fall through to handling this as a
3728 // built-in operator, which will produce an error message for us.
3729 break;
3730
3731 case OR_Ambiguous:
3732 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3733 << UnaryOperator::getOpcodeStr(Opc)
3734 << Input->getSourceRange();
3735 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3736 return ExprError();
3737
3738 case OR_Deleted:
3739 Diag(OpLoc, diag::err_ovl_deleted_oper)
3740 << Best->Function->isDeleted()
3741 << UnaryOperator::getOpcodeStr(Opc)
3742 << Input->getSourceRange();
3743 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3744 return ExprError();
3745 }
3746
3747 // Either we found no viable overloaded operator or we matched a
3748 // built-in operator. In either case, fall through to trying to
3749 // build a built-in operation.
3750 input.release();
3751 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
3752}
3753
Douglas Gregor063daf62009-03-13 18:40:31 +00003754/// \brief Create a binary operation that may resolve to an overloaded
3755/// operator.
3756///
3757/// \param OpLoc The location of the operator itself (e.g., '+').
3758///
3759/// \param OpcIn The BinaryOperator::Opcode that describes this
3760/// operator.
3761///
3762/// \param Functions The set of non-member functions that will be
3763/// considered by overload resolution. The caller needs to build this
3764/// set based on the context using, e.g.,
3765/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3766/// set should not contain any member functions; those will be added
3767/// by CreateOverloadedBinOp().
3768///
3769/// \param LHS Left-hand argument.
3770/// \param RHS Right-hand argument.
3771Sema::OwningExprResult
3772Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
3773 unsigned OpcIn,
3774 FunctionSet &Functions,
3775 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00003776 Expr *Args[2] = { LHS, RHS };
3777
3778 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
3779 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
3780 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3781
3782 // If either side is type-dependent, create an appropriate dependent
3783 // expression.
3784 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
3785 // .* cannot be overloaded.
3786 if (Opc == BinaryOperator::PtrMemD)
3787 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
3788 Context.DependentTy, OpLoc));
3789
3790 OverloadedFunctionDecl *Overloads
3791 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3792 for (FunctionSet::iterator Func = Functions.begin(),
3793 FuncEnd = Functions.end();
3794 Func != FuncEnd; ++Func)
3795 Overloads->addOverload(*Func);
3796
3797 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3798 OpLoc, false, false);
3799
3800 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3801 Args, 2,
3802 Context.DependentTy,
3803 OpLoc));
3804 }
3805
3806 // If this is the .* operator, which is not overloadable, just
3807 // create a built-in binary operator.
3808 if (Opc == BinaryOperator::PtrMemD)
3809 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3810
3811 // If this is one of the assignment operators, we only perform
3812 // overload resolution if the left-hand side is a class or
3813 // enumeration type (C++ [expr.ass]p3).
3814 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3815 !LHS->getType()->isOverloadableType())
3816 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3817
Douglas Gregorbc736fc2009-03-13 23:49:33 +00003818 // Build an empty overload set.
3819 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00003820
3821 // Add the candidates from the given function set.
3822 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
3823
3824 // Add operator candidates that are member functions.
3825 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
3826
3827 // Add builtin operator candidates.
3828 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
3829
3830 // Perform overload resolution.
3831 OverloadCandidateSet::iterator Best;
3832 switch (BestViableFunction(CandidateSet, Best)) {
3833 case OR_Success: {
3834 // We found a built-in operator or an overloaded operator.
3835 FunctionDecl *FnDecl = Best->Function;
3836
3837 if (FnDecl) {
3838 // We matched an overloaded operator. Build a call to that
3839 // operator.
3840
3841 // Convert the arguments.
3842 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3843 if (PerformObjectArgumentInitialization(LHS, Method) ||
3844 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
3845 "passing"))
3846 return ExprError();
3847 } else {
3848 // Convert the arguments.
3849 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
3850 "passing") ||
3851 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
3852 "passing"))
3853 return ExprError();
3854 }
3855
3856 // Determine the result type
3857 QualType ResultTy
3858 = FnDecl->getType()->getAsFunctionType()->getResultType();
3859 ResultTy = ResultTy.getNonReferenceType();
3860
3861 // Build the actual expression node.
3862 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3863 SourceLocation());
3864 UsualUnaryConversions(FnExpr);
3865
3866 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3867 Args, 2, ResultTy,
3868 OpLoc));
3869 } else {
3870 // We matched a built-in operator. Convert the arguments, then
3871 // break out so that we will build the appropriate built-in
3872 // operator node.
3873 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
3874 Best->Conversions[0], "passing") ||
3875 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
3876 Best->Conversions[1], "passing"))
3877 return ExprError();
3878
3879 break;
3880 }
3881 }
3882
3883 case OR_No_Viable_Function:
3884 // No viable function; fall through to handling this as a
3885 // built-in operator, which will produce an error message for us.
3886 break;
3887
3888 case OR_Ambiguous:
3889 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3890 << BinaryOperator::getOpcodeStr(Opc)
3891 << LHS->getSourceRange() << RHS->getSourceRange();
3892 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3893 return ExprError();
3894
3895 case OR_Deleted:
3896 Diag(OpLoc, diag::err_ovl_deleted_oper)
3897 << Best->Function->isDeleted()
3898 << BinaryOperator::getOpcodeStr(Opc)
3899 << LHS->getSourceRange() << RHS->getSourceRange();
3900 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3901 return ExprError();
3902 }
3903
3904 // Either we found no viable overloaded operator or we matched a
3905 // built-in operator. In either case, try to build a built-in
3906 // operation.
3907 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3908}
3909
Douglas Gregor88a35142008-12-22 05:46:06 +00003910/// BuildCallToMemberFunction - Build a call to a member
3911/// function. MemExpr is the expression that refers to the member
3912/// function (and includes the object parameter), Args/NumArgs are the
3913/// arguments to the function call (not including the object
3914/// parameter). The caller needs to validate that the member
3915/// expression refers to a member function or an overloaded member
3916/// function.
3917Sema::ExprResult
3918Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3919 SourceLocation LParenLoc, Expr **Args,
3920 unsigned NumArgs, SourceLocation *CommaLocs,
3921 SourceLocation RParenLoc) {
3922 // Dig out the member expression. This holds both the object
3923 // argument and the member function we're referring to.
3924 MemberExpr *MemExpr = 0;
3925 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3926 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3927 else
3928 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3929 assert(MemExpr && "Building member call without member expression");
3930
3931 // Extract the object argument.
3932 Expr *ObjectArg = MemExpr->getBase();
3933 if (MemExpr->isArrow())
Ted Kremenek8189cde2009-02-07 01:47:29 +00003934 ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref,
3935 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
Douglas Gregor611a8c42009-02-19 00:52:42 +00003936 ObjectArg->getLocStart());
Douglas Gregor88a35142008-12-22 05:46:06 +00003937 CXXMethodDecl *Method = 0;
3938 if (OverloadedFunctionDecl *Ovl
3939 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3940 // Add overload candidates
3941 OverloadCandidateSet CandidateSet;
3942 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3943 FuncEnd = Ovl->function_end();
3944 Func != FuncEnd; ++Func) {
3945 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3946 Method = cast<CXXMethodDecl>(*Func);
3947 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3948 /*SuppressUserConversions=*/false);
3949 }
3950
3951 OverloadCandidateSet::iterator Best;
3952 switch (BestViableFunction(CandidateSet, Best)) {
3953 case OR_Success:
3954 Method = cast<CXXMethodDecl>(Best->Function);
3955 break;
3956
3957 case OR_No_Viable_Function:
3958 Diag(MemExpr->getSourceRange().getBegin(),
3959 diag::err_ovl_no_viable_member_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00003960 << Ovl->getDeclName() << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00003961 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3962 // FIXME: Leaking incoming expressions!
3963 return true;
3964
3965 case OR_Ambiguous:
3966 Diag(MemExpr->getSourceRange().getBegin(),
3967 diag::err_ovl_ambiguous_member_call)
3968 << Ovl->getDeclName() << MemExprE->getSourceRange();
3969 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3970 // FIXME: Leaking incoming expressions!
3971 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003972
3973 case OR_Deleted:
3974 Diag(MemExpr->getSourceRange().getBegin(),
3975 diag::err_ovl_deleted_member_call)
3976 << Best->Function->isDeleted()
3977 << Ovl->getDeclName() << MemExprE->getSourceRange();
3978 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3979 // FIXME: Leaking incoming expressions!
3980 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003981 }
3982
3983 FixOverloadedFunctionReference(MemExpr, Method);
3984 } else {
3985 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3986 }
3987
3988 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek8189cde2009-02-07 01:47:29 +00003989 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00003990 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
3991 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003992 Method->getResultType().getNonReferenceType(),
3993 RParenLoc));
3994
3995 // Convert the object argument (for a non-static member function call).
3996 if (!Method->isStatic() &&
3997 PerformObjectArgumentInitialization(ObjectArg, Method))
3998 return true;
3999 MemExpr->setBase(ObjectArg);
4000
4001 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00004002 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004003 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4004 RParenLoc))
4005 return true;
4006
Sebastian Redl0eb23302009-01-19 00:08:26 +00004007 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00004008}
4009
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004010/// BuildCallToObjectOfClassType - Build a call to an object of class
4011/// type (C++ [over.call.object]), which can end up invoking an
4012/// overloaded function call operator (@c operator()) or performing a
4013/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00004014Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00004015Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4016 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004017 Expr **Args, unsigned NumArgs,
4018 SourceLocation *CommaLocs,
4019 SourceLocation RParenLoc) {
4020 assert(Object->getType()->isRecordType() && "Requires object type argument");
4021 const RecordType *Record = Object->getType()->getAsRecordType();
4022
4023 // C++ [over.call.object]p1:
4024 // If the primary-expression E in the function call syntax
4025 // evaluates to a class object of type “cv T”, then the set of
4026 // candidate functions includes at least the function call
4027 // operators of T. The function call operators of T are obtained by
4028 // ordinary lookup of the name operator() in the context of
4029 // (E).operator().
4030 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00004031 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004032 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00004033 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004034 Oper != OperEnd; ++Oper)
4035 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4036 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004037
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004038 // C++ [over.call.object]p2:
4039 // In addition, for each conversion function declared in T of the
4040 // form
4041 //
4042 // operator conversion-type-id () cv-qualifier;
4043 //
4044 // where cv-qualifier is the same cv-qualification as, or a
4045 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00004046 // denotes the type "pointer to function of (P1,...,Pn) returning
4047 // R", or the type "reference to pointer to function of
4048 // (P1,...,Pn) returning R", or the type "reference to function
4049 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004050 // is also considered as a candidate function. Similarly,
4051 // surrogate call functions are added to the set of candidate
4052 // functions for each conversion function declared in an
4053 // accessible base class provided the function is not hidden
4054 // within T by another intervening declaration.
4055 //
4056 // FIXME: Look in base classes for more conversion operators!
4057 OverloadedFunctionDecl *Conversions
4058 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00004059 for (OverloadedFunctionDecl::function_iterator
4060 Func = Conversions->function_begin(),
4061 FuncEnd = Conversions->function_end();
4062 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004063 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4064
4065 // Strip the reference type (if any) and then the pointer type (if
4066 // any) to get down to what might be a function type.
4067 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4068 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4069 ConvType = ConvPtrType->getPointeeType();
4070
Douglas Gregor72564e72009-02-26 23:50:07 +00004071 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004072 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4073 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004074
4075 // Perform overload resolution.
4076 OverloadCandidateSet::iterator Best;
4077 switch (BestViableFunction(CandidateSet, Best)) {
4078 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004079 // Overload resolution succeeded; we'll build the appropriate call
4080 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004081 break;
4082
4083 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00004084 Diag(Object->getSourceRange().getBegin(),
4085 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004086 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00004087 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004088 break;
4089
4090 case OR_Ambiguous:
4091 Diag(Object->getSourceRange().getBegin(),
4092 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00004093 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004094 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4095 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004096
4097 case OR_Deleted:
4098 Diag(Object->getSourceRange().getBegin(),
4099 diag::err_ovl_deleted_object_call)
4100 << Best->Function->isDeleted()
4101 << Object->getType() << Object->getSourceRange();
4102 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4103 break;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004104 }
4105
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004106 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004107 // We had an error; delete all of the subexpressions and return
4108 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004109 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004110 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004111 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004112 return true;
4113 }
4114
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004115 if (Best->Function == 0) {
4116 // Since there is no function declaration, this is one of the
4117 // surrogate candidates. Dig out the conversion function.
4118 CXXConversionDecl *Conv
4119 = cast<CXXConversionDecl>(
4120 Best->Conversions[0].UserDefined.ConversionFunction);
4121
4122 // We selected one of the surrogate functions that converts the
4123 // object parameter to a function pointer. Perform the conversion
4124 // on the object argument, then let ActOnCallExpr finish the job.
4125 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00004126 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004127 Conv->getConversionType().getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004128 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004129 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4130 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4131 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004132 }
4133
4134 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4135 // that calls this method, using Object for the implicit object
4136 // parameter and passing along the remaining arguments.
4137 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor72564e72009-02-26 23:50:07 +00004138 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004139
4140 unsigned NumArgsInProto = Proto->getNumArgs();
4141 unsigned NumArgsToCheck = NumArgs;
4142
4143 // Build the full argument list for the method call (the
4144 // implicit object parameter is placed at the beginning of the
4145 // list).
4146 Expr **MethodArgs;
4147 if (NumArgs < NumArgsInProto) {
4148 NumArgsToCheck = NumArgsInProto;
4149 MethodArgs = new Expr*[NumArgsInProto + 1];
4150 } else {
4151 MethodArgs = new Expr*[NumArgs + 1];
4152 }
4153 MethodArgs[0] = Object;
4154 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4155 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4156
Ted Kremenek8189cde2009-02-07 01:47:29 +00004157 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4158 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004159 UsualUnaryConversions(NewFn);
4160
4161 // Once we've built TheCall, all of the expressions are properly
4162 // owned.
4163 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004164 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor063daf62009-03-13 18:40:31 +00004165 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4166 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004167 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004168 delete [] MethodArgs;
4169
Douglas Gregor518fda12009-01-13 05:10:00 +00004170 // We may have default arguments. If so, we need to allocate more
4171 // slots in the call for them.
4172 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004173 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00004174 else if (NumArgs > NumArgsInProto)
4175 NumArgsToCheck = NumArgsInProto;
4176
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004177 // Initialize the implicit object parameter.
Douglas Gregor518fda12009-01-13 05:10:00 +00004178 if (PerformObjectArgumentInitialization(Object, Method))
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004179 return true;
4180 TheCall->setArg(0, Object);
4181
4182 // Check the argument types.
4183 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004184 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00004185 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004186 Arg = Args[i];
Douglas Gregor518fda12009-01-13 05:10:00 +00004187
4188 // Pass the argument.
4189 QualType ProtoArgType = Proto->getArgType(i);
4190 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
4191 return true;
4192 } else {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004193 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00004194 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004195
4196 TheCall->setArg(i + 1, Arg);
4197 }
4198
4199 // If this is a variadic call, handle args passed through "...".
4200 if (Proto->isVariadic()) {
4201 // Promote the arguments (C99 6.5.2.2p7).
4202 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4203 Expr *Arg = Args[i];
Anders Carlsson906fed02009-01-13 05:48:52 +00004204
Anders Carlssondce5e2c2009-01-16 16:48:51 +00004205 DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004206 TheCall->setArg(i + 1, Arg);
4207 }
4208 }
4209
Sebastian Redl0eb23302009-01-19 00:08:26 +00004210 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004211}
4212
Douglas Gregor8ba10742008-11-20 16:27:02 +00004213/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4214/// (if one exists), where @c Base is an expression of class type and
4215/// @c Member is the name of the member we're trying to find.
4216Action::ExprResult
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004217Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004218 SourceLocation MemberLoc,
4219 IdentifierInfo &Member) {
4220 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4221
4222 // C++ [over.ref]p1:
4223 //
4224 // [...] An expression x->m is interpreted as (x.operator->())->m
4225 // for a class object x of type T if T::operator->() exists and if
4226 // the operator is selected as the best match function by the
4227 // overload resolution mechanism (13.3).
4228 // FIXME: look in base classes.
4229 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4230 OverloadCandidateSet CandidateSet;
4231 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004232
4233 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00004234 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004235 Oper != OperEnd; ++Oper)
4236 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004237 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004238
Ted Kremenek8189cde2009-02-07 01:47:29 +00004239 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004240
Douglas Gregor8ba10742008-11-20 16:27:02 +00004241 // Perform overload resolution.
4242 OverloadCandidateSet::iterator Best;
4243 switch (BestViableFunction(CandidateSet, Best)) {
4244 case OR_Success:
4245 // Overload resolution succeeded; we'll build the call below.
4246 break;
4247
4248 case OR_No_Viable_Function:
4249 if (CandidateSet.empty())
4250 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00004251 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004252 else
4253 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Chris Lattner4330d652009-02-17 07:29:20 +00004254 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004255 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004256 return true;
4257
4258 case OR_Ambiguous:
4259 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00004260 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004261 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004262 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004263
4264 case OR_Deleted:
4265 Diag(OpLoc, diag::err_ovl_deleted_oper)
4266 << Best->Function->isDeleted()
4267 << "operator->" << BasePtr->getSourceRange();
4268 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4269 return true;
Douglas Gregor8ba10742008-11-20 16:27:02 +00004270 }
4271
4272 // Convert the object parameter.
4273 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004274 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00004275 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004276
4277 // No concerns about early exits now.
4278 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004279
4280 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004281 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4282 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004283 UsualUnaryConversions(FnExpr);
Douglas Gregor063daf62009-03-13 18:40:31 +00004284 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004285 Method->getResultType().getNonReferenceType(),
4286 OpLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004287 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004288 MemberLoc, Member, DeclPtrTy()).release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004289}
4290
Douglas Gregor904eed32008-11-10 20:40:00 +00004291/// FixOverloadedFunctionReference - E is an expression that refers to
4292/// a C++ overloaded function (possibly with some parentheses and
4293/// perhaps a '&' around it). We have resolved the overloaded function
4294/// to the function declaration Fn, so patch up the expression E to
4295/// refer (possibly indirectly) to Fn.
4296void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4297 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4298 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4299 E->setType(PE->getSubExpr()->getType());
4300 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4301 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4302 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00004303 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4304 if (Method->isStatic()) {
4305 // Do nothing: static member functions aren't any different
4306 // from non-member functions.
4307 }
4308 else if (QualifiedDeclRefExpr *DRE
4309 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4310 // We have taken the address of a pointer to member
4311 // function. Perform the computation here so that we get the
4312 // appropriate pointer to member type.
4313 DRE->setDecl(Fn);
4314 DRE->setType(Fn->getType());
4315 QualType ClassType
4316 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4317 E->setType(Context.getMemberPointerType(Fn->getType(),
4318 ClassType.getTypePtr()));
4319 return;
4320 }
4321 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004322 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00004323 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor904eed32008-11-10 20:40:00 +00004324 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4325 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4326 "Expected overloaded function");
4327 DR->setDecl(Fn);
4328 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004329 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4330 MemExpr->setMemberDecl(Fn);
4331 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00004332 } else {
4333 assert(false && "Invalid reference to overloaded function");
4334 }
4335}
4336
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004337} // end namespace clang