blob: 0c45ee77bab26da0a83f96431d92aeca092dfad3 [file] [log] [blame]
Douglas Gregord2baafd2008-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 Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor10f3c502008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-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 Gregore819caf2009-02-12 00:15:05 +000042 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000045 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000050 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000051 ICC_Conversion,
Douglas Gregord2baafd2008-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 Gregore819caf2009-02-12 00:15:05 +000069 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000072 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000077 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000078 ICR_Conversion,
Douglas Gregord2baafd2008-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 Gregore819caf2009-02-12 00:15:05 +000095 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000096 "Integral conversion",
97 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +000098 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000099 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000100 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000101 "Pointer conversion",
102 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000103 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000104 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000105 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000106 };
107 return Name[Kind];
108}
109
Douglas Gregorb72e9da2008-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 Gregora3b34bb2008-11-03 19:09:14 +0000119 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000120}
121
Douglas Gregord2baafd2008-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 Gregor80402cf2008-12-23 00:53:59 +0000150 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-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 Gregor14046502008-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 Gregord2baafd2008-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 Gregora3b34bb2008-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 Gregord2baafd2008-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 Lattner271d4c22008-11-24 05:29:24 +0000226 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-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 Gregor4fa58902009-02-26 23:50:07 +0000313 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
314 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000315 return false;
316
Douglas Gregor4fa58902009-02-26 23:50:07 +0000317 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType.getTypePtr());
318 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType.getTypePtr());
Douglas Gregord2baafd2008-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 Gregora7b56a32008-11-21 15:36:28 +0000342 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-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 Gregor81c29152008-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 Gregord2baafd2008-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 Gregora3b34bb2008-11-03 19:09:14 +0000373///
374/// If @p SuppressUserConversions, then user-defined conversions are
375/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000376/// If @p AllowExplicit, then explicit user-defined conversions are
377/// permitted.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000378ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000379Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000380 bool SuppressUserConversions,
Douglas Gregorb206cc42009-01-30 23:27:23 +0000381 bool AllowExplicit)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000382{
383 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000384 if (IsStandardConversion(From, ToType, ICS.Standard))
385 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000386 else if (getLangOptions().CPlusPlus &&
387 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregorb206cc42009-01-30 23:27:23 +0000388 !SuppressUserConversions, AllowExplicit)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000389 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-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 Gregord9176392009-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 Gregora3b34bb2008-11-03 19:09:14 +0000403 // Turn this into a "standard" conversion sequence, so that it
404 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-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 Gregora3b34bb2008-11-03 19:09:14 +0000409 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000410 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000411 ICS.Standard.Second = ICK_Derived_To_Base;
412 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000413 }
Douglas Gregorb206cc42009-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 Gregore640ab62008-11-03 17:51:48 +0000425 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000426 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-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 Gregord2baafd2008-10-21 16:13:35 +0000443 QualType FromType = From->getType();
444
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000445 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000446 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000447 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000448 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000449 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000450 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000451
Douglas Gregorfcb19192009-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 Gregord2baafd2008-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 Gregor45014fd2008-11-10 20:40:00 +0000470 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000471 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000472 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-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 Gregorfcb19192009-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 Gregorb72e9da2008-10-31 16:23:19 +0000480 FromType = FromType.getUnqualifiedType();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000481 }
482 // Array-to-pointer conversion (C++ 4.2)
483 else if (FromType->isArrayType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000484 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-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 Gregorb72e9da2008-10-31 16:23:19 +0000493 SCS.Deprecated = true;
Douglas Gregord2baafd2008-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 Gregorb72e9da2008-10-31 16:23:19 +0000499 SCS.Second = ICK_Identity;
500 SCS.Third = ICK_Qualification;
501 SCS.ToTypePtr = ToType.getAsOpaquePtr();
502 return true;
Douglas Gregord2baafd2008-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 Gregorb72e9da2008-10-31 16:23:19 +0000507 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-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 Redl7434fc32009-02-04 21:23:32 +0000513 }
Douglas Gregor45014fd2008-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 Redlce6fff02009-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 Redl7434fc32009-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 Gregor45014fd2008-11-10 20:40:00 +0000537 FromType = Context.getPointerType(FromType);
538 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000539 // We don't require any conversions for the first step.
540 else {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000541 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-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 Gregorfcb19192009-02-11 23:02:49 +0000548 // For overloading in C, this can also be a "compatible-type"
549 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000550 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000551 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000552 // The unqualified versions of the types are the same: there's no
553 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000554 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000555 }
556 // Integral promotion (C++ 4.5).
557 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000558 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000559 FromType = ToType.getUnqualifiedType();
560 }
561 // Floating point promotion (C++ 4.6).
562 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000563 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000564 FromType = ToType.getUnqualifiedType();
565 }
Douglas Gregore819caf2009-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 Gregord2baafd2008-10-21 16:13:35 +0000571 // Integral conversions (C++ 4.7).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000572 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000573 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000574 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000575 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-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 Gregorb72e9da2008-10-31 16:23:19 +0000580 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000581 FromType = ToType.getUnqualifiedType();
582 }
Douglas Gregore819caf2009-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 Gregord2baafd2008-10-21 16:13:35 +0000588 // Floating-integral conversions (C++ 4.9).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000589 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000590 else if ((FromType->isFloatingType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000591 ToType->isIntegralType() && !ToType->isBooleanType() &&
592 !ToType->isEnumeralType()) ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000593 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
594 ToType->isFloatingType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000595 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000596 FromType = ToType.getUnqualifiedType();
597 }
Douglas Gregore819caf2009-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 Gregord2baafd2008-10-21 16:13:35 +0000604 // Pointer conversions (C++ 4.10).
Douglas Gregor6fd35572008-12-19 17:40:08 +0000605 else if (IsPointerConversion(From, FromType, ToType, FromType,
606 IncompatibleObjC)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000607 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000608 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000609 }
Sebastian Redlba387562009-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 Gregord2baafd2008-10-21 16:13:35 +0000614 // Boolean conversions (C++ 4.12).
Douglas Gregord2baafd2008-10-21 16:13:35 +0000615 else if (ToType->isBooleanType() &&
616 (FromType->isArithmeticType() ||
617 FromType->isEnumeralType() ||
Douglas Gregor80402cf2008-12-23 00:53:59 +0000618 FromType->isPointerType() ||
Sebastian Redlba387562009-01-25 19:43:20 +0000619 FromType->isBlockPointerType() ||
620 FromType->isMemberPointerType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000621 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000622 FromType = Context.BoolTy;
Douglas Gregorfcb19192009-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 Gregord2baafd2008-10-21 16:13:35 +0000628 } else {
629 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000630 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000631 }
632
Douglas Gregor81c29152008-10-29 00:13:59 +0000633 QualType CanonFrom;
634 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000635 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000636 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000637 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000638 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000639 CanonFrom = Context.getCanonicalType(FromType);
640 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000641 } else {
642 // No conversion required
Douglas Gregorb72e9da2008-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 Gregor81c29152008-10-29 00:13:59 +0000649 CanonFrom = Context.getCanonicalType(FromType);
650 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000651 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000652 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
653 FromType = ToType;
654 CanonFrom = CanonTo;
655 }
Douglas Gregord2baafd2008-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 Gregor81c29152008-10-29 00:13:59 +0000660 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000661 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000662
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000663 SCS.ToTypePtr = FromType.getAsOpaquePtr();
664 return true;
Douglas Gregord2baafd2008-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 Redl12aee862008-11-04 15:59:10 +0000674 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000675 if (!To) {
676 return false;
677 }
Douglas Gregord2baafd2008-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 Redl9ac68aa2008-10-31 14:43:28 +0000684 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-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 Redl9ac68aa2008-10-31 14:43:28 +0000690 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000691 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000692 }
693
Douglas Gregord2baafd2008-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 Gregor6b5e34f2008-12-12 02:00:36 +0000717 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000718 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000719 Context.LongTy, Context.UnsignedLongTy ,
720 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000721 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000722 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-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 Redl9ac68aa2008-10-31 14:43:28 +0000730 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-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 Gregor4ff48512009-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 Gregord2baafd2008-10-21 16:13:35 +0000746 using llvm::APSInt;
Douglas Gregor82d44772008-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 Redl9ac68aa2008-10-31 14:43:28 +0000767 }
Douglas Gregord2baafd2008-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 Redl9ac68aa2008-10-31 14:43:28 +0000773 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000774 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000775 }
Douglas Gregord2baafd2008-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 Gregore819caf2009-02-12 00:15:05 +0000788 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000789 if (FromBuiltin->getKind() == BuiltinType::Float &&
790 ToBuiltin->getKind() == BuiltinType::Double)
791 return true;
792
Douglas Gregore819caf2009-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 Gregord2baafd2008-10-21 16:13:35 +0000803 return false;
804}
805
Douglas Gregore819caf2009-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 Gregor4ff48512009-02-12 00:26:06 +0000810/// floating-point or integral promotion.
Douglas Gregore819caf2009-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 Gregor4ff48512009-02-12 00:26:06 +0000821 ToComplex->getElementType()) ||
822 IsIntegralPromotion(0, FromComplex->getElementType(),
823 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000824}
825
Douglas Gregor24a90a52008-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 Gregord2baafd2008-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 Gregor9036ef72008-11-27 00:15:41 +0000860///
Douglas Gregor3f5a00c2008-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 Gregor6fd35572008-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 Gregord2baafd2008-10-21 16:13:35 +0000870bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000871 QualType& ConvertedType,
872 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000873{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000874 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000875 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
876 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000877
Douglas Gregorf1d75712008-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 Gregor9036ef72008-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 Gregord2baafd2008-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 Redl9ac68aa2008-10-31 14:43:28 +0000907
Douglas Gregor24a90a52008-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 Gregord2baafd2008-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 Gregor26ea1222009-03-24 20:32:41 +0000919 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000920 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
921 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000922 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000923 return true;
924 }
925
Douglas Gregorfcb19192009-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 Gregor14046502008-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 Gregorbb461502008-10-24 04:54:22 +0000947 // Note that we do not check for ambiguity or inaccessibility
948 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000949 if (getLangOptions().CPlusPlus &&
950 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000951 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000952 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
953 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000954 ToType, Context);
955 return true;
956 }
Douglas Gregor14046502008-10-23 00:40:37 +0000957
Douglas Gregor932778b2008-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 Gregor80402cf2008-12-23 00:53:59 +0000977 // Beyond this point, both types need to be pointers or block pointers.
978 QualType ToPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000979 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor80402cf2008-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 Gregor932778b2008-12-19 19:13:09 +0000985 return false;
986
Douglas Gregor80402cf2008-12-23 00:53:59 +0000987 QualType FromPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000988 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor80402cf2008-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 Gregor932778b2008-12-19 19:13:09 +0000995 return false;
996
Douglas Gregor24a90a52008-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 Gregor80402cf2008-12-23 00:53:59 +00001003 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001004 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001005 ToType, Context);
1006 return true;
1007 }
1008
Douglas Gregor6fd35572008-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 Gregor80402cf2008-12-23 00:53:59 +00001015 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor6fd35572008-12-19 17:40:08 +00001016 ToPointeeType,
1017 ToType, Context);
1018 return true;
1019 }
1020
Douglas Gregor24a90a52008-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 Naroff17c03822009-02-12 17:52:19 +00001023 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1024 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001025 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1026 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001027 ToType, Context);
1028 return true;
1029 }
Douglas Gregor14046502008-10-23 00:40:37 +00001030
Douglas Gregord0c653a2008-12-18 23:43:31 +00001031 // Objective C++: Allow conversions between the Objective-C "id" and
1032 // "Class", in either direction.
Steve Naroff17c03822009-02-12 17:52:19 +00001033 if ((Context.isObjCIdStructType(FromPointeeType) &&
1034 Context.isObjCClassStructType(ToPointeeType)) ||
1035 (Context.isObjCClassStructType(FromPointeeType) &&
1036 Context.isObjCIdStructType(ToPointeeType))) {
Douglas Gregord0c653a2008-12-18 23:43:31 +00001037 ConvertedType = ToType;
1038 return true;
1039 }
1040
Douglas Gregor932778b2008-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 Gregor80402cf2008-12-23 00:53:59 +00001052 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-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 Gregor4fa58902009-02-26 23:50:07 +00001056 const FunctionProtoType *FromFunctionType
1057 = FromPointeeType->getAsFunctionProtoType();
1058 const FunctionProtoType *ToFunctionType
1059 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-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 Redlba387562009-01-25 19:43:20 +00001115 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001116}
1117
Douglas Gregorbb461502008-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 Gregorbb461502008-10-24 04:54:22 +00001129 QualType FromPointeeType = FromPtrType->getPointeeType(),
1130 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-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 Naroff17c03822009-02-12 17:52:19 +00001135 if (Context.isObjCIdStructType(FromPointeeType) ||
1136 Context.isObjCIdStructType(ToPointeeType) ||
1137 Context.isObjCClassStructType(FromPointeeType) ||
1138 Context.isObjCClassStructType(ToPointeeType))
Douglas Gregord0c653a2008-12-18 23:43:31 +00001139 return false;
1140
Douglas Gregorbb461502008-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 Gregor651d1cc2008-10-24 16:17:19 +00001145 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1146 From->getExprLoc(),
1147 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001148 }
1149 }
1150
1151 return false;
1152}
1153
Sebastian Redlba387562009-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 Redlf41a58c2009-01-28 18:33:18 +00001200 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1201 if (!FromPtrType)
1202 return false;
Sebastian Redlba387562009-01-25 19:43:20 +00001203
Sebastian Redlf41a58c2009-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 Redlba387562009-01-25 19:43:20 +00001207
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001208 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1209 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001210
Sebastian Redlf41a58c2009-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 Redlba387562009-01-25 19:43:20 +00001214
Sebastian Redlf41a58c2009-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 Redlba387562009-01-25 19:43:20 +00001221
Sebastian Redlf41a58c2009-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 Redlba387562009-01-25 19:43:20 +00001230
Sebastian Redlf41a58c2009-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 Redlba387562009-01-25 19:43:20 +00001235 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001236
Douglas Gregor2e047592009-02-28 01:32:25 +00001237 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-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 Redlba387562009-01-25 19:43:20 +00001244 return false;
1245}
1246
Douglas Gregor6573cfd2008-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 Redlf41a58c2009-01-28 18:33:18 +00001260
Douglas Gregor6573cfd2008-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 Gregor6573cfd2008-10-21 23:43:52 +00001265 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001266 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-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 Gregorabed2172008-10-22 17:49:05 +00001270 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001271 // until there are no more pointers or pointers-to-members left to
1272 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001273 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-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 Gregore5db4f72008-10-22 00:38:21 +00001277 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001278 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001279
Douglas Gregor6573cfd2008-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 Gregorccc0ccc2008-10-22 14:17:15 +00001283 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001284 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001285
Douglas Gregor6573cfd2008-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 Gregorccc0ccc2008-10-22 14:17:15 +00001290 }
Douglas Gregor6573cfd2008-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 Gregorb206cc42009-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 Gregorb72e9da2008-10-31 16:23:19 +00001315bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001316 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001317 bool AllowConversionFunctions,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001318 bool AllowExplicit)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001319{
1320 OverloadCandidateSet CandidateSet;
Douglas Gregor2e047592009-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 Gregorb72e9da2008-10-31 16:23:19 +00001343 }
1344 }
1345
Douglas Gregorb206cc42009-01-30 23:27:23 +00001346 if (!AllowConversionFunctions) {
1347 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-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 Gregor60714f92008-11-07 22:36:19 +00001363 }
1364 }
Douglas Gregorb72e9da2008-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 Gregorb72e9da2008-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 Gregor60714f92008-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 Gregorb72e9da2008-10-31 16:23:19 +00001409 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001410 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001411 return false;
1412 }
1413
1414 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001415 case OR_Deleted:
Douglas Gregorb72e9da2008-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 Gregord2baafd2008-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 Gregord2baafd2008-10-21 16:13:35 +00001510
Douglas Gregorccc0ccc2008-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 Gregor14046502008-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 Gregor0e343382008-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 Gregor14046502008-10-23 00:40:37 +00001529 bool SCS1ConvertsToVoid
1530 = SCS1.isPointerConversionToVoidPointer(Context);
1531 bool SCS2ConvertsToVoid
1532 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-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 Gregor14046502008-10-23 00:40:37 +00001536 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1537 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-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 Gregor14046502008-10-23 00:40:37 +00001541 if (ImplicitConversionSequence::CompareKind DerivedCK
1542 = CompareDerivedToBaseConversions(SCS1, SCS2))
1543 return DerivedCK;
Douglas Gregor0e343382008-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 Gregor24a90a52008-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 Gregor0e343382008-10-29 14:50:44 +00001578 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001579
1580 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1581 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001582 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001583 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001584 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001585
Douglas Gregor0e343382008-10-29 14:50:44 +00001586 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001587 // C++0x [over.ics.rank]p3b4:
1588 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1589 // implicit object parameter of a non-static member function declared
1590 // without a ref-qualifier, and S1 binds an rvalue reference to an
1591 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001592 // FIXME: We don't know if we're dealing with the implicit object parameter,
1593 // or if the member function in this case has a ref qualifier.
1594 // (Of course, we don't have ref qualifiers yet.)
1595 if (SCS1.RRefBinding != SCS2.RRefBinding)
1596 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1597 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001598
1599 // C++ [over.ics.rank]p3b4:
1600 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1601 // which the references refer are the same type except for
1602 // top-level cv-qualifiers, and the type to which the reference
1603 // initialized by S2 refers is more cv-qualified than the type
1604 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001605 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1606 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001607 T1 = Context.getCanonicalType(T1);
1608 T2 = Context.getCanonicalType(T2);
1609 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1610 if (T2.isMoreQualifiedThan(T1))
1611 return ImplicitConversionSequence::Better;
1612 else if (T1.isMoreQualifiedThan(T2))
1613 return ImplicitConversionSequence::Worse;
1614 }
1615 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001616
1617 return ImplicitConversionSequence::Indistinguishable;
1618}
1619
1620/// CompareQualificationConversions - Compares two standard conversion
1621/// sequences to determine whether they can be ranked based on their
1622/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1623ImplicitConversionSequence::CompareKind
1624Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1625 const StandardConversionSequence& SCS2)
1626{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001627 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001628 // -- S1 and S2 differ only in their qualification conversion and
1629 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1630 // cv-qualification signature of type T1 is a proper subset of
1631 // the cv-qualification signature of type T2, and S1 is not the
1632 // deprecated string literal array-to-pointer conversion (4.2).
1633 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1634 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1635 return ImplicitConversionSequence::Indistinguishable;
1636
1637 // FIXME: the example in the standard doesn't use a qualification
1638 // conversion (!)
1639 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1640 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1641 T1 = Context.getCanonicalType(T1);
1642 T2 = Context.getCanonicalType(T2);
1643
1644 // If the types are the same, we won't learn anything by unwrapped
1645 // them.
1646 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1647 return ImplicitConversionSequence::Indistinguishable;
1648
1649 ImplicitConversionSequence::CompareKind Result
1650 = ImplicitConversionSequence::Indistinguishable;
1651 while (UnwrapSimilarPointerTypes(T1, T2)) {
1652 // Within each iteration of the loop, we check the qualifiers to
1653 // determine if this still looks like a qualification
1654 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001655 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001656 // until there are no more pointers or pointers-to-members left
1657 // to unwrap. This essentially mimics what
1658 // IsQualificationConversion does, but here we're checking for a
1659 // strict subset of qualifiers.
1660 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1661 // The qualifiers are the same, so this doesn't tell us anything
1662 // about how the sequences rank.
1663 ;
1664 else if (T2.isMoreQualifiedThan(T1)) {
1665 // T1 has fewer qualifiers, so it could be the better sequence.
1666 if (Result == ImplicitConversionSequence::Worse)
1667 // Neither has qualifiers that are a subset of the other's
1668 // qualifiers.
1669 return ImplicitConversionSequence::Indistinguishable;
1670
1671 Result = ImplicitConversionSequence::Better;
1672 } else if (T1.isMoreQualifiedThan(T2)) {
1673 // T2 has fewer qualifiers, so it could be the better sequence.
1674 if (Result == ImplicitConversionSequence::Better)
1675 // Neither has qualifiers that are a subset of the other's
1676 // qualifiers.
1677 return ImplicitConversionSequence::Indistinguishable;
1678
1679 Result = ImplicitConversionSequence::Worse;
1680 } else {
1681 // Qualifiers are disjoint.
1682 return ImplicitConversionSequence::Indistinguishable;
1683 }
1684
1685 // If the types after this point are equivalent, we're done.
1686 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1687 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001688 }
1689
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001690 // Check that the winning standard conversion sequence isn't using
1691 // the deprecated string literal array to pointer conversion.
1692 switch (Result) {
1693 case ImplicitConversionSequence::Better:
1694 if (SCS1.Deprecated)
1695 Result = ImplicitConversionSequence::Indistinguishable;
1696 break;
1697
1698 case ImplicitConversionSequence::Indistinguishable:
1699 break;
1700
1701 case ImplicitConversionSequence::Worse:
1702 if (SCS2.Deprecated)
1703 Result = ImplicitConversionSequence::Indistinguishable;
1704 break;
1705 }
1706
1707 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001708}
1709
Douglas Gregor14046502008-10-23 00:40:37 +00001710/// CompareDerivedToBaseConversions - Compares two standard conversion
1711/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001712/// various kinds of derived-to-base conversions (C++
1713/// [over.ics.rank]p4b3). As part of these checks, we also look at
1714/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001715ImplicitConversionSequence::CompareKind
1716Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1717 const StandardConversionSequence& SCS2) {
1718 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1719 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1720 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1721 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1722
1723 // Adjust the types we're converting from via the array-to-pointer
1724 // conversion, if we need to.
1725 if (SCS1.First == ICK_Array_To_Pointer)
1726 FromType1 = Context.getArrayDecayedType(FromType1);
1727 if (SCS2.First == ICK_Array_To_Pointer)
1728 FromType2 = Context.getArrayDecayedType(FromType2);
1729
1730 // Canonicalize all of the types.
1731 FromType1 = Context.getCanonicalType(FromType1);
1732 ToType1 = Context.getCanonicalType(ToType1);
1733 FromType2 = Context.getCanonicalType(FromType2);
1734 ToType2 = Context.getCanonicalType(ToType2);
1735
Douglas Gregor0e343382008-10-29 14:50:44 +00001736 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001737 //
1738 // If class B is derived directly or indirectly from class A and
1739 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001740 //
1741 // For Objective-C, we let A, B, and C also be Objective-C
1742 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001743
1744 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001745 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001746 SCS2.Second == ICK_Pointer_Conversion &&
1747 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1748 FromType1->isPointerType() && FromType2->isPointerType() &&
1749 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001750 QualType FromPointee1
1751 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1752 QualType ToPointee1
1753 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1754 QualType FromPointee2
1755 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1756 QualType ToPointee2
1757 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001758
1759 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1760 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1761 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1762 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1763
Douglas Gregor0e343382008-10-29 14:50:44 +00001764 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001765 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1766 if (IsDerivedFrom(ToPointee1, ToPointee2))
1767 return ImplicitConversionSequence::Better;
1768 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1769 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001770
1771 if (ToIface1 && ToIface2) {
1772 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1773 return ImplicitConversionSequence::Better;
1774 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1775 return ImplicitConversionSequence::Worse;
1776 }
Douglas Gregor14046502008-10-23 00:40:37 +00001777 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001778
1779 // -- conversion of B* to A* is better than conversion of C* to A*,
1780 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1781 if (IsDerivedFrom(FromPointee2, FromPointee1))
1782 return ImplicitConversionSequence::Better;
1783 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1784 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001785
1786 if (FromIface1 && FromIface2) {
1787 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1788 return ImplicitConversionSequence::Better;
1789 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1790 return ImplicitConversionSequence::Worse;
1791 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001792 }
Douglas Gregor14046502008-10-23 00:40:37 +00001793 }
1794
Douglas Gregor0e343382008-10-29 14:50:44 +00001795 // Compare based on reference bindings.
1796 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1797 SCS1.Second == ICK_Derived_To_Base) {
1798 // -- binding of an expression of type C to a reference of type
1799 // B& is better than binding an expression of type C to a
1800 // reference of type A&,
1801 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1802 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1803 if (IsDerivedFrom(ToType1, ToType2))
1804 return ImplicitConversionSequence::Better;
1805 else if (IsDerivedFrom(ToType2, ToType1))
1806 return ImplicitConversionSequence::Worse;
1807 }
1808
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001809 // -- binding of an expression of type B to a reference of type
1810 // A& is better than binding an expression of type C to a
1811 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001812 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1813 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1814 if (IsDerivedFrom(FromType2, FromType1))
1815 return ImplicitConversionSequence::Better;
1816 else if (IsDerivedFrom(FromType1, FromType2))
1817 return ImplicitConversionSequence::Worse;
1818 }
1819 }
1820
1821
1822 // FIXME: conversion of A::* to B::* is better than conversion of
1823 // A::* to C::*,
1824
1825 // FIXME: conversion of B::* to C::* is better than conversion of
1826 // A::* to C::*, and
1827
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001828 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1829 SCS1.Second == ICK_Derived_To_Base) {
1830 // -- conversion of C to B is better than conversion of C to A,
1831 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1832 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1833 if (IsDerivedFrom(ToType1, ToType2))
1834 return ImplicitConversionSequence::Better;
1835 else if (IsDerivedFrom(ToType2, ToType1))
1836 return ImplicitConversionSequence::Worse;
1837 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001838
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001839 // -- conversion of B to A is better than conversion of C to A.
1840 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1841 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1842 if (IsDerivedFrom(FromType2, FromType1))
1843 return ImplicitConversionSequence::Better;
1844 else if (IsDerivedFrom(FromType1, FromType2))
1845 return ImplicitConversionSequence::Worse;
1846 }
1847 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001848
Douglas Gregor14046502008-10-23 00:40:37 +00001849 return ImplicitConversionSequence::Indistinguishable;
1850}
1851
Douglas Gregor81c29152008-10-29 00:13:59 +00001852/// TryCopyInitialization - Try to copy-initialize a value of type
1853/// ToType from the expression From. Return the implicit conversion
1854/// sequence required to pass this argument, which may be a bad
1855/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001856/// a parameter of this type). If @p SuppressUserConversions, then we
1857/// do not permit any user-defined conversion sequences.
Douglas Gregor81c29152008-10-29 00:13:59 +00001858ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001859Sema::TryCopyInitialization(Expr *From, QualType ToType,
1860 bool SuppressUserConversions) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001861 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001862 ImplicitConversionSequence ICS;
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001863 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001864 return ICS;
1865 } else {
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001866 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001867 }
1868}
1869
1870/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1871/// type ToType. Returns true (and emits a diagnostic) if there was
1872/// an error, returns false if the initialization succeeded.
1873bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1874 const char* Flavor) {
1875 if (!getLangOptions().CPlusPlus) {
1876 // In C, argument passing is the same as performing an assignment.
1877 QualType FromType = From->getType();
1878 AssignConvertType ConvTy =
1879 CheckSingleAssignmentConstraints(ToType, From);
1880
1881 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1882 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001883 }
Chris Lattner271d4c22008-11-24 05:29:24 +00001884
1885 if (ToType->isReferenceType())
1886 return CheckReferenceInit(From, ToType);
1887
Douglas Gregor6fd35572008-12-19 17:40:08 +00001888 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattner271d4c22008-11-24 05:29:24 +00001889 return false;
1890
1891 return Diag(From->getSourceRange().getBegin(),
1892 diag::err_typecheck_convert_incompatible)
1893 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001894}
1895
Douglas Gregor5ed15042008-11-18 23:14:02 +00001896/// TryObjectArgumentInitialization - Try to initialize the object
1897/// parameter of the given member function (@c Method) from the
1898/// expression @p From.
1899ImplicitConversionSequence
1900Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1901 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1902 unsigned MethodQuals = Method->getTypeQualifiers();
1903 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1904
1905 // Set up the conversion sequence as a "bad" conversion, to allow us
1906 // to exit early.
1907 ImplicitConversionSequence ICS;
1908 ICS.Standard.setAsIdentityConversion();
1909 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1910
1911 // We need to have an object of class type.
1912 QualType FromType = From->getType();
1913 if (!FromType->isRecordType())
1914 return ICS;
1915
1916 // The implicit object parmeter is has the type "reference to cv X",
1917 // where X is the class of which the function is a member
1918 // (C++ [over.match.funcs]p4). However, when finding an implicit
1919 // conversion sequence for the argument, we are not allowed to
1920 // create temporaries or perform user-defined conversions
1921 // (C++ [over.match.funcs]p5). We perform a simplified version of
1922 // reference binding here, that allows class rvalues to bind to
1923 // non-constant references.
1924
1925 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1926 // with the implicit object parameter (C++ [over.match.funcs]p5).
1927 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1928 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1929 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1930 return ICS;
1931
1932 // Check that we have either the same type or a derived type. It
1933 // affects the conversion rank.
1934 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1935 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1936 ICS.Standard.Second = ICK_Identity;
1937 else if (IsDerivedFrom(FromType, ClassType))
1938 ICS.Standard.Second = ICK_Derived_To_Base;
1939 else
1940 return ICS;
1941
1942 // Success. Mark this as a reference binding.
1943 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1944 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1945 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1946 ICS.Standard.ReferenceBinding = true;
1947 ICS.Standard.DirectBinding = true;
1948 return ICS;
1949}
1950
1951/// PerformObjectArgumentInitialization - Perform initialization of
1952/// the implicit object parameter for the given Method with the given
1953/// expression.
1954bool
1955Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1956 QualType ImplicitParamType
1957 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1958 ImplicitConversionSequence ICS
1959 = TryObjectArgumentInitialization(From, Method);
1960 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1961 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001962 diag::err_implicit_object_parameter_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001963 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor5ed15042008-11-18 23:14:02 +00001964
1965 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1966 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1967 From->getSourceRange().getBegin(),
1968 From->getSourceRange()))
1969 return true;
1970
1971 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1972 return false;
1973}
1974
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001975/// TryContextuallyConvertToBool - Attempt to contextually convert the
1976/// expression From to bool (C++0x [conv]p3).
1977ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1978 return TryImplicitConversion(From, Context.BoolTy, false, true);
1979}
1980
1981/// PerformContextuallyConvertToBool - Perform a contextual conversion
1982/// of the expression From to bool (C++0x [conv]p3).
1983bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1984 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1985 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1986 return false;
1987
1988 return Diag(From->getSourceRange().getBegin(),
1989 diag::err_typecheck_bool_condition)
1990 << From->getType() << From->getSourceRange();
1991}
1992
Douglas Gregord2baafd2008-10-21 16:13:35 +00001993/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001994/// candidate functions, using the given function call arguments. If
1995/// @p SuppressUserConversions, then don't allow user-defined
1996/// conversions via constructors or conversion operators.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001997void
1998Sema::AddOverloadCandidate(FunctionDecl *Function,
1999 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002000 OverloadCandidateSet& CandidateSet,
2001 bool SuppressUserConversions)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002002{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002003 const FunctionProtoType* Proto
2004 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002005 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002006 assert(!isa<CXXConversionDecl>(Function) &&
2007 "Use AddConversionCandidate for conversion functions");
Douglas Gregord2baafd2008-10-21 16:13:35 +00002008
Douglas Gregor3257fb52008-12-22 05:46:06 +00002009 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2010 // If we get here, it's because we're calling a member function
2011 // that is named without a member access expression (e.g.,
2012 // "this->f") that was either written explicitly or created
2013 // implicitly. This can happen with a qualified call to a member
2014 // function, e.g., X::f(). We use a NULL object as the implied
2015 // object argument (C++ [over.call.func]p3).
2016 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2017 SuppressUserConversions);
2018 return;
2019 }
2020
2021
Douglas Gregord2baafd2008-10-21 16:13:35 +00002022 // Add this candidate
2023 CandidateSet.push_back(OverloadCandidate());
2024 OverloadCandidate& Candidate = CandidateSet.back();
2025 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002026 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002027 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002028 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002029
2030 unsigned NumArgsInProto = Proto->getNumArgs();
2031
2032 // (C++ 13.3.2p2): A candidate function having fewer than m
2033 // parameters is viable only if it has an ellipsis in its parameter
2034 // list (8.3.5).
2035 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2036 Candidate.Viable = false;
2037 return;
2038 }
2039
2040 // (C++ 13.3.2p2): A candidate function having more than m parameters
2041 // is viable only if the (m+1)st parameter has a default argument
2042 // (8.3.6). For the purposes of overload resolution, the
2043 // parameter list is truncated on the right, so that there are
2044 // exactly m parameters.
2045 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2046 if (NumArgs < MinRequiredArgs) {
2047 // Not enough arguments.
2048 Candidate.Viable = false;
2049 return;
2050 }
2051
2052 // Determine the implicit conversion sequences for each of the
2053 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002054 Candidate.Conversions.resize(NumArgs);
2055 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2056 if (ArgIdx < NumArgsInProto) {
2057 // (C++ 13.3.2p3): for F to be a viable function, there shall
2058 // exist for each argument an implicit conversion sequence
2059 // (13.3.3.1) that converts that argument to the corresponding
2060 // parameter of F.
2061 QualType ParamType = Proto->getArgType(ArgIdx);
2062 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002063 = TryCopyInitialization(Args[ArgIdx], ParamType,
2064 SuppressUserConversions);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002065 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002066 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002067 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002068 break;
2069 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002070 } else {
2071 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2072 // argument for which there is no corresponding parameter is
2073 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2074 Candidate.Conversions[ArgIdx].ConversionKind
2075 = ImplicitConversionSequence::EllipsisConversion;
2076 }
2077 }
2078}
2079
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002080/// \brief Add all of the function declarations in the given function set to
2081/// the overload canddiate set.
2082void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2083 Expr **Args, unsigned NumArgs,
2084 OverloadCandidateSet& CandidateSet,
2085 bool SuppressUserConversions) {
2086 for (FunctionSet::const_iterator F = Functions.begin(),
2087 FEnd = Functions.end();
2088 F != FEnd; ++F)
2089 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2090 SuppressUserConversions);
2091}
2092
Douglas Gregor5ed15042008-11-18 23:14:02 +00002093/// AddMethodCandidate - Adds the given C++ member function to the set
2094/// of candidate functions, using the given function call arguments
2095/// and the object argument (@c Object). For example, in a call
2096/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2097/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2098/// allow user-defined conversions via constructors or conversion
2099/// operators.
2100void
2101Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2102 Expr **Args, unsigned NumArgs,
2103 OverloadCandidateSet& CandidateSet,
2104 bool SuppressUserConversions)
2105{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002106 const FunctionProtoType* Proto
2107 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002108 assert(Proto && "Methods without a prototype cannot be overloaded");
2109 assert(!isa<CXXConversionDecl>(Method) &&
2110 "Use AddConversionCandidate for conversion functions");
2111
2112 // Add this candidate
2113 CandidateSet.push_back(OverloadCandidate());
2114 OverloadCandidate& Candidate = CandidateSet.back();
2115 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002116 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002117 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002118
2119 unsigned NumArgsInProto = Proto->getNumArgs();
2120
2121 // (C++ 13.3.2p2): A candidate function having fewer than m
2122 // parameters is viable only if it has an ellipsis in its parameter
2123 // list (8.3.5).
2124 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2125 Candidate.Viable = false;
2126 return;
2127 }
2128
2129 // (C++ 13.3.2p2): A candidate function having more than m parameters
2130 // is viable only if the (m+1)st parameter has a default argument
2131 // (8.3.6). For the purposes of overload resolution, the
2132 // parameter list is truncated on the right, so that there are
2133 // exactly m parameters.
2134 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2135 if (NumArgs < MinRequiredArgs) {
2136 // Not enough arguments.
2137 Candidate.Viable = false;
2138 return;
2139 }
2140
2141 Candidate.Viable = true;
2142 Candidate.Conversions.resize(NumArgs + 1);
2143
Douglas Gregor3257fb52008-12-22 05:46:06 +00002144 if (Method->isStatic() || !Object)
2145 // The implicit object argument is ignored.
2146 Candidate.IgnoreObjectArgument = true;
2147 else {
2148 // Determine the implicit conversion sequence for the object
2149 // parameter.
2150 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2151 if (Candidate.Conversions[0].ConversionKind
2152 == ImplicitConversionSequence::BadConversion) {
2153 Candidate.Viable = false;
2154 return;
2155 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002156 }
2157
2158 // Determine the implicit conversion sequences for each of the
2159 // arguments.
2160 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2161 if (ArgIdx < NumArgsInProto) {
2162 // (C++ 13.3.2p3): for F to be a viable function, there shall
2163 // exist for each argument an implicit conversion sequence
2164 // (13.3.3.1) that converts that argument to the corresponding
2165 // parameter of F.
2166 QualType ParamType = Proto->getArgType(ArgIdx);
2167 Candidate.Conversions[ArgIdx + 1]
2168 = TryCopyInitialization(Args[ArgIdx], ParamType,
2169 SuppressUserConversions);
2170 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2171 == ImplicitConversionSequence::BadConversion) {
2172 Candidate.Viable = false;
2173 break;
2174 }
2175 } else {
2176 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2177 // argument for which there is no corresponding parameter is
2178 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2179 Candidate.Conversions[ArgIdx + 1].ConversionKind
2180 = ImplicitConversionSequence::EllipsisConversion;
2181 }
2182 }
2183}
2184
Douglas Gregor60714f92008-11-07 22:36:19 +00002185/// AddConversionCandidate - Add a C++ conversion function as a
2186/// candidate in the candidate set (C++ [over.match.conv],
2187/// C++ [over.match.copy]). From is the expression we're converting from,
2188/// and ToType is the type that we're eventually trying to convert to
2189/// (which may or may not be the same type as the type that the
2190/// conversion function produces).
2191void
2192Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2193 Expr *From, QualType ToType,
2194 OverloadCandidateSet& CandidateSet) {
2195 // Add this candidate
2196 CandidateSet.push_back(OverloadCandidate());
2197 OverloadCandidate& Candidate = CandidateSet.back();
2198 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002199 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002200 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002201 Candidate.FinalConversion.setAsIdentityConversion();
2202 Candidate.FinalConversion.FromTypePtr
2203 = Conversion->getConversionType().getAsOpaquePtr();
2204 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2205
Douglas Gregor5ed15042008-11-18 23:14:02 +00002206 // Determine the implicit conversion sequence for the implicit
2207 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002208 Candidate.Viable = true;
2209 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002210 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002211
Douglas Gregor60714f92008-11-07 22:36:19 +00002212 if (Candidate.Conversions[0].ConversionKind
2213 == ImplicitConversionSequence::BadConversion) {
2214 Candidate.Viable = false;
2215 return;
2216 }
2217
2218 // To determine what the conversion from the result of calling the
2219 // conversion function to the type we're eventually trying to
2220 // convert to (ToType), we need to synthesize a call to the
2221 // conversion function and attempt copy initialization from it. This
2222 // makes sure that we get the right semantics with respect to
2223 // lvalues/rvalues and the type. Fortunately, we can allocate this
2224 // call on the stack and we don't need its arguments to be
2225 // well-formed.
2226 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2227 SourceLocation());
2228 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregor70d26122008-11-12 17:17:38 +00002229 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002230
2231 // Note that it is safe to allocate CallExpr on the stack here because
2232 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2233 // allocator).
2234 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002235 Conversion->getConversionType().getNonReferenceType(),
2236 SourceLocation());
2237 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2238 switch (ICS.ConversionKind) {
2239 case ImplicitConversionSequence::StandardConversion:
2240 Candidate.FinalConversion = ICS.Standard;
2241 break;
2242
2243 case ImplicitConversionSequence::BadConversion:
2244 Candidate.Viable = false;
2245 break;
2246
2247 default:
2248 assert(false &&
2249 "Can only end up with a standard conversion sequence or failure");
2250 }
2251}
2252
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002253/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2254/// converts the given @c Object to a function pointer via the
2255/// conversion function @c Conversion, and then attempts to call it
2256/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2257/// the type of function that we'll eventually be calling.
2258void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002259 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002260 Expr *Object, Expr **Args, unsigned NumArgs,
2261 OverloadCandidateSet& CandidateSet) {
2262 CandidateSet.push_back(OverloadCandidate());
2263 OverloadCandidate& Candidate = CandidateSet.back();
2264 Candidate.Function = 0;
2265 Candidate.Surrogate = Conversion;
2266 Candidate.Viable = true;
2267 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002268 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002269 Candidate.Conversions.resize(NumArgs + 1);
2270
2271 // Determine the implicit conversion sequence for the implicit
2272 // object parameter.
2273 ImplicitConversionSequence ObjectInit
2274 = TryObjectArgumentInitialization(Object, Conversion);
2275 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2276 Candidate.Viable = false;
2277 return;
2278 }
2279
2280 // The first conversion is actually a user-defined conversion whose
2281 // first conversion is ObjectInit's standard conversion (which is
2282 // effectively a reference binding). Record it as such.
2283 Candidate.Conversions[0].ConversionKind
2284 = ImplicitConversionSequence::UserDefinedConversion;
2285 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2286 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2287 Candidate.Conversions[0].UserDefined.After
2288 = Candidate.Conversions[0].UserDefined.Before;
2289 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2290
2291 // Find the
2292 unsigned NumArgsInProto = Proto->getNumArgs();
2293
2294 // (C++ 13.3.2p2): A candidate function having fewer than m
2295 // parameters is viable only if it has an ellipsis in its parameter
2296 // list (8.3.5).
2297 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2298 Candidate.Viable = false;
2299 return;
2300 }
2301
2302 // Function types don't have any default arguments, so just check if
2303 // we have enough arguments.
2304 if (NumArgs < NumArgsInProto) {
2305 // Not enough arguments.
2306 Candidate.Viable = false;
2307 return;
2308 }
2309
2310 // Determine the implicit conversion sequences for each of the
2311 // arguments.
2312 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2313 if (ArgIdx < NumArgsInProto) {
2314 // (C++ 13.3.2p3): for F to be a viable function, there shall
2315 // exist for each argument an implicit conversion sequence
2316 // (13.3.3.1) that converts that argument to the corresponding
2317 // parameter of F.
2318 QualType ParamType = Proto->getArgType(ArgIdx);
2319 Candidate.Conversions[ArgIdx + 1]
2320 = TryCopyInitialization(Args[ArgIdx], ParamType,
2321 /*SuppressUserConversions=*/false);
2322 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2323 == ImplicitConversionSequence::BadConversion) {
2324 Candidate.Viable = false;
2325 break;
2326 }
2327 } else {
2328 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2329 // argument for which there is no corresponding parameter is
2330 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2331 Candidate.Conversions[ArgIdx + 1].ConversionKind
2332 = ImplicitConversionSequence::EllipsisConversion;
2333 }
2334 }
2335}
2336
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002337// FIXME: This will eventually be removed, once we've migrated all of
2338// the operator overloading logic over to the scheme used by binary
2339// operators, which works for template instantiation.
2340void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002341 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002342 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002343 OverloadCandidateSet& CandidateSet,
2344 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002345
2346 FunctionSet Functions;
2347
2348 QualType T1 = Args[0]->getType();
2349 QualType T2;
2350 if (NumArgs > 1)
2351 T2 = Args[1]->getType();
2352
2353 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2354 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2355 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2356 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2357 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2358 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2359}
2360
2361/// \brief Add overload candidates for overloaded operators that are
2362/// member functions.
2363///
2364/// Add the overloaded operator candidates that are member functions
2365/// for the operator Op that was used in an operator expression such
2366/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2367/// CandidateSet will store the added overload candidates. (C++
2368/// [over.match.oper]).
2369void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2370 SourceLocation OpLoc,
2371 Expr **Args, unsigned NumArgs,
2372 OverloadCandidateSet& CandidateSet,
2373 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002374 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2375
2376 // C++ [over.match.oper]p3:
2377 // For a unary operator @ with an operand of a type whose
2378 // cv-unqualified version is T1, and for a binary operator @ with
2379 // a left operand of a type whose cv-unqualified version is T1 and
2380 // a right operand of a type whose cv-unqualified version is T2,
2381 // three sets of candidate functions, designated member
2382 // candidates, non-member candidates and built-in candidates, are
2383 // constructed as follows:
2384 QualType T1 = Args[0]->getType();
2385 QualType T2;
2386 if (NumArgs > 1)
2387 T2 = Args[1]->getType();
2388
2389 // -- If T1 is a class type, the set of member candidates is the
2390 // result of the qualified lookup of T1::operator@
2391 // (13.3.1.1.1); otherwise, the set of member candidates is
2392 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002393 // FIXME: Lookup in base classes, too!
Douglas Gregor5ed15042008-11-18 23:14:02 +00002394 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002395 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00002396 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002397 Oper != OperEnd; ++Oper)
2398 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2399 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002400 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002401 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002402}
2403
Douglas Gregor70d26122008-11-12 17:17:38 +00002404/// AddBuiltinCandidate - Add a candidate for a built-in
2405/// operator. ResultTy and ParamTys are the result and parameter types
2406/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002407/// arguments being passed to the candidate. IsAssignmentOperator
2408/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002409/// operator. NumContextualBoolArguments is the number of arguments
2410/// (at the beginning of the argument list) that will be contextually
2411/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002412void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2413 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002414 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002415 bool IsAssignmentOperator,
2416 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002417 // Add this candidate
2418 CandidateSet.push_back(OverloadCandidate());
2419 OverloadCandidate& Candidate = CandidateSet.back();
2420 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002421 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002422 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002423 Candidate.BuiltinTypes.ResultTy = ResultTy;
2424 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2425 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2426
2427 // Determine the implicit conversion sequences for each of the
2428 // arguments.
2429 Candidate.Viable = true;
2430 Candidate.Conversions.resize(NumArgs);
2431 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002432 // C++ [over.match.oper]p4:
2433 // For the built-in assignment operators, conversions of the
2434 // left operand are restricted as follows:
2435 // -- no temporaries are introduced to hold the left operand, and
2436 // -- no user-defined conversions are applied to the left
2437 // operand to achieve a type match with the left-most
2438 // parameter of a built-in candidate.
2439 //
2440 // We block these conversions by turning off user-defined
2441 // conversions, since that is the only way that initialization of
2442 // a reference to a non-class type can occur from something that
2443 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002444 if (ArgIdx < NumContextualBoolArguments) {
2445 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2446 "Contextual conversion to bool requires bool type");
2447 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2448 } else {
2449 Candidate.Conversions[ArgIdx]
2450 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2451 ArgIdx == 0 && IsAssignmentOperator);
2452 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002453 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002454 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002455 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002456 break;
2457 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002458 }
2459}
2460
2461/// BuiltinCandidateTypeSet - A set of types that will be used for the
2462/// candidate operator functions for built-in operators (C++
2463/// [over.built]). The types are separated into pointer types and
2464/// enumeration types.
2465class BuiltinCandidateTypeSet {
2466 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002467 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002468
2469 /// PointerTypes - The set of pointer types that will be used in the
2470 /// built-in candidates.
2471 TypeSet PointerTypes;
2472
2473 /// EnumerationTypes - The set of enumeration types that will be
2474 /// used in the built-in candidates.
2475 TypeSet EnumerationTypes;
2476
2477 /// Context - The AST context in which we will build the type sets.
2478 ASTContext &Context;
2479
2480 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2481
2482public:
2483 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002484 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002485
2486 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2487
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002488 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2489 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002490
2491 /// pointer_begin - First pointer type found;
2492 iterator pointer_begin() { return PointerTypes.begin(); }
2493
2494 /// pointer_end - Last pointer type found;
2495 iterator pointer_end() { return PointerTypes.end(); }
2496
2497 /// enumeration_begin - First enumeration type found;
2498 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2499
2500 /// enumeration_end - Last enumeration type found;
2501 iterator enumeration_end() { return EnumerationTypes.end(); }
2502};
2503
2504/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2505/// the set of pointer types along with any more-qualified variants of
2506/// that type. For example, if @p Ty is "int const *", this routine
2507/// will add "int const *", "int const volatile *", "int const
2508/// restrict *", and "int const volatile restrict *" to the set of
2509/// pointer types. Returns true if the add of @p Ty itself succeeded,
2510/// false otherwise.
2511bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2512 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002513 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002514 return false;
2515
2516 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2517 QualType PointeeTy = PointerTy->getPointeeType();
2518 // FIXME: Optimize this so that we don't keep trying to add the same types.
2519
2520 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2521 // with all pointer conversions that don't cast away constness?
2522 if (!PointeeTy.isConstQualified())
2523 AddWithMoreQualifiedTypeVariants
2524 (Context.getPointerType(PointeeTy.withConst()));
2525 if (!PointeeTy.isVolatileQualified())
2526 AddWithMoreQualifiedTypeVariants
2527 (Context.getPointerType(PointeeTy.withVolatile()));
2528 if (!PointeeTy.isRestrictQualified())
2529 AddWithMoreQualifiedTypeVariants
2530 (Context.getPointerType(PointeeTy.withRestrict()));
2531 }
2532
2533 return true;
2534}
2535
2536/// AddTypesConvertedFrom - Add each of the types to which the type @p
2537/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002538/// primarily interested in pointer types and enumeration types.
2539/// AllowUserConversions is true if we should look at the conversion
2540/// functions of a class type, and AllowExplicitConversions if we
2541/// should also include the explicit conversion functions of a class
2542/// type.
2543void
2544BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2545 bool AllowUserConversions,
2546 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002547 // Only deal with canonical types.
2548 Ty = Context.getCanonicalType(Ty);
2549
2550 // Look through reference types; they aren't part of the type of an
2551 // expression for the purposes of conversions.
2552 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2553 Ty = RefTy->getPointeeType();
2554
2555 // We don't care about qualifiers on the type.
2556 Ty = Ty.getUnqualifiedType();
2557
2558 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2559 QualType PointeeTy = PointerTy->getPointeeType();
2560
2561 // Insert our type, and its more-qualified variants, into the set
2562 // of types.
2563 if (!AddWithMoreQualifiedTypeVariants(Ty))
2564 return;
2565
2566 // Add 'cv void*' to our set of types.
2567 if (!Ty->isVoidType()) {
2568 QualType QualVoid
2569 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2570 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2571 }
2572
2573 // If this is a pointer to a class type, add pointers to its bases
2574 // (with the same level of cv-qualification as the original
2575 // derived class, of course).
2576 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2577 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2578 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2579 Base != ClassDecl->bases_end(); ++Base) {
2580 QualType BaseTy = Context.getCanonicalType(Base->getType());
2581 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2582
2583 // Add the pointer type, recursively, so that we get all of
2584 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002585 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002586 }
2587 }
2588 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002589 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002590 } else if (AllowUserConversions) {
2591 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2592 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2593 // FIXME: Visit conversion functions in the base classes, too.
2594 OverloadedFunctionDecl *Conversions
2595 = ClassDecl->getConversionFunctions();
2596 for (OverloadedFunctionDecl::function_iterator Func
2597 = Conversions->function_begin();
2598 Func != Conversions->function_end(); ++Func) {
2599 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002600 if (AllowExplicitConversions || !Conv->isExplicit())
2601 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002602 }
2603 }
2604 }
2605}
2606
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002607/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2608/// operator overloads to the candidate set (C++ [over.built]), based
2609/// on the operator @p Op and the arguments given. For example, if the
2610/// operator is a binary '+', this routine might add "int
2611/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002612void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002613Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2614 Expr **Args, unsigned NumArgs,
2615 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002616 // The set of "promoted arithmetic types", which are the arithmetic
2617 // types are that preserved by promotion (C++ [over.built]p2). Note
2618 // that the first few of these types are the promoted integral
2619 // types; these types need to be first.
2620 // FIXME: What about complex?
2621 const unsigned FirstIntegralType = 0;
2622 const unsigned LastIntegralType = 13;
2623 const unsigned FirstPromotedIntegralType = 7,
2624 LastPromotedIntegralType = 13;
2625 const unsigned FirstPromotedArithmeticType = 7,
2626 LastPromotedArithmeticType = 16;
2627 const unsigned NumArithmeticTypes = 16;
2628 QualType ArithmeticTypes[NumArithmeticTypes] = {
2629 Context.BoolTy, Context.CharTy, Context.WCharTy,
2630 Context.SignedCharTy, Context.ShortTy,
2631 Context.UnsignedCharTy, Context.UnsignedShortTy,
2632 Context.IntTy, Context.LongTy, Context.LongLongTy,
2633 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2634 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2635 };
2636
2637 // Find all of the types that the arguments can convert to, but only
2638 // if the operator we're looking at has built-in operator candidates
2639 // that make use of these types.
2640 BuiltinCandidateTypeSet CandidateTypes(Context);
2641 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2642 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002643 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002644 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002645 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2646 (Op == OO_Star && NumArgs == 1)) {
2647 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002648 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2649 true,
2650 (Op == OO_Exclaim ||
2651 Op == OO_AmpAmp ||
2652 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002653 }
2654
2655 bool isComparison = false;
2656 switch (Op) {
2657 case OO_None:
2658 case NUM_OVERLOADED_OPERATORS:
2659 assert(false && "Expected an overloaded operator");
2660 break;
2661
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002662 case OO_Star: // '*' is either unary or binary
2663 if (NumArgs == 1)
2664 goto UnaryStar;
2665 else
2666 goto BinaryStar;
2667 break;
2668
2669 case OO_Plus: // '+' is either unary or binary
2670 if (NumArgs == 1)
2671 goto UnaryPlus;
2672 else
2673 goto BinaryPlus;
2674 break;
2675
2676 case OO_Minus: // '-' is either unary or binary
2677 if (NumArgs == 1)
2678 goto UnaryMinus;
2679 else
2680 goto BinaryMinus;
2681 break;
2682
2683 case OO_Amp: // '&' is either unary or binary
2684 if (NumArgs == 1)
2685 goto UnaryAmp;
2686 else
2687 goto BinaryAmp;
2688
2689 case OO_PlusPlus:
2690 case OO_MinusMinus:
2691 // C++ [over.built]p3:
2692 //
2693 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2694 // is either volatile or empty, there exist candidate operator
2695 // functions of the form
2696 //
2697 // VQ T& operator++(VQ T&);
2698 // T operator++(VQ T&, int);
2699 //
2700 // C++ [over.built]p4:
2701 //
2702 // For every pair (T, VQ), where T is an arithmetic type other
2703 // than bool, and VQ is either volatile or empty, there exist
2704 // candidate operator functions of the form
2705 //
2706 // VQ T& operator--(VQ T&);
2707 // T operator--(VQ T&, int);
2708 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2709 Arith < NumArithmeticTypes; ++Arith) {
2710 QualType ArithTy = ArithmeticTypes[Arith];
2711 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00002712 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002713
2714 // Non-volatile version.
2715 if (NumArgs == 1)
2716 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2717 else
2718 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2719
2720 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00002721 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002722 if (NumArgs == 1)
2723 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2724 else
2725 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2726 }
2727
2728 // C++ [over.built]p5:
2729 //
2730 // For every pair (T, VQ), where T is a cv-qualified or
2731 // cv-unqualified object type, and VQ is either volatile or
2732 // empty, there exist candidate operator functions of the form
2733 //
2734 // T*VQ& operator++(T*VQ&);
2735 // T*VQ& operator--(T*VQ&);
2736 // T* operator++(T*VQ&, int);
2737 // T* operator--(T*VQ&, int);
2738 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2739 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2740 // Skip pointer types that aren't pointers to object types.
Douglas Gregor26ea1222009-03-24 20:32:41 +00002741 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002742 continue;
2743
2744 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002745 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002746 };
2747
2748 // Without volatile
2749 if (NumArgs == 1)
2750 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2751 else
2752 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2753
2754 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2755 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00002756 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002757 if (NumArgs == 1)
2758 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2759 else
2760 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2761 }
2762 }
2763 break;
2764
2765 UnaryStar:
2766 // C++ [over.built]p6:
2767 // For every cv-qualified or cv-unqualified object type T, there
2768 // exist candidate operator functions of the form
2769 //
2770 // T& operator*(T*);
2771 //
2772 // C++ [over.built]p7:
2773 // For every function type T, there exist candidate operator
2774 // functions of the form
2775 // T& operator*(T*);
2776 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2777 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2778 QualType ParamTy = *Ptr;
2779 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00002780 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002781 &ParamTy, Args, 1, CandidateSet);
2782 }
2783 break;
2784
2785 UnaryPlus:
2786 // C++ [over.built]p8:
2787 // For every type T, there exist candidate operator functions of
2788 // the form
2789 //
2790 // T* operator+(T*);
2791 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2792 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2793 QualType ParamTy = *Ptr;
2794 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2795 }
2796
2797 // Fall through
2798
2799 UnaryMinus:
2800 // C++ [over.built]p9:
2801 // For every promoted arithmetic type T, there exist candidate
2802 // operator functions of the form
2803 //
2804 // T operator+(T);
2805 // T operator-(T);
2806 for (unsigned Arith = FirstPromotedArithmeticType;
2807 Arith < LastPromotedArithmeticType; ++Arith) {
2808 QualType ArithTy = ArithmeticTypes[Arith];
2809 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2810 }
2811 break;
2812
2813 case OO_Tilde:
2814 // C++ [over.built]p10:
2815 // For every promoted integral type T, there exist candidate
2816 // operator functions of the form
2817 //
2818 // T operator~(T);
2819 for (unsigned Int = FirstPromotedIntegralType;
2820 Int < LastPromotedIntegralType; ++Int) {
2821 QualType IntTy = ArithmeticTypes[Int];
2822 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2823 }
2824 break;
2825
Douglas Gregor70d26122008-11-12 17:17:38 +00002826 case OO_New:
2827 case OO_Delete:
2828 case OO_Array_New:
2829 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00002830 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002831 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00002832 break;
2833
2834 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002835 UnaryAmp:
2836 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00002837 // C++ [over.match.oper]p3:
2838 // -- For the operator ',', the unary operator '&', or the
2839 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00002840 break;
2841
2842 case OO_Less:
2843 case OO_Greater:
2844 case OO_LessEqual:
2845 case OO_GreaterEqual:
2846 case OO_EqualEqual:
2847 case OO_ExclaimEqual:
2848 // C++ [over.built]p15:
2849 //
2850 // For every pointer or enumeration type T, there exist
2851 // candidate operator functions of the form
2852 //
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 // bool operator!=(T, T);
2859 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2860 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2861 QualType ParamTypes[2] = { *Ptr, *Ptr };
2862 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2863 }
2864 for (BuiltinCandidateTypeSet::iterator Enum
2865 = CandidateTypes.enumeration_begin();
2866 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2867 QualType ParamTypes[2] = { *Enum, *Enum };
2868 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2869 }
2870
2871 // Fall through.
2872 isComparison = true;
2873
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002874 BinaryPlus:
2875 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00002876 if (!isComparison) {
2877 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2878
2879 // C++ [over.built]p13:
2880 //
2881 // For every cv-qualified or cv-unqualified object type T
2882 // there exist candidate operator functions of the form
2883 //
2884 // T* operator+(T*, ptrdiff_t);
2885 // T& operator[](T*, ptrdiff_t); [BELOW]
2886 // T* operator-(T*, ptrdiff_t);
2887 // T* operator+(ptrdiff_t, T*);
2888 // T& operator[](ptrdiff_t, T*); [BELOW]
2889 //
2890 // C++ [over.built]p14:
2891 //
2892 // For every T, where T is a pointer to object type, there
2893 // exist candidate operator functions of the form
2894 //
2895 // ptrdiff_t operator-(T, T);
2896 for (BuiltinCandidateTypeSet::iterator Ptr
2897 = CandidateTypes.pointer_begin();
2898 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2899 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2900
2901 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2902 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2903
2904 if (Op == OO_Plus) {
2905 // T* operator+(ptrdiff_t, T*);
2906 ParamTypes[0] = ParamTypes[1];
2907 ParamTypes[1] = *Ptr;
2908 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2909 } else {
2910 // ptrdiff_t operator-(T, T);
2911 ParamTypes[1] = *Ptr;
2912 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2913 Args, 2, CandidateSet);
2914 }
2915 }
2916 }
2917 // Fall through
2918
Douglas Gregor70d26122008-11-12 17:17:38 +00002919 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002920 BinaryStar:
Douglas Gregor70d26122008-11-12 17:17:38 +00002921 // C++ [over.built]p12:
2922 //
2923 // For every pair of promoted arithmetic types L and R, there
2924 // exist candidate operator functions of the form
2925 //
2926 // LR operator*(L, R);
2927 // LR operator/(L, R);
2928 // LR operator+(L, R);
2929 // LR 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 // bool operator!=(L, R);
2936 //
2937 // where LR is the result of the usual arithmetic conversions
2938 // between types L and R.
2939 for (unsigned Left = FirstPromotedArithmeticType;
2940 Left < LastPromotedArithmeticType; ++Left) {
2941 for (unsigned Right = FirstPromotedArithmeticType;
2942 Right < LastPromotedArithmeticType; ++Right) {
2943 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2944 QualType Result
2945 = isComparison? Context.BoolTy
2946 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2947 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2948 }
2949 }
2950 break;
2951
2952 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002953 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00002954 case OO_Caret:
2955 case OO_Pipe:
2956 case OO_LessLess:
2957 case OO_GreaterGreater:
2958 // C++ [over.built]p17:
2959 //
2960 // For every pair of promoted integral types L and R, there
2961 // exist candidate operator functions of the form
2962 //
2963 // LR operator%(L, R);
2964 // LR operator&(L, R);
2965 // LR operator^(L, R);
2966 // LR operator|(L, R);
2967 // L operator<<(L, R);
2968 // L operator>>(L, R);
2969 //
2970 // where LR is the result of the usual arithmetic conversions
2971 // between types L and R.
2972 for (unsigned Left = FirstPromotedIntegralType;
2973 Left < LastPromotedIntegralType; ++Left) {
2974 for (unsigned Right = FirstPromotedIntegralType;
2975 Right < LastPromotedIntegralType; ++Right) {
2976 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2977 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2978 ? LandR[0]
2979 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2980 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2981 }
2982 }
2983 break;
2984
2985 case OO_Equal:
2986 // C++ [over.built]p20:
2987 //
2988 // For every pair (T, VQ), where T is an enumeration or
2989 // (FIXME:) pointer to member type and VQ is either volatile or
2990 // empty, there exist candidate operator functions of the form
2991 //
2992 // VQ T& operator=(VQ T&, T);
2993 for (BuiltinCandidateTypeSet::iterator Enum
2994 = CandidateTypes.enumeration_begin();
2995 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2996 QualType ParamTypes[2];
2997
2998 // T& operator=(T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00002999 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregor70d26122008-11-12 17:17:38 +00003000 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003001 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003002 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003003
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003004 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3005 // volatile T& operator=(volatile T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003006 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003007 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003008 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003009 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003010 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003011 }
3012 // Fall through.
3013
3014 case OO_PlusEqual:
3015 case OO_MinusEqual:
3016 // C++ [over.built]p19:
3017 //
3018 // For every pair (T, VQ), where T is any type and VQ is either
3019 // volatile or empty, there exist candidate operator functions
3020 // of the form
3021 //
3022 // T*VQ& operator=(T*VQ&, T*);
3023 //
3024 // C++ [over.built]p21:
3025 //
3026 // For every pair (T, VQ), where T is a cv-qualified or
3027 // cv-unqualified object type and VQ is either volatile or
3028 // empty, there exist candidate operator functions of the form
3029 //
3030 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3031 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3032 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3033 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3034 QualType ParamTypes[2];
3035 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3036
3037 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003038 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003039 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3040 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003041
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003042 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3043 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003044 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003045 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3046 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003047 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003048 }
3049 // Fall through.
3050
3051 case OO_StarEqual:
3052 case OO_SlashEqual:
3053 // C++ [over.built]p18:
3054 //
3055 // For every triple (L, VQ, R), where L is an arithmetic type,
3056 // VQ is either volatile or empty, and R is a promoted
3057 // arithmetic type, there exist candidate operator functions of
3058 // the form
3059 //
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 // VQ L& operator-=(VQ L&, R);
3065 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3066 for (unsigned Right = FirstPromotedArithmeticType;
3067 Right < LastPromotedArithmeticType; ++Right) {
3068 QualType ParamTypes[2];
3069 ParamTypes[1] = ArithmeticTypes[Right];
3070
3071 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003072 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003073 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3074 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003075
3076 // Add this built-in operator as a candidate (VQ is 'volatile').
3077 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003078 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003079 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3080 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003081 }
3082 }
3083 break;
3084
3085 case OO_PercentEqual:
3086 case OO_LessLessEqual:
3087 case OO_GreaterGreaterEqual:
3088 case OO_AmpEqual:
3089 case OO_CaretEqual:
3090 case OO_PipeEqual:
3091 // C++ [over.built]p22:
3092 //
3093 // For every triple (L, VQ, R), where L is an integral type, VQ
3094 // is either volatile or empty, and R is a promoted integral
3095 // type, there exist candidate operator functions of the form
3096 //
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 // VQ L& operator|=(VQ L&, R);
3103 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3104 for (unsigned Right = FirstPromotedIntegralType;
3105 Right < LastPromotedIntegralType; ++Right) {
3106 QualType ParamTypes[2];
3107 ParamTypes[1] = ArithmeticTypes[Right];
3108
3109 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003110 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003111 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3112
3113 // Add this built-in operator as a candidate (VQ is 'volatile').
3114 ParamTypes[0] = ArithmeticTypes[Left];
3115 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003116 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003117 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3118 }
3119 }
3120 break;
3121
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003122 case OO_Exclaim: {
3123 // C++ [over.operator]p23:
3124 //
3125 // There also exist candidate operator functions of the form
3126 //
3127 // bool operator!(bool);
3128 // bool operator&&(bool, bool); [BELOW]
3129 // bool operator||(bool, bool); [BELOW]
3130 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003131 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3132 /*IsAssignmentOperator=*/false,
3133 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003134 break;
3135 }
3136
Douglas Gregor70d26122008-11-12 17:17:38 +00003137 case OO_AmpAmp:
3138 case OO_PipePipe: {
3139 // C++ [over.operator]p23:
3140 //
3141 // There also exist candidate operator functions of the form
3142 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003143 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003144 // bool operator&&(bool, bool);
3145 // bool operator||(bool, bool);
3146 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003147 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3148 /*IsAssignmentOperator=*/false,
3149 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003150 break;
3151 }
3152
3153 case OO_Subscript:
3154 // C++ [over.built]p13:
3155 //
3156 // For every cv-qualified or cv-unqualified object type T there
3157 // exist candidate operator functions of the form
3158 //
3159 // T* operator+(T*, ptrdiff_t); [ABOVE]
3160 // T& operator[](T*, ptrdiff_t);
3161 // T* operator-(T*, ptrdiff_t); [ABOVE]
3162 // T* operator+(ptrdiff_t, T*); [ABOVE]
3163 // T& operator[](ptrdiff_t, T*);
3164 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3165 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3166 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3167 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003168 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003169
3170 // T& operator[](T*, ptrdiff_t)
3171 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3172
3173 // T& operator[](ptrdiff_t, T*);
3174 ParamTypes[0] = ParamTypes[1];
3175 ParamTypes[1] = *Ptr;
3176 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3177 }
3178 break;
3179
3180 case OO_ArrowStar:
3181 // FIXME: No support for pointer-to-members yet.
3182 break;
3183 }
3184}
3185
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003186/// \brief Add function candidates found via argument-dependent lookup
3187/// to the set of overloading candidates.
3188///
3189/// This routine performs argument-dependent name lookup based on the
3190/// given function name (which may also be an operator name) and adds
3191/// all of the overload candidates found by ADL to the overload
3192/// candidate set (C++ [basic.lookup.argdep]).
3193void
3194Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3195 Expr **Args, unsigned NumArgs,
3196 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003197 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003198
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003199 // Record all of the function candidates that we've already
3200 // added to the overload set, so that we don't add those same
3201 // candidates a second time.
3202 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3203 CandEnd = CandidateSet.end();
3204 Cand != CandEnd; ++Cand)
3205 if (Cand->Function)
3206 Functions.insert(Cand->Function);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003207
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003208 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003209
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003210 // Erase all of the candidates we already knew about.
3211 // FIXME: This is suboptimal. Is there a better way?
3212 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3213 CandEnd = CandidateSet.end();
3214 Cand != CandEnd; ++Cand)
3215 if (Cand->Function)
3216 Functions.erase(Cand->Function);
3217
3218 // For each of the ADL candidates we found, add it to the overload
3219 // set.
3220 for (FunctionSet::iterator Func = Functions.begin(),
3221 FuncEnd = Functions.end();
3222 Func != FuncEnd; ++Func)
3223 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003224}
3225
Douglas Gregord2baafd2008-10-21 16:13:35 +00003226/// isBetterOverloadCandidate - Determines whether the first overload
3227/// candidate is a better candidate than the second (C++ 13.3.3p1).
3228bool
3229Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3230 const OverloadCandidate& Cand2)
3231{
3232 // Define viable functions to be better candidates than non-viable
3233 // functions.
3234 if (!Cand2.Viable)
3235 return Cand1.Viable;
3236 else if (!Cand1.Viable)
3237 return false;
3238
Douglas Gregor3257fb52008-12-22 05:46:06 +00003239 // C++ [over.match.best]p1:
3240 //
3241 // -- if F is a static member function, ICS1(F) is defined such
3242 // that ICS1(F) is neither better nor worse than ICS1(G) for
3243 // any function G, and, symmetrically, ICS1(G) is neither
3244 // better nor worse than ICS1(F).
3245 unsigned StartArg = 0;
3246 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3247 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003248
3249 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3250 // function than another viable function F2 if for all arguments i,
3251 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3252 // then...
3253 unsigned NumArgs = Cand1.Conversions.size();
3254 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3255 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003256 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003257 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3258 Cand2.Conversions[ArgIdx])) {
3259 case ImplicitConversionSequence::Better:
3260 // Cand1 has a better conversion sequence.
3261 HasBetterConversion = true;
3262 break;
3263
3264 case ImplicitConversionSequence::Worse:
3265 // Cand1 can't be better than Cand2.
3266 return false;
3267
3268 case ImplicitConversionSequence::Indistinguishable:
3269 // Do nothing.
3270 break;
3271 }
3272 }
3273
3274 if (HasBetterConversion)
3275 return true;
3276
Douglas Gregor70d26122008-11-12 17:17:38 +00003277 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3278 // implemented, but they require template support.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003279
Douglas Gregor60714f92008-11-07 22:36:19 +00003280 // C++ [over.match.best]p1b4:
3281 //
3282 // -- the context is an initialization by user-defined conversion
3283 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3284 // from the return type of F1 to the destination type (i.e.,
3285 // the type of the entity being initialized) is a better
3286 // conversion sequence than the standard conversion sequence
3287 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003288 if (Cand1.Function && Cand2.Function &&
3289 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003290 isa<CXXConversionDecl>(Cand2.Function)) {
3291 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3292 Cand2.FinalConversion)) {
3293 case ImplicitConversionSequence::Better:
3294 // Cand1 has a better conversion sequence.
3295 return true;
3296
3297 case ImplicitConversionSequence::Worse:
3298 // Cand1 can't be better than Cand2.
3299 return false;
3300
3301 case ImplicitConversionSequence::Indistinguishable:
3302 // Do nothing
3303 break;
3304 }
3305 }
3306
Douglas Gregord2baafd2008-10-21 16:13:35 +00003307 return false;
3308}
3309
3310/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3311/// within an overload candidate set. If overloading is successful,
3312/// the result will be OR_Success and Best will be set to point to the
3313/// best viable function within the candidate set. Otherwise, one of
3314/// several kinds of errors will be returned; see
3315/// Sema::OverloadingResult.
3316Sema::OverloadingResult
3317Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3318 OverloadCandidateSet::iterator& Best)
3319{
3320 // Find the best viable function.
3321 Best = CandidateSet.end();
3322 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3323 Cand != CandidateSet.end(); ++Cand) {
3324 if (Cand->Viable) {
3325 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3326 Best = Cand;
3327 }
3328 }
3329
3330 // If we didn't find any viable functions, abort.
3331 if (Best == CandidateSet.end())
3332 return OR_No_Viable_Function;
3333
3334 // Make sure that this function is better than every other viable
3335 // function. If not, we have an ambiguity.
3336 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3337 Cand != CandidateSet.end(); ++Cand) {
3338 if (Cand->Viable &&
3339 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003340 !isBetterOverloadCandidate(*Best, *Cand)) {
3341 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003342 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003343 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003344 }
3345
3346 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003347 if (Best->Function &&
3348 (Best->Function->isDeleted() ||
3349 Best->Function->getAttr<UnavailableAttr>()))
3350 return OR_Deleted;
3351
3352 // If Best refers to a function that is either deleted (C++0x) or
3353 // unavailable (Clang extension) report an error.
3354
Douglas Gregord2baafd2008-10-21 16:13:35 +00003355 return OR_Success;
3356}
3357
3358/// PrintOverloadCandidates - When overload resolution fails, prints
3359/// diagnostic messages containing the candidates in the candidate
3360/// set. If OnlyViable is true, only viable candidates will be printed.
3361void
3362Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3363 bool OnlyViable)
3364{
3365 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3366 LastCand = CandidateSet.end();
3367 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003368 if (Cand->Viable || !OnlyViable) {
3369 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003370 if (Cand->Function->isDeleted() ||
3371 Cand->Function->getAttr<UnavailableAttr>()) {
3372 // Deleted or "unavailable" function.
3373 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3374 << Cand->Function->isDeleted();
3375 } else {
3376 // Normal function
3377 // FIXME: Give a better reason!
3378 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3379 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003380 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003381 // Desugar the type of the surrogate down to a function type,
3382 // retaining as many typedefs as possible while still showing
3383 // the function type (and, therefore, its parameter types).
3384 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003385 bool isLValueReference = false;
3386 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003387 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003388 if (const LValueReferenceType *FnTypeRef =
3389 FnType->getAsLValueReferenceType()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003390 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003391 isLValueReference = true;
3392 } else if (const RValueReferenceType *FnTypeRef =
3393 FnType->getAsRValueReferenceType()) {
3394 FnType = FnTypeRef->getPointeeType();
3395 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003396 }
3397 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3398 FnType = FnTypePtr->getPointeeType();
3399 isPointer = true;
3400 }
3401 // Desugar down to a function type.
3402 FnType = QualType(FnType->getAsFunctionType(), 0);
3403 // Reconstruct the pointer/reference as appropriate.
3404 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003405 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3406 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003407
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003408 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003409 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003410 } else {
3411 // FIXME: We need to get the identifier in here
3412 // FIXME: Do we want the error message to point at the
3413 // operator? (built-ins won't have a location)
3414 QualType FnType
3415 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3416 Cand->BuiltinTypes.ParamTypes,
3417 Cand->Conversions.size(),
3418 false, 0);
3419
Chris Lattner4bfd2232008-11-24 06:25:27 +00003420 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003421 }
3422 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003423 }
3424}
3425
Douglas Gregor45014fd2008-11-10 20:40:00 +00003426/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3427/// an overloaded function (C++ [over.over]), where @p From is an
3428/// expression with overloaded function type and @p ToType is the type
3429/// we're trying to resolve to. For example:
3430///
3431/// @code
3432/// int f(double);
3433/// int f(int);
3434///
3435/// int (*pfd)(double) = f; // selects f(double)
3436/// @endcode
3437///
3438/// This routine returns the resulting FunctionDecl if it could be
3439/// resolved, and NULL otherwise. When @p Complain is true, this
3440/// routine will emit diagnostics if there is an error.
3441FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003442Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003443 bool Complain) {
3444 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003445 bool IsMember = false;
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003446 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003447 FunctionType = ToTypePtr->getPointeeType();
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003448 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3449 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003450 else if (const MemberPointerType *MemTypePtr =
3451 ToType->getAsMemberPointerType()) {
3452 FunctionType = MemTypePtr->getPointeeType();
3453 IsMember = true;
3454 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003455
3456 // We only look at pointers or references to functions.
3457 if (!FunctionType->isFunctionType())
3458 return 0;
3459
3460 // Find the actual overloaded function declaration.
3461 OverloadedFunctionDecl *Ovl = 0;
3462
3463 // C++ [over.over]p1:
3464 // [...] [Note: any redundant set of parentheses surrounding the
3465 // overloaded function name is ignored (5.1). ]
3466 Expr *OvlExpr = From->IgnoreParens();
3467
3468 // C++ [over.over]p1:
3469 // [...] The overloaded function name can be preceded by the &
3470 // operator.
3471 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3472 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3473 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3474 }
3475
3476 // Try to dig out the overloaded function.
3477 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3478 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3479
3480 // If there's no overloaded function declaration, we're done.
3481 if (!Ovl)
3482 return 0;
3483
3484 // Look through all of the overloaded functions, searching for one
3485 // whose type matches exactly.
3486 // FIXME: When templates or using declarations come along, we'll actually
3487 // have to deal with duplicates, partial ordering, etc. For now, we
3488 // can just do a simple search.
3489 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3490 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3491 Fun != Ovl->function_end(); ++Fun) {
3492 // C++ [over.over]p3:
3493 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003494 // targets of type "pointer-to-function" or "reference-to-function."
3495 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003496 // type "pointer-to-member-function."
3497 // Note that according to DR 247, the containing class does not matter.
3498 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3499 // Skip non-static functions when converting to pointer, and static
3500 // when converting to member pointer.
3501 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003502 continue;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003503 } else if (IsMember)
3504 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003505
3506 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3507 return *Fun;
3508 }
3509
3510 return 0;
3511}
3512
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003513/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003514/// (which eventually refers to the declaration Func) and the call
3515/// arguments Args/NumArgs, attempt to resolve the function call down
3516/// to a specific function. If overload resolution succeeds, returns
3517/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003518/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003519/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003520FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003521 DeclarationName UnqualifiedName,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003522 SourceLocation LParenLoc,
3523 Expr **Args, unsigned NumArgs,
3524 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003525 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003526 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003527 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003528
3529 // Add the functions denoted by Callee to the set of candidate
3530 // functions. While we're doing so, track whether argument-dependent
3531 // lookup still applies, per:
3532 //
3533 // C++0x [basic.lookup.argdep]p3:
3534 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3535 // and let Y be the lookup set produced by argument dependent
3536 // lookup (defined as follows). If X contains
3537 //
3538 // -- a declaration of a class member, or
3539 //
3540 // -- a block-scope function declaration that is not a
3541 // using-declaration, or
3542 //
3543 // -- a declaration that is neither a function or a function
3544 // template
3545 //
3546 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003547 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003548 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3549 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3550 FuncEnd = Ovl->function_end();
3551 Func != FuncEnd; ++Func) {
3552 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3553
3554 if ((*Func)->getDeclContext()->isRecord() ||
3555 (*Func)->getDeclContext()->isFunctionOrMethod())
3556 ArgumentDependentLookup = false;
3557 }
3558 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3559 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3560
3561 if (Func->getDeclContext()->isRecord() ||
3562 Func->getDeclContext()->isFunctionOrMethod())
3563 ArgumentDependentLookup = false;
3564 }
3565
3566 if (Callee)
3567 UnqualifiedName = Callee->getDeclName();
3568
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003569 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003570 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003571 CandidateSet);
3572
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003573 OverloadCandidateSet::iterator Best;
3574 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003575 case OR_Success:
3576 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003577
3578 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00003579 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003580 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00003581 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003582 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3583 break;
3584
3585 case OR_Ambiguous:
3586 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003587 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003588 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3589 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00003590
3591 case OR_Deleted:
3592 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3593 << Best->Function->isDeleted()
3594 << UnqualifiedName
3595 << Fn->getSourceRange();
3596 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3597 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003598 }
3599
3600 // Overload resolution failed. Destroy all of the subexpressions and
3601 // return NULL.
3602 Fn->Destroy(Context);
3603 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3604 Args[Arg]->Destroy(Context);
3605 return 0;
3606}
3607
Douglas Gregorc78182d2009-03-13 23:49:33 +00003608/// \brief Create a unary operation that may resolve to an overloaded
3609/// operator.
3610///
3611/// \param OpLoc The location of the operator itself (e.g., '*').
3612///
3613/// \param OpcIn The UnaryOperator::Opcode that describes this
3614/// operator.
3615///
3616/// \param Functions The set of non-member functions that will be
3617/// considered by overload resolution. The caller needs to build this
3618/// set based on the context using, e.g.,
3619/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3620/// set should not contain any member functions; those will be added
3621/// by CreateOverloadedUnaryOp().
3622///
3623/// \param input The input argument.
3624Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3625 unsigned OpcIn,
3626 FunctionSet &Functions,
3627 ExprArg input) {
3628 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3629 Expr *Input = (Expr *)input.get();
3630
3631 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3632 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3633 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3634
3635 Expr *Args[2] = { Input, 0 };
3636 unsigned NumArgs = 1;
3637
3638 // For post-increment and post-decrement, add the implicit '0' as
3639 // the second argument, so that we know this is a post-increment or
3640 // post-decrement.
3641 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3642 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3643 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3644 SourceLocation());
3645 NumArgs = 2;
3646 }
3647
3648 if (Input->isTypeDependent()) {
3649 OverloadedFunctionDecl *Overloads
3650 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3651 for (FunctionSet::iterator Func = Functions.begin(),
3652 FuncEnd = Functions.end();
3653 Func != FuncEnd; ++Func)
3654 Overloads->addOverload(*Func);
3655
3656 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3657 OpLoc, false, false);
3658
3659 input.release();
3660 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3661 &Args[0], NumArgs,
3662 Context.DependentTy,
3663 OpLoc));
3664 }
3665
3666 // Build an empty overload set.
3667 OverloadCandidateSet CandidateSet;
3668
3669 // Add the candidates from the given function set.
3670 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3671
3672 // Add operator candidates that are member functions.
3673 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3674
3675 // Add builtin operator candidates.
3676 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3677
3678 // Perform overload resolution.
3679 OverloadCandidateSet::iterator Best;
3680 switch (BestViableFunction(CandidateSet, Best)) {
3681 case OR_Success: {
3682 // We found a built-in operator or an overloaded operator.
3683 FunctionDecl *FnDecl = Best->Function;
3684
3685 if (FnDecl) {
3686 // We matched an overloaded operator. Build a call to that
3687 // operator.
3688
3689 // Convert the arguments.
3690 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3691 if (PerformObjectArgumentInitialization(Input, Method))
3692 return ExprError();
3693 } else {
3694 // Convert the arguments.
3695 if (PerformCopyInitialization(Input,
3696 FnDecl->getParamDecl(0)->getType(),
3697 "passing"))
3698 return ExprError();
3699 }
3700
3701 // Determine the result type
3702 QualType ResultTy
3703 = FnDecl->getType()->getAsFunctionType()->getResultType();
3704 ResultTy = ResultTy.getNonReferenceType();
3705
3706 // Build the actual expression node.
3707 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3708 SourceLocation());
3709 UsualUnaryConversions(FnExpr);
3710
3711 input.release();
3712 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3713 &Input, 1, ResultTy,
3714 OpLoc));
3715 } else {
3716 // We matched a built-in operator. Convert the arguments, then
3717 // break out so that we will build the appropriate built-in
3718 // operator node.
3719 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3720 Best->Conversions[0], "passing"))
3721 return ExprError();
3722
3723 break;
3724 }
3725 }
3726
3727 case OR_No_Viable_Function:
3728 // No viable function; fall through to handling this as a
3729 // built-in operator, which will produce an error message for us.
3730 break;
3731
3732 case OR_Ambiguous:
3733 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3734 << UnaryOperator::getOpcodeStr(Opc)
3735 << Input->getSourceRange();
3736 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3737 return ExprError();
3738
3739 case OR_Deleted:
3740 Diag(OpLoc, diag::err_ovl_deleted_oper)
3741 << Best->Function->isDeleted()
3742 << UnaryOperator::getOpcodeStr(Opc)
3743 << Input->getSourceRange();
3744 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3745 return ExprError();
3746 }
3747
3748 // Either we found no viable overloaded operator or we matched a
3749 // built-in operator. In either case, fall through to trying to
3750 // build a built-in operation.
3751 input.release();
3752 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
3753}
3754
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003755/// \brief Create a binary operation that may resolve to an overloaded
3756/// operator.
3757///
3758/// \param OpLoc The location of the operator itself (e.g., '+').
3759///
3760/// \param OpcIn The BinaryOperator::Opcode that describes this
3761/// operator.
3762///
3763/// \param Functions The set of non-member functions that will be
3764/// considered by overload resolution. The caller needs to build this
3765/// set based on the context using, e.g.,
3766/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3767/// set should not contain any member functions; those will be added
3768/// by CreateOverloadedBinOp().
3769///
3770/// \param LHS Left-hand argument.
3771/// \param RHS Right-hand argument.
3772Sema::OwningExprResult
3773Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
3774 unsigned OpcIn,
3775 FunctionSet &Functions,
3776 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003777 Expr *Args[2] = { LHS, RHS };
3778
3779 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
3780 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
3781 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3782
3783 // If either side is type-dependent, create an appropriate dependent
3784 // expression.
3785 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
3786 // .* cannot be overloaded.
3787 if (Opc == BinaryOperator::PtrMemD)
3788 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
3789 Context.DependentTy, OpLoc));
3790
3791 OverloadedFunctionDecl *Overloads
3792 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3793 for (FunctionSet::iterator Func = Functions.begin(),
3794 FuncEnd = Functions.end();
3795 Func != FuncEnd; ++Func)
3796 Overloads->addOverload(*Func);
3797
3798 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3799 OpLoc, false, false);
3800
3801 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3802 Args, 2,
3803 Context.DependentTy,
3804 OpLoc));
3805 }
3806
3807 // If this is the .* operator, which is not overloadable, just
3808 // create a built-in binary operator.
3809 if (Opc == BinaryOperator::PtrMemD)
3810 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3811
3812 // If this is one of the assignment operators, we only perform
3813 // overload resolution if the left-hand side is a class or
3814 // enumeration type (C++ [expr.ass]p3).
3815 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3816 !LHS->getType()->isOverloadableType())
3817 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3818
Douglas Gregorc78182d2009-03-13 23:49:33 +00003819 // Build an empty overload set.
3820 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003821
3822 // Add the candidates from the given function set.
3823 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
3824
3825 // Add operator candidates that are member functions.
3826 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
3827
3828 // Add builtin operator candidates.
3829 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
3830
3831 // Perform overload resolution.
3832 OverloadCandidateSet::iterator Best;
3833 switch (BestViableFunction(CandidateSet, Best)) {
3834 case OR_Success: {
3835 // We found a built-in operator or an overloaded operator.
3836 FunctionDecl *FnDecl = Best->Function;
3837
3838 if (FnDecl) {
3839 // We matched an overloaded operator. Build a call to that
3840 // operator.
3841
3842 // Convert the arguments.
3843 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3844 if (PerformObjectArgumentInitialization(LHS, Method) ||
3845 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
3846 "passing"))
3847 return ExprError();
3848 } else {
3849 // Convert the arguments.
3850 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
3851 "passing") ||
3852 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
3853 "passing"))
3854 return ExprError();
3855 }
3856
3857 // Determine the result type
3858 QualType ResultTy
3859 = FnDecl->getType()->getAsFunctionType()->getResultType();
3860 ResultTy = ResultTy.getNonReferenceType();
3861
3862 // Build the actual expression node.
3863 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3864 SourceLocation());
3865 UsualUnaryConversions(FnExpr);
3866
3867 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3868 Args, 2, ResultTy,
3869 OpLoc));
3870 } else {
3871 // We matched a built-in operator. Convert the arguments, then
3872 // break out so that we will build the appropriate built-in
3873 // operator node.
3874 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
3875 Best->Conversions[0], "passing") ||
3876 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
3877 Best->Conversions[1], "passing"))
3878 return ExprError();
3879
3880 break;
3881 }
3882 }
3883
3884 case OR_No_Viable_Function:
3885 // No viable function; fall through to handling this as a
3886 // built-in operator, which will produce an error message for us.
3887 break;
3888
3889 case OR_Ambiguous:
3890 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3891 << BinaryOperator::getOpcodeStr(Opc)
3892 << LHS->getSourceRange() << RHS->getSourceRange();
3893 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3894 return ExprError();
3895
3896 case OR_Deleted:
3897 Diag(OpLoc, diag::err_ovl_deleted_oper)
3898 << Best->Function->isDeleted()
3899 << BinaryOperator::getOpcodeStr(Opc)
3900 << LHS->getSourceRange() << RHS->getSourceRange();
3901 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3902 return ExprError();
3903 }
3904
3905 // Either we found no viable overloaded operator or we matched a
3906 // built-in operator. In either case, try to build a built-in
3907 // operation.
3908 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3909}
3910
Douglas Gregor3257fb52008-12-22 05:46:06 +00003911/// BuildCallToMemberFunction - Build a call to a member
3912/// function. MemExpr is the expression that refers to the member
3913/// function (and includes the object parameter), Args/NumArgs are the
3914/// arguments to the function call (not including the object
3915/// parameter). The caller needs to validate that the member
3916/// expression refers to a member function or an overloaded member
3917/// function.
3918Sema::ExprResult
3919Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3920 SourceLocation LParenLoc, Expr **Args,
3921 unsigned NumArgs, SourceLocation *CommaLocs,
3922 SourceLocation RParenLoc) {
3923 // Dig out the member expression. This holds both the object
3924 // argument and the member function we're referring to.
3925 MemberExpr *MemExpr = 0;
3926 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3927 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3928 else
3929 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3930 assert(MemExpr && "Building member call without member expression");
3931
3932 // Extract the object argument.
3933 Expr *ObjectArg = MemExpr->getBase();
3934 if (MemExpr->isArrow())
Ted Kremenek0c97e042009-02-07 01:47:29 +00003935 ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref,
3936 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
Douglas Gregor8d103492009-02-19 00:52:42 +00003937 ObjectArg->getLocStart());
Douglas Gregor3257fb52008-12-22 05:46:06 +00003938 CXXMethodDecl *Method = 0;
3939 if (OverloadedFunctionDecl *Ovl
3940 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3941 // Add overload candidates
3942 OverloadCandidateSet CandidateSet;
3943 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3944 FuncEnd = Ovl->function_end();
3945 Func != FuncEnd; ++Func) {
3946 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3947 Method = cast<CXXMethodDecl>(*Func);
3948 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3949 /*SuppressUserConversions=*/false);
3950 }
3951
3952 OverloadCandidateSet::iterator Best;
3953 switch (BestViableFunction(CandidateSet, Best)) {
3954 case OR_Success:
3955 Method = cast<CXXMethodDecl>(Best->Function);
3956 break;
3957
3958 case OR_No_Viable_Function:
3959 Diag(MemExpr->getSourceRange().getBegin(),
3960 diag::err_ovl_no_viable_member_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00003961 << Ovl->getDeclName() << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00003962 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3963 // FIXME: Leaking incoming expressions!
3964 return true;
3965
3966 case OR_Ambiguous:
3967 Diag(MemExpr->getSourceRange().getBegin(),
3968 diag::err_ovl_ambiguous_member_call)
3969 << Ovl->getDeclName() << MemExprE->getSourceRange();
3970 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3971 // FIXME: Leaking incoming expressions!
3972 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00003973
3974 case OR_Deleted:
3975 Diag(MemExpr->getSourceRange().getBegin(),
3976 diag::err_ovl_deleted_member_call)
3977 << Best->Function->isDeleted()
3978 << Ovl->getDeclName() << MemExprE->getSourceRange();
3979 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3980 // FIXME: Leaking incoming expressions!
3981 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003982 }
3983
3984 FixOverloadedFunctionReference(MemExpr, Method);
3985 } else {
3986 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3987 }
3988
3989 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00003990 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00003991 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
3992 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00003993 Method->getResultType().getNonReferenceType(),
3994 RParenLoc));
3995
3996 // Convert the object argument (for a non-static member function call).
3997 if (!Method->isStatic() &&
3998 PerformObjectArgumentInitialization(ObjectArg, Method))
3999 return true;
4000 MemExpr->setBase(ObjectArg);
4001
4002 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004003 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004004 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4005 RParenLoc))
4006 return true;
4007
Sebastian Redl8b769972009-01-19 00:08:26 +00004008 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004009}
4010
Douglas Gregor10f3c502008-11-19 21:05:33 +00004011/// BuildCallToObjectOfClassType - Build a call to an object of class
4012/// type (C++ [over.call.object]), which can end up invoking an
4013/// overloaded function call operator (@c operator()) or performing a
4014/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004015Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004016Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4017 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004018 Expr **Args, unsigned NumArgs,
4019 SourceLocation *CommaLocs,
4020 SourceLocation RParenLoc) {
4021 assert(Object->getType()->isRecordType() && "Requires object type argument");
4022 const RecordType *Record = Object->getType()->getAsRecordType();
4023
4024 // C++ [over.call.object]p1:
4025 // If the primary-expression E in the function call syntax
4026 // evaluates to a class object of type “cv T”, then the set of
4027 // candidate functions includes at least the function call
4028 // operators of T. The function call operators of T are obtained by
4029 // ordinary lookup of the name operator() in the context of
4030 // (E).operator().
4031 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004032 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004033 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00004034 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004035 Oper != OperEnd; ++Oper)
4036 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4037 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004038
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004039 // C++ [over.call.object]p2:
4040 // In addition, for each conversion function declared in T of the
4041 // form
4042 //
4043 // operator conversion-type-id () cv-qualifier;
4044 //
4045 // where cv-qualifier is the same cv-qualification as, or a
4046 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004047 // denotes the type "pointer to function of (P1,...,Pn) returning
4048 // R", or the type "reference to pointer to function of
4049 // (P1,...,Pn) returning R", or the type "reference to function
4050 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004051 // is also considered as a candidate function. Similarly,
4052 // surrogate call functions are added to the set of candidate
4053 // functions for each conversion function declared in an
4054 // accessible base class provided the function is not hidden
4055 // within T by another intervening declaration.
4056 //
4057 // FIXME: Look in base classes for more conversion operators!
4058 OverloadedFunctionDecl *Conversions
4059 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004060 for (OverloadedFunctionDecl::function_iterator
4061 Func = Conversions->function_begin(),
4062 FuncEnd = Conversions->function_end();
4063 Func != FuncEnd; ++Func) {
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004064 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4065
4066 // Strip the reference type (if any) and then the pointer type (if
4067 // any) to get down to what might be a function type.
4068 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4069 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4070 ConvType = ConvPtrType->getPointeeType();
4071
Douglas Gregor4fa58902009-02-26 23:50:07 +00004072 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004073 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4074 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004075
4076 // Perform overload resolution.
4077 OverloadCandidateSet::iterator Best;
4078 switch (BestViableFunction(CandidateSet, Best)) {
4079 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004080 // Overload resolution succeeded; we'll build the appropriate call
4081 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004082 break;
4083
4084 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004085 Diag(Object->getSourceRange().getBegin(),
4086 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004087 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004088 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004089 break;
4090
4091 case OR_Ambiguous:
4092 Diag(Object->getSourceRange().getBegin(),
4093 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004094 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004095 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4096 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004097
4098 case OR_Deleted:
4099 Diag(Object->getSourceRange().getBegin(),
4100 diag::err_ovl_deleted_object_call)
4101 << Best->Function->isDeleted()
4102 << Object->getType() << Object->getSourceRange();
4103 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4104 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004105 }
4106
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004107 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004108 // We had an error; delete all of the subexpressions and return
4109 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004110 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004111 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004112 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004113 return true;
4114 }
4115
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004116 if (Best->Function == 0) {
4117 // Since there is no function declaration, this is one of the
4118 // surrogate candidates. Dig out the conversion function.
4119 CXXConversionDecl *Conv
4120 = cast<CXXConversionDecl>(
4121 Best->Conversions[0].UserDefined.ConversionFunction);
4122
4123 // We selected one of the surrogate functions that converts the
4124 // object parameter to a function pointer. Perform the conversion
4125 // on the object argument, then let ActOnCallExpr finish the job.
4126 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004127 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004128 Conv->getConversionType().getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +00004129 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004130 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4131 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4132 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004133 }
4134
4135 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4136 // that calls this method, using Object for the implicit object
4137 // parameter and passing along the remaining arguments.
4138 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004139 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004140
4141 unsigned NumArgsInProto = Proto->getNumArgs();
4142 unsigned NumArgsToCheck = NumArgs;
4143
4144 // Build the full argument list for the method call (the
4145 // implicit object parameter is placed at the beginning of the
4146 // list).
4147 Expr **MethodArgs;
4148 if (NumArgs < NumArgsInProto) {
4149 NumArgsToCheck = NumArgsInProto;
4150 MethodArgs = new Expr*[NumArgsInProto + 1];
4151 } else {
4152 MethodArgs = new Expr*[NumArgs + 1];
4153 }
4154 MethodArgs[0] = Object;
4155 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4156 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4157
Ted Kremenek0c97e042009-02-07 01:47:29 +00004158 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4159 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004160 UsualUnaryConversions(NewFn);
4161
4162 // Once we've built TheCall, all of the expressions are properly
4163 // owned.
4164 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004165 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004166 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4167 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004168 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004169 delete [] MethodArgs;
4170
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004171 // We may have default arguments. If so, we need to allocate more
4172 // slots in the call for them.
4173 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004174 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004175 else if (NumArgs > NumArgsInProto)
4176 NumArgsToCheck = NumArgsInProto;
4177
Douglas Gregor10f3c502008-11-19 21:05:33 +00004178 // Initialize the implicit object parameter.
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004179 if (PerformObjectArgumentInitialization(Object, Method))
Douglas Gregor10f3c502008-11-19 21:05:33 +00004180 return true;
4181 TheCall->setArg(0, Object);
4182
4183 // Check the argument types.
4184 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004185 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004186 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004187 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004188
4189 // Pass the argument.
4190 QualType ProtoArgType = Proto->getArgType(i);
4191 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
4192 return true;
4193 } else {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004194 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004195 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004196
4197 TheCall->setArg(i + 1, Arg);
4198 }
4199
4200 // If this is a variadic call, handle args passed through "...".
4201 if (Proto->isVariadic()) {
4202 // Promote the arguments (C99 6.5.2.2p7).
4203 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4204 Expr *Arg = Args[i];
Anders Carlssonfde627e2009-01-13 05:48:52 +00004205
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00004206 DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004207 TheCall->setArg(i + 1, Arg);
4208 }
4209 }
4210
Sebastian Redl8b769972009-01-19 00:08:26 +00004211 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004212}
4213
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004214/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4215/// (if one exists), where @c Base is an expression of class type and
4216/// @c Member is the name of the member we're trying to find.
4217Action::ExprResult
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004218Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004219 SourceLocation MemberLoc,
4220 IdentifierInfo &Member) {
4221 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4222
4223 // C++ [over.ref]p1:
4224 //
4225 // [...] An expression x->m is interpreted as (x.operator->())->m
4226 // for a class object x of type T if T::operator->() exists and if
4227 // the operator is selected as the best match function by the
4228 // overload resolution mechanism (13.3).
4229 // FIXME: look in base classes.
4230 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4231 OverloadCandidateSet CandidateSet;
4232 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004233
4234 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00004235 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004236 Oper != OperEnd; ++Oper)
4237 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004238 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004239
Ted Kremenek0c97e042009-02-07 01:47:29 +00004240 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004241
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004242 // Perform overload resolution.
4243 OverloadCandidateSet::iterator Best;
4244 switch (BestViableFunction(CandidateSet, Best)) {
4245 case OR_Success:
4246 // Overload resolution succeeded; we'll build the call below.
4247 break;
4248
4249 case OR_No_Viable_Function:
4250 if (CandidateSet.empty())
4251 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004252 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004253 else
4254 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Chris Lattner4a526112009-02-17 07:29:20 +00004255 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004256 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004257 return true;
4258
4259 case OR_Ambiguous:
4260 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004261 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004262 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004263 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004264
4265 case OR_Deleted:
4266 Diag(OpLoc, diag::err_ovl_deleted_oper)
4267 << Best->Function->isDeleted()
4268 << "operator->" << BasePtr->getSourceRange();
4269 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4270 return true;
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004271 }
4272
4273 // Convert the object parameter.
4274 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004275 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004276 return true;
Douglas Gregor9c690e92008-11-21 03:04:22 +00004277
4278 // No concerns about early exits now.
4279 BasePtr.take();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004280
4281 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004282 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4283 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004284 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004285 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004286 Method->getResultType().getNonReferenceType(),
4287 OpLoc);
Sebastian Redl8b769972009-01-19 00:08:26 +00004288 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
Chris Lattner5261d0c2009-03-28 19:18:32 +00004289 MemberLoc, Member, DeclPtrTy()).release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004290}
4291
Douglas Gregor45014fd2008-11-10 20:40:00 +00004292/// FixOverloadedFunctionReference - E is an expression that refers to
4293/// a C++ overloaded function (possibly with some parentheses and
4294/// perhaps a '&' around it). We have resolved the overloaded function
4295/// to the function declaration Fn, so patch up the expression E to
4296/// refer (possibly indirectly) to Fn.
4297void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4298 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4299 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4300 E->setType(PE->getSubExpr()->getType());
4301 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4302 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4303 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004304 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4305 if (Method->isStatic()) {
4306 // Do nothing: static member functions aren't any different
4307 // from non-member functions.
4308 }
4309 else if (QualifiedDeclRefExpr *DRE
4310 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4311 // We have taken the address of a pointer to member
4312 // function. Perform the computation here so that we get the
4313 // appropriate pointer to member type.
4314 DRE->setDecl(Fn);
4315 DRE->setType(Fn->getType());
4316 QualType ClassType
4317 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4318 E->setType(Context.getMemberPointerType(Fn->getType(),
4319 ClassType.getTypePtr()));
4320 return;
4321 }
4322 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004323 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004324 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004325 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4326 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4327 "Expected overloaded function");
4328 DR->setDecl(Fn);
4329 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004330 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4331 MemExpr->setMemberDecl(Fn);
4332 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004333 } else {
4334 assert(false && "Invalid reference to overloaded function");
4335 }
4336}
4337
Douglas Gregord2baafd2008-10-21 16:13:35 +00004338} // end namespace clang