blob: 48d31056a7928555e85604cbabd728607b4f65a6 [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.
313 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
314 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
315 return false;
316
317 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
318 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
319
320 // The signature of a function includes the types of its
321 // parameters (C++ 1.3.10), which includes the presence or absence
322 // of the ellipsis; see C++ DR 357).
323 if (OldQType != NewQType &&
324 (OldType->getNumArgs() != NewType->getNumArgs() ||
325 OldType->isVariadic() != NewType->isVariadic() ||
326 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
327 NewType->arg_type_begin())))
328 return true;
329
330 // If the function is a class member, its signature includes the
331 // cv-qualifiers (if any) on the function itself.
332 //
333 // As part of this, also check whether one of the member functions
334 // is static, in which case they are not overloads (C++
335 // 13.1p2). While not part of the definition of the signature,
336 // this check is important to determine whether these functions
337 // can be overloaded.
338 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
339 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
340 if (OldMethod && NewMethod &&
341 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas 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() &&
471 !FromType->isOverloadType()) {
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();
522 if (ToType->isReferenceType())
523 FromType = Context.getReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000524 else if (ToType->isMemberPointerType()) {
525 // Resolve address only succeeds if both sides are member pointers,
526 // but it doesn't have to be the same class. See DR 247.
527 // Note that this means that the type of &Derived::fn can be
528 // Ret (Base::*)(Args) if the fn overload actually found is from the
529 // base class, even if it was brought into the derived class via a
530 // using declaration. The standard isn't clear on this issue at all.
531 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
532 FromType = Context.getMemberPointerType(FromType,
533 Context.getTypeDeclType(M->getParent()).getTypePtr());
534 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000535 FromType = Context.getPointerType(FromType);
536 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000537 // We don't require any conversions for the first step.
538 else {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000539 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000540 }
541
542 // The second conversion can be an integral promotion, floating
543 // point promotion, integral conversion, floating point conversion,
544 // floating-integral conversion, pointer conversion,
545 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000546 // For overloading in C, this can also be a "compatible-type"
547 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000548 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000549 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000550 // The unqualified versions of the types are the same: there's no
551 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000552 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000553 }
554 // Integral promotion (C++ 4.5).
555 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000556 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000557 FromType = ToType.getUnqualifiedType();
558 }
559 // Floating point promotion (C++ 4.6).
560 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000561 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000562 FromType = ToType.getUnqualifiedType();
563 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000564 // Complex promotion (Clang extension)
565 else if (IsComplexPromotion(FromType, ToType)) {
566 SCS.Second = ICK_Complex_Promotion;
567 FromType = ToType.getUnqualifiedType();
568 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000569 // Integral conversions (C++ 4.7).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000570 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000571 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000572 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000573 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000574 FromType = ToType.getUnqualifiedType();
575 }
576 // Floating point conversions (C++ 4.8).
577 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000578 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000579 FromType = ToType.getUnqualifiedType();
580 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000581 // Complex conversions (C99 6.3.1.6)
582 else if (FromType->isComplexType() && ToType->isComplexType()) {
583 SCS.Second = ICK_Complex_Conversion;
584 FromType = ToType.getUnqualifiedType();
585 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000586 // Floating-integral conversions (C++ 4.9).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000587 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000588 else if ((FromType->isFloatingType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000589 ToType->isIntegralType() && !ToType->isBooleanType() &&
590 !ToType->isEnumeralType()) ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000591 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
592 ToType->isFloatingType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000593 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000594 FromType = ToType.getUnqualifiedType();
595 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000596 // Complex-real conversions (C99 6.3.1.7)
597 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
598 (ToType->isComplexType() && FromType->isArithmeticType())) {
599 SCS.Second = ICK_Complex_Real;
600 FromType = ToType.getUnqualifiedType();
601 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000602 // Pointer conversions (C++ 4.10).
Douglas Gregor6fd35572008-12-19 17:40:08 +0000603 else if (IsPointerConversion(From, FromType, ToType, FromType,
604 IncompatibleObjC)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000605 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000606 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000607 }
Sebastian Redlba387562009-01-25 19:43:20 +0000608 // Pointer to member conversions (4.11).
609 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
610 SCS.Second = ICK_Pointer_Member;
611 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000612 // Boolean conversions (C++ 4.12).
Douglas Gregord2baafd2008-10-21 16:13:35 +0000613 else if (ToType->isBooleanType() &&
614 (FromType->isArithmeticType() ||
615 FromType->isEnumeralType() ||
Douglas Gregor80402cf2008-12-23 00:53:59 +0000616 FromType->isPointerType() ||
Sebastian Redlba387562009-01-25 19:43:20 +0000617 FromType->isBlockPointerType() ||
618 FromType->isMemberPointerType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000619 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000620 FromType = Context.BoolTy;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000621 }
622 // Compatible conversions (Clang extension for C function overloading)
623 else if (!getLangOptions().CPlusPlus &&
624 Context.typesAreCompatible(ToType, FromType)) {
625 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000626 } else {
627 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000628 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000629 }
630
Douglas Gregor81c29152008-10-29 00:13:59 +0000631 QualType CanonFrom;
632 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000633 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000634 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000635 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000636 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000637 CanonFrom = Context.getCanonicalType(FromType);
638 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000639 } else {
640 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000641 SCS.Third = ICK_Identity;
642
643 // C++ [over.best.ics]p6:
644 // [...] Any difference in top-level cv-qualification is
645 // subsumed by the initialization itself and does not constitute
646 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000647 CanonFrom = Context.getCanonicalType(FromType);
648 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000649 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000650 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
651 FromType = ToType;
652 CanonFrom = CanonTo;
653 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000654 }
655
656 // If we have not converted the argument type to the parameter type,
657 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000658 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000659 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000660
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000661 SCS.ToTypePtr = FromType.getAsOpaquePtr();
662 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000663}
664
665/// IsIntegralPromotion - Determines whether the conversion from the
666/// expression From (whose potentially-adjusted type is FromType) to
667/// ToType is an integral promotion (C++ 4.5). If so, returns true and
668/// sets PromotedType to the promoted type.
669bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
670{
671 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000672 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000673 if (!To) {
674 return false;
675 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000676
677 // An rvalue of type char, signed char, unsigned char, short int, or
678 // unsigned short int can be converted to an rvalue of type int if
679 // int can represent all the values of the source type; otherwise,
680 // the source rvalue can be converted to an rvalue of type unsigned
681 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000682 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000683 if (// We can promote any signed, promotable integer type to an int
684 (FromType->isSignedIntegerType() ||
685 // We can promote any unsigned integer type whose size is
686 // less than int to an int.
687 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000688 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000689 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000690 }
691
Douglas Gregord2baafd2008-10-21 16:13:35 +0000692 return To->getKind() == BuiltinType::UInt;
693 }
694
695 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
696 // can be converted to an rvalue of the first of the following types
697 // that can represent all the values of its underlying type: int,
698 // unsigned int, long, or unsigned long (C++ 4.5p2).
699 if ((FromType->isEnumeralType() || FromType->isWideCharType())
700 && ToType->isIntegerType()) {
701 // Determine whether the type we're converting from is signed or
702 // unsigned.
703 bool FromIsSigned;
704 uint64_t FromSize = Context.getTypeSize(FromType);
705 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
706 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
707 FromIsSigned = UnderlyingType->isSignedIntegerType();
708 } else {
709 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
710 FromIsSigned = true;
711 }
712
713 // The types we'll try to promote to, in the appropriate
714 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000715 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000716 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000717 Context.LongTy, Context.UnsignedLongTy ,
718 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000719 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000720 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000721 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
722 if (FromSize < ToSize ||
723 (FromSize == ToSize &&
724 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
725 // We found the type that we can promote to. If this is the
726 // type we wanted, we have a promotion. Otherwise, no
727 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000728 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000729 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
730 }
731 }
732 }
733
734 // An rvalue for an integral bit-field (9.6) can be converted to an
735 // rvalue of type int if int can represent all the values of the
736 // bit-field; otherwise, it can be converted to unsigned int if
737 // unsigned int can represent all the values of the bit-field. If
738 // the bit-field is larger yet, no integral promotion applies to
739 // it. If the bit-field has an enumerated type, it is treated as any
740 // other value of that type for promotion purposes (C++ 4.5p3).
741 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
742 using llvm::APSInt;
Douglas Gregor82d44772008-12-20 23:49:58 +0000743 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
744 APSInt BitWidth;
745 if (MemberDecl->isBitField() &&
746 FromType->isIntegralType() && !FromType->isEnumeralType() &&
747 From->isIntegerConstantExpr(BitWidth, Context)) {
748 APSInt ToSize(Context.getTypeSize(ToType));
749
750 // Are we promoting to an int from a bitfield that fits in an int?
751 if (BitWidth < ToSize ||
752 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
753 return To->getKind() == BuiltinType::Int;
754 }
755
756 // Are we promoting to an unsigned int from an unsigned bitfield
757 // that fits into an unsigned int?
758 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
759 return To->getKind() == BuiltinType::UInt;
760 }
761
762 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000763 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000764 }
765 }
766
767 // An rvalue of type bool can be converted to an rvalue of type int,
768 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000769 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000770 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000771 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000772
773 return false;
774}
775
776/// IsFloatingPointPromotion - Determines whether the conversion from
777/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
778/// returns true and sets PromotedType to the promoted type.
779bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
780{
781 /// An rvalue of type float can be converted to an rvalue of type
782 /// double. (C++ 4.6p1).
783 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000784 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000785 if (FromBuiltin->getKind() == BuiltinType::Float &&
786 ToBuiltin->getKind() == BuiltinType::Double)
787 return true;
788
Douglas Gregore819caf2009-02-12 00:15:05 +0000789 // C99 6.3.1.5p1:
790 // When a float is promoted to double or long double, or a
791 // double is promoted to long double [...].
792 if (!getLangOptions().CPlusPlus &&
793 (FromBuiltin->getKind() == BuiltinType::Float ||
794 FromBuiltin->getKind() == BuiltinType::Double) &&
795 (ToBuiltin->getKind() == BuiltinType::LongDouble))
796 return true;
797 }
798
Douglas Gregord2baafd2008-10-21 16:13:35 +0000799 return false;
800}
801
Douglas Gregore819caf2009-02-12 00:15:05 +0000802/// \brief Determine if a conversion is a complex promotion.
803///
804/// A complex promotion is defined as a complex -> complex conversion
805/// where the conversion between the underlying real types is a
806/// floating-point conversion.
807bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
808 const ComplexType *FromComplex = FromType->getAsComplexType();
809 if (!FromComplex)
810 return false;
811
812 const ComplexType *ToComplex = ToType->getAsComplexType();
813 if (!ToComplex)
814 return false;
815
816 return IsFloatingPointPromotion(FromComplex->getElementType(),
817 ToComplex->getElementType());
818}
819
Douglas Gregor24a90a52008-11-26 23:31:11 +0000820/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
821/// the pointer type FromPtr to a pointer to type ToPointee, with the
822/// same type qualifiers as FromPtr has on its pointee type. ToType,
823/// if non-empty, will be a pointer to ToType that may or may not have
824/// the right set of qualifiers on its pointee.
825static QualType
826BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
827 QualType ToPointee, QualType ToType,
828 ASTContext &Context) {
829 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
830 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
831 unsigned Quals = CanonFromPointee.getCVRQualifiers();
832
833 // Exact qualifier match -> return the pointer type we're converting to.
834 if (CanonToPointee.getCVRQualifiers() == Quals) {
835 // ToType is exactly what we need. Return it.
836 if (ToType.getTypePtr())
837 return ToType;
838
839 // Build a pointer to ToPointee. It has the right qualifiers
840 // already.
841 return Context.getPointerType(ToPointee);
842 }
843
844 // Just build a canonical type that has the right qualifiers.
845 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
846}
847
Douglas Gregord2baafd2008-10-21 16:13:35 +0000848/// IsPointerConversion - Determines whether the conversion of the
849/// expression From, which has the (possibly adjusted) type FromType,
850/// can be converted to the type ToType via a pointer conversion (C++
851/// 4.10). If so, returns true and places the converted type (that
852/// might differ from ToType in its cv-qualifiers at some level) into
853/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000854///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000855/// This routine also supports conversions to and from block pointers
856/// and conversions with Objective-C's 'id', 'id<protocols...>', and
857/// pointers to interfaces. FIXME: Once we've determined the
858/// appropriate overloading rules for Objective-C, we may want to
859/// split the Objective-C checks into a different routine; however,
860/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000861/// conversions, so for now they live here. IncompatibleObjC will be
862/// set if the conversion is an allowed Objective-C conversion that
863/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000864bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000865 QualType& ConvertedType,
866 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000867{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000868 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000869 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
870 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000871
Douglas Gregorf1d75712008-12-22 20:51:52 +0000872 // Conversion from a null pointer constant to any Objective-C pointer type.
873 if (Context.isObjCObjectPointerType(ToType) &&
874 From->isNullPointerConstant(Context)) {
875 ConvertedType = ToType;
876 return true;
877 }
878
Douglas Gregor9036ef72008-11-27 00:15:41 +0000879 // Blocks: Block pointers can be converted to void*.
880 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
881 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
882 ConvertedType = ToType;
883 return true;
884 }
885 // Blocks: A null pointer constant can be converted to a block
886 // pointer type.
887 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
888 ConvertedType = ToType;
889 return true;
890 }
891
Douglas Gregord2baafd2008-10-21 16:13:35 +0000892 const PointerType* ToTypePtr = ToType->getAsPointerType();
893 if (!ToTypePtr)
894 return false;
895
896 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
897 if (From->isNullPointerConstant(Context)) {
898 ConvertedType = ToType;
899 return true;
900 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000901
Douglas Gregor24a90a52008-11-26 23:31:11 +0000902 // Beyond this point, both types need to be pointers.
903 const PointerType *FromTypePtr = FromType->getAsPointerType();
904 if (!FromTypePtr)
905 return false;
906
907 QualType FromPointeeType = FromTypePtr->getPointeeType();
908 QualType ToPointeeType = ToTypePtr->getPointeeType();
909
Douglas Gregord2baafd2008-10-21 16:13:35 +0000910 // An rvalue of type "pointer to cv T," where T is an object type,
911 // can be converted to an rvalue of type "pointer to cv void" (C++
912 // 4.10p2).
Douglas Gregor932778b2008-12-19 19:13:09 +0000913 if (FromPointeeType->isIncompleteOrObjectType() &&
914 ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000915 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
916 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000917 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000918 return true;
919 }
920
Douglas Gregorfcb19192009-02-11 23:02:49 +0000921 // When we're overloading in C, we allow a special kind of pointer
922 // conversion for compatible-but-not-identical pointee types.
923 if (!getLangOptions().CPlusPlus &&
924 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
925 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
926 ToPointeeType,
927 ToType, Context);
928 return true;
929 }
930
Douglas Gregor14046502008-10-23 00:40:37 +0000931 // C++ [conv.ptr]p3:
932 //
933 // An rvalue of type "pointer to cv D," where D is a class type,
934 // can be converted to an rvalue of type "pointer to cv B," where
935 // B is a base class (clause 10) of D. If B is an inaccessible
936 // (clause 11) or ambiguous (10.2) base class of D, a program that
937 // necessitates this conversion is ill-formed. The result of the
938 // conversion is a pointer to the base class sub-object of the
939 // derived class object. The null pointer value is converted to
940 // the null pointer value of the destination type.
941 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000942 // Note that we do not check for ambiguity or inaccessibility
943 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000944 if (getLangOptions().CPlusPlus &&
945 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000946 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000947 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
948 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000949 ToType, Context);
950 return true;
951 }
Douglas Gregor14046502008-10-23 00:40:37 +0000952
Douglas Gregor932778b2008-12-19 19:13:09 +0000953 return false;
954}
955
956/// isObjCPointerConversion - Determines whether this is an
957/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
958/// with the same arguments and return values.
959bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
960 QualType& ConvertedType,
961 bool &IncompatibleObjC) {
962 if (!getLangOptions().ObjC1)
963 return false;
964
965 // Conversions with Objective-C's id<...>.
966 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
967 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
968 ConvertedType = ToType;
969 return true;
970 }
971
Douglas Gregor80402cf2008-12-23 00:53:59 +0000972 // Beyond this point, both types need to be pointers or block pointers.
973 QualType ToPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000974 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000975 if (ToTypePtr)
976 ToPointeeType = ToTypePtr->getPointeeType();
977 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
978 ToPointeeType = ToBlockPtr->getPointeeType();
979 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000980 return false;
981
Douglas Gregor80402cf2008-12-23 00:53:59 +0000982 QualType FromPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000983 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000984 if (FromTypePtr)
985 FromPointeeType = FromTypePtr->getPointeeType();
986 else if (const BlockPointerType *FromBlockPtr
987 = FromType->getAsBlockPointerType())
988 FromPointeeType = FromBlockPtr->getPointeeType();
989 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000990 return false;
991
Douglas Gregor24a90a52008-11-26 23:31:11 +0000992 // Objective C++: We're able to convert from a pointer to an
993 // interface to a pointer to a different interface.
994 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
995 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
996 if (FromIface && ToIface &&
997 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor80402cf2008-12-23 00:53:59 +0000998 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000999 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001000 ToType, Context);
1001 return true;
1002 }
1003
Douglas Gregor6fd35572008-12-19 17:40:08 +00001004 if (FromIface && ToIface &&
1005 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1006 // Okay: this is some kind of implicit downcast of Objective-C
1007 // interfaces, which is permitted. However, we're going to
1008 // complain about it.
1009 IncompatibleObjC = true;
Douglas Gregor80402cf2008-12-23 00:53:59 +00001010 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor6fd35572008-12-19 17:40:08 +00001011 ToPointeeType,
1012 ToType, Context);
1013 return true;
1014 }
1015
Douglas Gregor24a90a52008-11-26 23:31:11 +00001016 // Objective C++: We're able to convert between "id" and a pointer
1017 // to any interface (in both directions).
1018 if ((FromIface && Context.isObjCIdType(ToPointeeType))
1019 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001020 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1021 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001022 ToType, Context);
1023 return true;
1024 }
Douglas Gregor14046502008-10-23 00:40:37 +00001025
Douglas Gregord0c653a2008-12-18 23:43:31 +00001026 // Objective C++: Allow conversions between the Objective-C "id" and
1027 // "Class", in either direction.
1028 if ((Context.isObjCIdType(FromPointeeType) &&
1029 Context.isObjCClassType(ToPointeeType)) ||
1030 (Context.isObjCClassType(FromPointeeType) &&
1031 Context.isObjCIdType(ToPointeeType))) {
1032 ConvertedType = ToType;
1033 return true;
1034 }
1035
Douglas Gregor932778b2008-12-19 19:13:09 +00001036 // If we have pointers to pointers, recursively check whether this
1037 // is an Objective-C conversion.
1038 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1039 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1040 IncompatibleObjC)) {
1041 // We always complain about this conversion.
1042 IncompatibleObjC = true;
1043 ConvertedType = ToType;
1044 return true;
1045 }
1046
Douglas Gregor80402cf2008-12-23 00:53:59 +00001047 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001048 // differences in the argument and result types are in Objective-C
1049 // pointer conversions. If so, we permit the conversion (but
1050 // complain about it).
1051 const FunctionTypeProto *FromFunctionType
1052 = FromPointeeType->getAsFunctionTypeProto();
1053 const FunctionTypeProto *ToFunctionType
1054 = ToPointeeType->getAsFunctionTypeProto();
1055 if (FromFunctionType && ToFunctionType) {
1056 // If the function types are exactly the same, this isn't an
1057 // Objective-C pointer conversion.
1058 if (Context.getCanonicalType(FromPointeeType)
1059 == Context.getCanonicalType(ToPointeeType))
1060 return false;
1061
1062 // Perform the quick checks that will tell us whether these
1063 // function types are obviously different.
1064 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1065 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1066 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1067 return false;
1068
1069 bool HasObjCConversion = false;
1070 if (Context.getCanonicalType(FromFunctionType->getResultType())
1071 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1072 // Okay, the types match exactly. Nothing to do.
1073 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1074 ToFunctionType->getResultType(),
1075 ConvertedType, IncompatibleObjC)) {
1076 // Okay, we have an Objective-C pointer conversion.
1077 HasObjCConversion = true;
1078 } else {
1079 // Function types are too different. Abort.
1080 return false;
1081 }
1082
1083 // Check argument types.
1084 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1085 ArgIdx != NumArgs; ++ArgIdx) {
1086 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1087 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1088 if (Context.getCanonicalType(FromArgType)
1089 == Context.getCanonicalType(ToArgType)) {
1090 // Okay, the types match exactly. Nothing to do.
1091 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1092 ConvertedType, IncompatibleObjC)) {
1093 // Okay, we have an Objective-C pointer conversion.
1094 HasObjCConversion = true;
1095 } else {
1096 // Argument types are too different. Abort.
1097 return false;
1098 }
1099 }
1100
1101 if (HasObjCConversion) {
1102 // We had an Objective-C conversion. Allow this pointer
1103 // conversion, but complain about it.
1104 ConvertedType = ToType;
1105 IncompatibleObjC = true;
1106 return true;
1107 }
1108 }
1109
Sebastian Redlba387562009-01-25 19:43:20 +00001110 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001111}
1112
Douglas Gregorbb461502008-10-24 04:54:22 +00001113/// CheckPointerConversion - Check the pointer conversion from the
1114/// expression From to the type ToType. This routine checks for
1115/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1116/// conversions for which IsPointerConversion has already returned
1117/// true. It returns true and produces a diagnostic if there was an
1118/// error, or returns false otherwise.
1119bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1120 QualType FromType = From->getType();
1121
1122 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1123 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001124 QualType FromPointeeType = FromPtrType->getPointeeType(),
1125 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001126
1127 // Objective-C++ conversions are always okay.
1128 // FIXME: We should have a different class of conversions for
1129 // the Objective-C++ implicit conversions.
1130 if (Context.isObjCIdType(FromPointeeType) ||
1131 Context.isObjCIdType(ToPointeeType) ||
1132 Context.isObjCClassType(FromPointeeType) ||
1133 Context.isObjCClassType(ToPointeeType))
1134 return false;
1135
Douglas Gregorbb461502008-10-24 04:54:22 +00001136 if (FromPointeeType->isRecordType() &&
1137 ToPointeeType->isRecordType()) {
1138 // We must have a derived-to-base conversion. Check an
1139 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001140 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1141 From->getExprLoc(),
1142 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001143 }
1144 }
1145
1146 return false;
1147}
1148
Sebastian Redlba387562009-01-25 19:43:20 +00001149/// IsMemberPointerConversion - Determines whether the conversion of the
1150/// expression From, which has the (possibly adjusted) type FromType, can be
1151/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1152/// If so, returns true and places the converted type (that might differ from
1153/// ToType in its cv-qualifiers at some level) into ConvertedType.
1154bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1155 QualType ToType, QualType &ConvertedType)
1156{
1157 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1158 if (!ToTypePtr)
1159 return false;
1160
1161 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1162 if (From->isNullPointerConstant(Context)) {
1163 ConvertedType = ToType;
1164 return true;
1165 }
1166
1167 // Otherwise, both types have to be member pointers.
1168 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1169 if (!FromTypePtr)
1170 return false;
1171
1172 // A pointer to member of B can be converted to a pointer to member of D,
1173 // where D is derived from B (C++ 4.11p2).
1174 QualType FromClass(FromTypePtr->getClass(), 0);
1175 QualType ToClass(ToTypePtr->getClass(), 0);
1176 // FIXME: What happens when these are dependent? Is this function even called?
1177
1178 if (IsDerivedFrom(ToClass, FromClass)) {
1179 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1180 ToClass.getTypePtr());
1181 return true;
1182 }
1183
1184 return false;
1185}
1186
1187/// CheckMemberPointerConversion - Check the member pointer conversion from the
1188/// expression From to the type ToType. This routine checks for ambiguous or
1189/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1190/// for which IsMemberPointerConversion has already returned true. It returns
1191/// true and produces a diagnostic if there was an error, or returns false
1192/// otherwise.
1193bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1194 QualType FromType = From->getType();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001195 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1196 if (!FromPtrType)
1197 return false;
Sebastian Redlba387562009-01-25 19:43:20 +00001198
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001199 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1200 assert(ToPtrType && "No member pointer cast has a target type "
1201 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001202
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001203 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1204 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001205
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001206 // FIXME: What about dependent types?
1207 assert(FromClass->isRecordType() && "Pointer into non-class.");
1208 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001209
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001210 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1211 /*DetectVirtual=*/true);
1212 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1213 assert(DerivationOkay &&
1214 "Should not have been called if derivation isn't OK.");
1215 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001216
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001217 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1218 getUnqualifiedType())) {
1219 // Derivation is ambiguous. Redo the check to find the exact paths.
1220 Paths.clear();
1221 Paths.setRecordingPaths(true);
1222 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1223 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1224 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001225
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001226 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1227 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1228 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1229 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001230 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001231
1232 if (const CXXRecordType *VBase = Paths.getDetectedVirtual()) {
1233 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1234 << FromClass << ToClass << QualType(VBase, 0)
1235 << From->getSourceRange();
1236 return true;
1237 }
1238
Sebastian Redlba387562009-01-25 19:43:20 +00001239 return false;
1240}
1241
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001242/// IsQualificationConversion - Determines whether the conversion from
1243/// an rvalue of type FromType to ToType is a qualification conversion
1244/// (C++ 4.4).
1245bool
1246Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1247{
1248 FromType = Context.getCanonicalType(FromType);
1249 ToType = Context.getCanonicalType(ToType);
1250
1251 // If FromType and ToType are the same type, this is not a
1252 // qualification conversion.
1253 if (FromType == ToType)
1254 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001255
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001256 // (C++ 4.4p4):
1257 // A conversion can add cv-qualifiers at levels other than the first
1258 // in multi-level pointers, subject to the following rules: [...]
1259 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001260 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001261 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001262 // Within each iteration of the loop, we check the qualifiers to
1263 // determine if this still looks like a qualification
1264 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001265 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001266 // until there are no more pointers or pointers-to-members left to
1267 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001268 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001269
1270 // -- for every j > 0, if const is in cv 1,j then const is in cv
1271 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001272 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001273 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001274
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001275 // -- if the cv 1,j and cv 2,j are different, then const is in
1276 // every cv for 0 < k < j.
1277 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001278 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001279 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001280
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001281 // Keep track of whether all prior cv-qualifiers in the "to" type
1282 // include const.
1283 PreviousToQualsIncludeConst
1284 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001285 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001286
1287 // We are left with FromType and ToType being the pointee types
1288 // after unwrapping the original FromType and ToType the same number
1289 // of types. If we unwrapped any pointers, and if FromType and
1290 // ToType have the same unqualified type (since we checked
1291 // qualifiers above), then this is a qualification conversion.
1292 return UnwrappedAnyPointer &&
1293 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1294}
1295
Douglas Gregorb206cc42009-01-30 23:27:23 +00001296/// Determines whether there is a user-defined conversion sequence
1297/// (C++ [over.ics.user]) that converts expression From to the type
1298/// ToType. If such a conversion exists, User will contain the
1299/// user-defined conversion sequence that performs such a conversion
1300/// and this routine will return true. Otherwise, this routine returns
1301/// false and User is unspecified.
1302///
1303/// \param AllowConversionFunctions true if the conversion should
1304/// consider conversion functions at all. If false, only constructors
1305/// will be considered.
1306///
1307/// \param AllowExplicit true if the conversion should consider C++0x
1308/// "explicit" conversion functions as well as non-explicit conversion
1309/// functions (C++0x [class.conv.fct]p2).
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001310bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001311 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001312 bool AllowConversionFunctions,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001313 bool AllowExplicit)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001314{
1315 OverloadCandidateSet CandidateSet;
1316 if (const CXXRecordType *ToRecordType
1317 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
1318 // C++ [over.match.ctor]p1:
1319 // When objects of class type are direct-initialized (8.5), or
1320 // copy-initialized from an expression of the same or a
1321 // derived class type (8.5), overload resolution selects the
1322 // constructor. [...] For copy-initialization, the candidate
1323 // functions are all the converting constructors (12.3.1) of
1324 // that class. The argument list is the expression-list within
1325 // the parentheses of the initializer.
1326 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
Douglas Gregorb9213832008-12-15 21:24:18 +00001327 DeclarationName ConstructorName
1328 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor036b5a02009-01-13 00:11:19 +00001329 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001330 DeclContext::lookup_iterator Con, ConEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00001331 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001332 Con != ConEnd; ++Con) {
1333 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001334 if (Constructor->isConvertingConstructor())
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001335 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1336 /*SuppressUserConversions=*/true);
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001337 }
1338 }
1339
Douglas Gregorb206cc42009-01-30 23:27:23 +00001340 if (!AllowConversionFunctions) {
1341 // Don't allow any conversion functions to enter the overload set.
1342 } else if (const CXXRecordType *FromRecordType
1343 = dyn_cast_or_null<CXXRecordType>(
1344 From->getType()->getAsRecordType())) {
Douglas Gregor60714f92008-11-07 22:36:19 +00001345 // Add all of the conversion functions as candidates.
1346 // FIXME: Look for conversions in base classes!
1347 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
1348 OverloadedFunctionDecl *Conversions
1349 = FromRecordDecl->getConversionFunctions();
1350 for (OverloadedFunctionDecl::function_iterator Func
1351 = Conversions->function_begin();
1352 Func != Conversions->function_end(); ++Func) {
1353 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001354 if (AllowExplicit || !Conv->isExplicit())
1355 AddConversionCandidate(Conv, From, ToType, CandidateSet);
Douglas Gregor60714f92008-11-07 22:36:19 +00001356 }
1357 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001358
1359 OverloadCandidateSet::iterator Best;
1360 switch (BestViableFunction(CandidateSet, Best)) {
1361 case OR_Success:
1362 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001363 if (CXXConstructorDecl *Constructor
1364 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1365 // C++ [over.ics.user]p1:
1366 // If the user-defined conversion is specified by a
1367 // constructor (12.3.1), the initial standard conversion
1368 // sequence converts the source type to the type required by
1369 // the argument of the constructor.
1370 //
1371 // FIXME: What about ellipsis conversions?
1372 QualType ThisType = Constructor->getThisType(Context);
1373 User.Before = Best->Conversions[0].Standard;
1374 User.ConversionFunction = Constructor;
1375 User.After.setAsIdentityConversion();
1376 User.After.FromTypePtr
1377 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1378 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1379 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001380 } else if (CXXConversionDecl *Conversion
1381 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1382 // C++ [over.ics.user]p1:
1383 //
1384 // [...] If the user-defined conversion is specified by a
1385 // conversion function (12.3.2), the initial standard
1386 // conversion sequence converts the source type to the
1387 // implicit object parameter of the conversion function.
1388 User.Before = Best->Conversions[0].Standard;
1389 User.ConversionFunction = Conversion;
1390
1391 // C++ [over.ics.user]p2:
1392 // The second standard conversion sequence converts the
1393 // result of the user-defined conversion to the target type
1394 // for the sequence. Since an implicit conversion sequence
1395 // is an initialization, the special rules for
1396 // initialization by user-defined conversion apply when
1397 // selecting the best user-defined conversion for a
1398 // user-defined conversion sequence (see 13.3.3 and
1399 // 13.3.3.1).
1400 User.After = Best->FinalConversion;
1401 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001402 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001403 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001404 return false;
1405 }
1406
1407 case OR_No_Viable_Function:
1408 // No conversion here! We're done.
1409 return false;
1410
1411 case OR_Ambiguous:
1412 // FIXME: See C++ [over.best.ics]p10 for the handling of
1413 // ambiguous conversion sequences.
1414 return false;
1415 }
1416
1417 return false;
1418}
1419
Douglas Gregord2baafd2008-10-21 16:13:35 +00001420/// CompareImplicitConversionSequences - Compare two implicit
1421/// conversion sequences to determine whether one is better than the
1422/// other or if they are indistinguishable (C++ 13.3.3.2).
1423ImplicitConversionSequence::CompareKind
1424Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1425 const ImplicitConversionSequence& ICS2)
1426{
1427 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1428 // conversion sequences (as defined in 13.3.3.1)
1429 // -- a standard conversion sequence (13.3.3.1.1) is a better
1430 // conversion sequence than a user-defined conversion sequence or
1431 // an ellipsis conversion sequence, and
1432 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1433 // conversion sequence than an ellipsis conversion sequence
1434 // (13.3.3.1.3).
1435 //
1436 if (ICS1.ConversionKind < ICS2.ConversionKind)
1437 return ImplicitConversionSequence::Better;
1438 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1439 return ImplicitConversionSequence::Worse;
1440
1441 // Two implicit conversion sequences of the same form are
1442 // indistinguishable conversion sequences unless one of the
1443 // following rules apply: (C++ 13.3.3.2p3):
1444 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1445 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1446 else if (ICS1.ConversionKind ==
1447 ImplicitConversionSequence::UserDefinedConversion) {
1448 // User-defined conversion sequence U1 is a better conversion
1449 // sequence than another user-defined conversion sequence U2 if
1450 // they contain the same user-defined conversion function or
1451 // constructor and if the second standard conversion sequence of
1452 // U1 is better than the second standard conversion sequence of
1453 // U2 (C++ 13.3.3.2p3).
1454 if (ICS1.UserDefined.ConversionFunction ==
1455 ICS2.UserDefined.ConversionFunction)
1456 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1457 ICS2.UserDefined.After);
1458 }
1459
1460 return ImplicitConversionSequence::Indistinguishable;
1461}
1462
1463/// CompareStandardConversionSequences - Compare two standard
1464/// conversion sequences to determine whether one is better than the
1465/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1466ImplicitConversionSequence::CompareKind
1467Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1468 const StandardConversionSequence& SCS2)
1469{
1470 // Standard conversion sequence S1 is a better conversion sequence
1471 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1472
1473 // -- S1 is a proper subsequence of S2 (comparing the conversion
1474 // sequences in the canonical form defined by 13.3.3.1.1,
1475 // excluding any Lvalue Transformation; the identity conversion
1476 // sequence is considered to be a subsequence of any
1477 // non-identity conversion sequence) or, if not that,
1478 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1479 // Neither is a proper subsequence of the other. Do nothing.
1480 ;
1481 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1482 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1483 (SCS1.Second == ICK_Identity &&
1484 SCS1.Third == ICK_Identity))
1485 // SCS1 is a proper subsequence of SCS2.
1486 return ImplicitConversionSequence::Better;
1487 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1488 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1489 (SCS2.Second == ICK_Identity &&
1490 SCS2.Third == ICK_Identity))
1491 // SCS2 is a proper subsequence of SCS1.
1492 return ImplicitConversionSequence::Worse;
1493
1494 // -- the rank of S1 is better than the rank of S2 (by the rules
1495 // defined below), or, if not that,
1496 ImplicitConversionRank Rank1 = SCS1.getRank();
1497 ImplicitConversionRank Rank2 = SCS2.getRank();
1498 if (Rank1 < Rank2)
1499 return ImplicitConversionSequence::Better;
1500 else if (Rank2 < Rank1)
1501 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001502
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001503 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1504 // are indistinguishable unless one of the following rules
1505 // applies:
1506
1507 // A conversion that is not a conversion of a pointer, or
1508 // pointer to member, to bool is better than another conversion
1509 // that is such a conversion.
1510 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1511 return SCS2.isPointerConversionToBool()
1512 ? ImplicitConversionSequence::Better
1513 : ImplicitConversionSequence::Worse;
1514
Douglas Gregor14046502008-10-23 00:40:37 +00001515 // C++ [over.ics.rank]p4b2:
1516 //
1517 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001518 // conversion of B* to A* is better than conversion of B* to
1519 // void*, and conversion of A* to void* is better than conversion
1520 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001521 bool SCS1ConvertsToVoid
1522 = SCS1.isPointerConversionToVoidPointer(Context);
1523 bool SCS2ConvertsToVoid
1524 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001525 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1526 // Exactly one of the conversion sequences is a conversion to
1527 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001528 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1529 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001530 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1531 // Neither conversion sequence converts to a void pointer; compare
1532 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001533 if (ImplicitConversionSequence::CompareKind DerivedCK
1534 = CompareDerivedToBaseConversions(SCS1, SCS2))
1535 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001536 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1537 // Both conversion sequences are conversions to void
1538 // pointers. Compare the source types to determine if there's an
1539 // inheritance relationship in their sources.
1540 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1541 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1542
1543 // Adjust the types we're converting from via the array-to-pointer
1544 // conversion, if we need to.
1545 if (SCS1.First == ICK_Array_To_Pointer)
1546 FromType1 = Context.getArrayDecayedType(FromType1);
1547 if (SCS2.First == ICK_Array_To_Pointer)
1548 FromType2 = Context.getArrayDecayedType(FromType2);
1549
1550 QualType FromPointee1
1551 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1552 QualType FromPointee2
1553 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1554
1555 if (IsDerivedFrom(FromPointee2, FromPointee1))
1556 return ImplicitConversionSequence::Better;
1557 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1558 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001559
1560 // Objective-C++: If one interface is more specific than the
1561 // other, it is the better one.
1562 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1563 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1564 if (FromIface1 && FromIface1) {
1565 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1566 return ImplicitConversionSequence::Better;
1567 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1568 return ImplicitConversionSequence::Worse;
1569 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001570 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001571
1572 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1573 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001574 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001575 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001576 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001577
Douglas Gregor0e343382008-10-29 14:50:44 +00001578 // C++ [over.ics.rank]p3b4:
1579 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1580 // which the references refer are the same type except for
1581 // top-level cv-qualifiers, and the type to which the reference
1582 // initialized by S2 refers is more cv-qualified than the type
1583 // to which the reference initialized by S1 refers.
1584 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1585 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1586 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1587 T1 = Context.getCanonicalType(T1);
1588 T2 = Context.getCanonicalType(T2);
1589 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1590 if (T2.isMoreQualifiedThan(T1))
1591 return ImplicitConversionSequence::Better;
1592 else if (T1.isMoreQualifiedThan(T2))
1593 return ImplicitConversionSequence::Worse;
1594 }
1595 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001596
1597 return ImplicitConversionSequence::Indistinguishable;
1598}
1599
1600/// CompareQualificationConversions - Compares two standard conversion
1601/// sequences to determine whether they can be ranked based on their
1602/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1603ImplicitConversionSequence::CompareKind
1604Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1605 const StandardConversionSequence& SCS2)
1606{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001607 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001608 // -- S1 and S2 differ only in their qualification conversion and
1609 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1610 // cv-qualification signature of type T1 is a proper subset of
1611 // the cv-qualification signature of type T2, and S1 is not the
1612 // deprecated string literal array-to-pointer conversion (4.2).
1613 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1614 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1615 return ImplicitConversionSequence::Indistinguishable;
1616
1617 // FIXME: the example in the standard doesn't use a qualification
1618 // conversion (!)
1619 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1620 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1621 T1 = Context.getCanonicalType(T1);
1622 T2 = Context.getCanonicalType(T2);
1623
1624 // If the types are the same, we won't learn anything by unwrapped
1625 // them.
1626 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1627 return ImplicitConversionSequence::Indistinguishable;
1628
1629 ImplicitConversionSequence::CompareKind Result
1630 = ImplicitConversionSequence::Indistinguishable;
1631 while (UnwrapSimilarPointerTypes(T1, T2)) {
1632 // Within each iteration of the loop, we check the qualifiers to
1633 // determine if this still looks like a qualification
1634 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001635 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001636 // until there are no more pointers or pointers-to-members left
1637 // to unwrap. This essentially mimics what
1638 // IsQualificationConversion does, but here we're checking for a
1639 // strict subset of qualifiers.
1640 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1641 // The qualifiers are the same, so this doesn't tell us anything
1642 // about how the sequences rank.
1643 ;
1644 else if (T2.isMoreQualifiedThan(T1)) {
1645 // T1 has fewer qualifiers, so it could be the better sequence.
1646 if (Result == ImplicitConversionSequence::Worse)
1647 // Neither has qualifiers that are a subset of the other's
1648 // qualifiers.
1649 return ImplicitConversionSequence::Indistinguishable;
1650
1651 Result = ImplicitConversionSequence::Better;
1652 } else if (T1.isMoreQualifiedThan(T2)) {
1653 // T2 has fewer qualifiers, so it could be the better sequence.
1654 if (Result == ImplicitConversionSequence::Better)
1655 // Neither has qualifiers that are a subset of the other's
1656 // qualifiers.
1657 return ImplicitConversionSequence::Indistinguishable;
1658
1659 Result = ImplicitConversionSequence::Worse;
1660 } else {
1661 // Qualifiers are disjoint.
1662 return ImplicitConversionSequence::Indistinguishable;
1663 }
1664
1665 // If the types after this point are equivalent, we're done.
1666 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1667 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001668 }
1669
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001670 // Check that the winning standard conversion sequence isn't using
1671 // the deprecated string literal array to pointer conversion.
1672 switch (Result) {
1673 case ImplicitConversionSequence::Better:
1674 if (SCS1.Deprecated)
1675 Result = ImplicitConversionSequence::Indistinguishable;
1676 break;
1677
1678 case ImplicitConversionSequence::Indistinguishable:
1679 break;
1680
1681 case ImplicitConversionSequence::Worse:
1682 if (SCS2.Deprecated)
1683 Result = ImplicitConversionSequence::Indistinguishable;
1684 break;
1685 }
1686
1687 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001688}
1689
Douglas Gregor14046502008-10-23 00:40:37 +00001690/// CompareDerivedToBaseConversions - Compares two standard conversion
1691/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001692/// various kinds of derived-to-base conversions (C++
1693/// [over.ics.rank]p4b3). As part of these checks, we also look at
1694/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001695ImplicitConversionSequence::CompareKind
1696Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1697 const StandardConversionSequence& SCS2) {
1698 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1699 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1700 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1701 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1702
1703 // Adjust the types we're converting from via the array-to-pointer
1704 // conversion, if we need to.
1705 if (SCS1.First == ICK_Array_To_Pointer)
1706 FromType1 = Context.getArrayDecayedType(FromType1);
1707 if (SCS2.First == ICK_Array_To_Pointer)
1708 FromType2 = Context.getArrayDecayedType(FromType2);
1709
1710 // Canonicalize all of the types.
1711 FromType1 = Context.getCanonicalType(FromType1);
1712 ToType1 = Context.getCanonicalType(ToType1);
1713 FromType2 = Context.getCanonicalType(FromType2);
1714 ToType2 = Context.getCanonicalType(ToType2);
1715
Douglas Gregor0e343382008-10-29 14:50:44 +00001716 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001717 //
1718 // If class B is derived directly or indirectly from class A and
1719 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001720 //
1721 // For Objective-C, we let A, B, and C also be Objective-C
1722 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001723
1724 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001725 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001726 SCS2.Second == ICK_Pointer_Conversion &&
1727 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1728 FromType1->isPointerType() && FromType2->isPointerType() &&
1729 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001730 QualType FromPointee1
1731 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1732 QualType ToPointee1
1733 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1734 QualType FromPointee2
1735 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1736 QualType ToPointee2
1737 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001738
1739 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1740 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1741 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1742 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1743
Douglas Gregor0e343382008-10-29 14:50:44 +00001744 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001745 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1746 if (IsDerivedFrom(ToPointee1, ToPointee2))
1747 return ImplicitConversionSequence::Better;
1748 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1749 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001750
1751 if (ToIface1 && ToIface2) {
1752 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1753 return ImplicitConversionSequence::Better;
1754 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1755 return ImplicitConversionSequence::Worse;
1756 }
Douglas Gregor14046502008-10-23 00:40:37 +00001757 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001758
1759 // -- conversion of B* to A* is better than conversion of C* to A*,
1760 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1761 if (IsDerivedFrom(FromPointee2, FromPointee1))
1762 return ImplicitConversionSequence::Better;
1763 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1764 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001765
1766 if (FromIface1 && FromIface2) {
1767 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1768 return ImplicitConversionSequence::Better;
1769 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1770 return ImplicitConversionSequence::Worse;
1771 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001772 }
Douglas Gregor14046502008-10-23 00:40:37 +00001773 }
1774
Douglas Gregor0e343382008-10-29 14:50:44 +00001775 // Compare based on reference bindings.
1776 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1777 SCS1.Second == ICK_Derived_To_Base) {
1778 // -- binding of an expression of type C to a reference of type
1779 // B& is better than binding an expression of type C to a
1780 // reference of type A&,
1781 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1782 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1783 if (IsDerivedFrom(ToType1, ToType2))
1784 return ImplicitConversionSequence::Better;
1785 else if (IsDerivedFrom(ToType2, ToType1))
1786 return ImplicitConversionSequence::Worse;
1787 }
1788
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001789 // -- binding of an expression of type B to a reference of type
1790 // A& is better than binding an expression of type C to a
1791 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001792 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1793 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1794 if (IsDerivedFrom(FromType2, FromType1))
1795 return ImplicitConversionSequence::Better;
1796 else if (IsDerivedFrom(FromType1, FromType2))
1797 return ImplicitConversionSequence::Worse;
1798 }
1799 }
1800
1801
1802 // FIXME: conversion of A::* to B::* is better than conversion of
1803 // A::* to C::*,
1804
1805 // FIXME: conversion of B::* to C::* is better than conversion of
1806 // A::* to C::*, and
1807
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001808 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1809 SCS1.Second == ICK_Derived_To_Base) {
1810 // -- conversion of C to B is better than conversion of C to A,
1811 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1812 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1813 if (IsDerivedFrom(ToType1, ToType2))
1814 return ImplicitConversionSequence::Better;
1815 else if (IsDerivedFrom(ToType2, ToType1))
1816 return ImplicitConversionSequence::Worse;
1817 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001818
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001819 // -- conversion of B to A is better than conversion of C to A.
1820 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1821 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1822 if (IsDerivedFrom(FromType2, FromType1))
1823 return ImplicitConversionSequence::Better;
1824 else if (IsDerivedFrom(FromType1, FromType2))
1825 return ImplicitConversionSequence::Worse;
1826 }
1827 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001828
Douglas Gregor14046502008-10-23 00:40:37 +00001829 return ImplicitConversionSequence::Indistinguishable;
1830}
1831
Douglas Gregor81c29152008-10-29 00:13:59 +00001832/// TryCopyInitialization - Try to copy-initialize a value of type
1833/// ToType from the expression From. Return the implicit conversion
1834/// sequence required to pass this argument, which may be a bad
1835/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001836/// a parameter of this type). If @p SuppressUserConversions, then we
1837/// do not permit any user-defined conversion sequences.
Douglas Gregor81c29152008-10-29 00:13:59 +00001838ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001839Sema::TryCopyInitialization(Expr *From, QualType ToType,
1840 bool SuppressUserConversions) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001841 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001842 ImplicitConversionSequence ICS;
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001843 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001844 return ICS;
1845 } else {
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001846 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001847 }
1848}
1849
1850/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1851/// type ToType. Returns true (and emits a diagnostic) if there was
1852/// an error, returns false if the initialization succeeded.
1853bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1854 const char* Flavor) {
1855 if (!getLangOptions().CPlusPlus) {
1856 // In C, argument passing is the same as performing an assignment.
1857 QualType FromType = From->getType();
1858 AssignConvertType ConvTy =
1859 CheckSingleAssignmentConstraints(ToType, From);
1860
1861 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1862 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001863 }
Chris Lattner271d4c22008-11-24 05:29:24 +00001864
1865 if (ToType->isReferenceType())
1866 return CheckReferenceInit(From, ToType);
1867
Douglas Gregor6fd35572008-12-19 17:40:08 +00001868 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattner271d4c22008-11-24 05:29:24 +00001869 return false;
1870
1871 return Diag(From->getSourceRange().getBegin(),
1872 diag::err_typecheck_convert_incompatible)
1873 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001874}
1875
Douglas Gregor5ed15042008-11-18 23:14:02 +00001876/// TryObjectArgumentInitialization - Try to initialize the object
1877/// parameter of the given member function (@c Method) from the
1878/// expression @p From.
1879ImplicitConversionSequence
1880Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1881 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1882 unsigned MethodQuals = Method->getTypeQualifiers();
1883 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1884
1885 // Set up the conversion sequence as a "bad" conversion, to allow us
1886 // to exit early.
1887 ImplicitConversionSequence ICS;
1888 ICS.Standard.setAsIdentityConversion();
1889 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1890
1891 // We need to have an object of class type.
1892 QualType FromType = From->getType();
1893 if (!FromType->isRecordType())
1894 return ICS;
1895
1896 // The implicit object parmeter is has the type "reference to cv X",
1897 // where X is the class of which the function is a member
1898 // (C++ [over.match.funcs]p4). However, when finding an implicit
1899 // conversion sequence for the argument, we are not allowed to
1900 // create temporaries or perform user-defined conversions
1901 // (C++ [over.match.funcs]p5). We perform a simplified version of
1902 // reference binding here, that allows class rvalues to bind to
1903 // non-constant references.
1904
1905 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1906 // with the implicit object parameter (C++ [over.match.funcs]p5).
1907 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1908 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1909 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1910 return ICS;
1911
1912 // Check that we have either the same type or a derived type. It
1913 // affects the conversion rank.
1914 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1915 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1916 ICS.Standard.Second = ICK_Identity;
1917 else if (IsDerivedFrom(FromType, ClassType))
1918 ICS.Standard.Second = ICK_Derived_To_Base;
1919 else
1920 return ICS;
1921
1922 // Success. Mark this as a reference binding.
1923 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1924 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1925 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1926 ICS.Standard.ReferenceBinding = true;
1927 ICS.Standard.DirectBinding = true;
1928 return ICS;
1929}
1930
1931/// PerformObjectArgumentInitialization - Perform initialization of
1932/// the implicit object parameter for the given Method with the given
1933/// expression.
1934bool
1935Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1936 QualType ImplicitParamType
1937 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1938 ImplicitConversionSequence ICS
1939 = TryObjectArgumentInitialization(From, Method);
1940 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1941 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001942 diag::err_implicit_object_parameter_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001943 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor5ed15042008-11-18 23:14:02 +00001944
1945 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1946 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1947 From->getSourceRange().getBegin(),
1948 From->getSourceRange()))
1949 return true;
1950
1951 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1952 return false;
1953}
1954
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001955/// TryContextuallyConvertToBool - Attempt to contextually convert the
1956/// expression From to bool (C++0x [conv]p3).
1957ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1958 return TryImplicitConversion(From, Context.BoolTy, false, true);
1959}
1960
1961/// PerformContextuallyConvertToBool - Perform a contextual conversion
1962/// of the expression From to bool (C++0x [conv]p3).
1963bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1964 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1965 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1966 return false;
1967
1968 return Diag(From->getSourceRange().getBegin(),
1969 diag::err_typecheck_bool_condition)
1970 << From->getType() << From->getSourceRange();
1971}
1972
Douglas Gregord2baafd2008-10-21 16:13:35 +00001973/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001974/// candidate functions, using the given function call arguments. If
1975/// @p SuppressUserConversions, then don't allow user-defined
1976/// conversions via constructors or conversion operators.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001977void
1978Sema::AddOverloadCandidate(FunctionDecl *Function,
1979 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001980 OverloadCandidateSet& CandidateSet,
1981 bool SuppressUserConversions)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001982{
1983 const FunctionTypeProto* Proto
1984 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1985 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00001986 assert(!isa<CXXConversionDecl>(Function) &&
1987 "Use AddConversionCandidate for conversion functions");
Douglas Gregord2baafd2008-10-21 16:13:35 +00001988
Douglas Gregor3257fb52008-12-22 05:46:06 +00001989 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
1990 // If we get here, it's because we're calling a member function
1991 // that is named without a member access expression (e.g.,
1992 // "this->f") that was either written explicitly or created
1993 // implicitly. This can happen with a qualified call to a member
1994 // function, e.g., X::f(). We use a NULL object as the implied
1995 // object argument (C++ [over.call.func]p3).
1996 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
1997 SuppressUserConversions);
1998 return;
1999 }
2000
2001
Douglas Gregord2baafd2008-10-21 16:13:35 +00002002 // Add this candidate
2003 CandidateSet.push_back(OverloadCandidate());
2004 OverloadCandidate& Candidate = CandidateSet.back();
2005 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002006 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002007 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002008 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002009
2010 unsigned NumArgsInProto = Proto->getNumArgs();
2011
2012 // (C++ 13.3.2p2): A candidate function having fewer than m
2013 // parameters is viable only if it has an ellipsis in its parameter
2014 // list (8.3.5).
2015 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2016 Candidate.Viable = false;
2017 return;
2018 }
2019
2020 // (C++ 13.3.2p2): A candidate function having more than m parameters
2021 // is viable only if the (m+1)st parameter has a default argument
2022 // (8.3.6). For the purposes of overload resolution, the
2023 // parameter list is truncated on the right, so that there are
2024 // exactly m parameters.
2025 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2026 if (NumArgs < MinRequiredArgs) {
2027 // Not enough arguments.
2028 Candidate.Viable = false;
2029 return;
2030 }
2031
2032 // Determine the implicit conversion sequences for each of the
2033 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002034 Candidate.Conversions.resize(NumArgs);
2035 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2036 if (ArgIdx < NumArgsInProto) {
2037 // (C++ 13.3.2p3): for F to be a viable function, there shall
2038 // exist for each argument an implicit conversion sequence
2039 // (13.3.3.1) that converts that argument to the corresponding
2040 // parameter of F.
2041 QualType ParamType = Proto->getArgType(ArgIdx);
2042 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002043 = TryCopyInitialization(Args[ArgIdx], ParamType,
2044 SuppressUserConversions);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002045 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002046 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002047 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002048 break;
2049 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002050 } else {
2051 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2052 // argument for which there is no corresponding parameter is
2053 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2054 Candidate.Conversions[ArgIdx].ConversionKind
2055 = ImplicitConversionSequence::EllipsisConversion;
2056 }
2057 }
2058}
2059
Douglas Gregor5ed15042008-11-18 23:14:02 +00002060/// AddMethodCandidate - Adds the given C++ member function to the set
2061/// of candidate functions, using the given function call arguments
2062/// and the object argument (@c Object). For example, in a call
2063/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2064/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2065/// allow user-defined conversions via constructors or conversion
2066/// operators.
2067void
2068Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2069 Expr **Args, unsigned NumArgs,
2070 OverloadCandidateSet& CandidateSet,
2071 bool SuppressUserConversions)
2072{
2073 const FunctionTypeProto* Proto
2074 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
2075 assert(Proto && "Methods without a prototype cannot be overloaded");
2076 assert(!isa<CXXConversionDecl>(Method) &&
2077 "Use AddConversionCandidate for conversion functions");
2078
2079 // Add this candidate
2080 CandidateSet.push_back(OverloadCandidate());
2081 OverloadCandidate& Candidate = CandidateSet.back();
2082 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002083 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002084 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002085
2086 unsigned NumArgsInProto = Proto->getNumArgs();
2087
2088 // (C++ 13.3.2p2): A candidate function having fewer than m
2089 // parameters is viable only if it has an ellipsis in its parameter
2090 // list (8.3.5).
2091 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2092 Candidate.Viable = false;
2093 return;
2094 }
2095
2096 // (C++ 13.3.2p2): A candidate function having more than m parameters
2097 // is viable only if the (m+1)st parameter has a default argument
2098 // (8.3.6). For the purposes of overload resolution, the
2099 // parameter list is truncated on the right, so that there are
2100 // exactly m parameters.
2101 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2102 if (NumArgs < MinRequiredArgs) {
2103 // Not enough arguments.
2104 Candidate.Viable = false;
2105 return;
2106 }
2107
2108 Candidate.Viable = true;
2109 Candidate.Conversions.resize(NumArgs + 1);
2110
Douglas Gregor3257fb52008-12-22 05:46:06 +00002111 if (Method->isStatic() || !Object)
2112 // The implicit object argument is ignored.
2113 Candidate.IgnoreObjectArgument = true;
2114 else {
2115 // Determine the implicit conversion sequence for the object
2116 // parameter.
2117 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2118 if (Candidate.Conversions[0].ConversionKind
2119 == ImplicitConversionSequence::BadConversion) {
2120 Candidate.Viable = false;
2121 return;
2122 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002123 }
2124
2125 // Determine the implicit conversion sequences for each of the
2126 // arguments.
2127 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2128 if (ArgIdx < NumArgsInProto) {
2129 // (C++ 13.3.2p3): for F to be a viable function, there shall
2130 // exist for each argument an implicit conversion sequence
2131 // (13.3.3.1) that converts that argument to the corresponding
2132 // parameter of F.
2133 QualType ParamType = Proto->getArgType(ArgIdx);
2134 Candidate.Conversions[ArgIdx + 1]
2135 = TryCopyInitialization(Args[ArgIdx], ParamType,
2136 SuppressUserConversions);
2137 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2138 == ImplicitConversionSequence::BadConversion) {
2139 Candidate.Viable = false;
2140 break;
2141 }
2142 } else {
2143 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2144 // argument for which there is no corresponding parameter is
2145 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2146 Candidate.Conversions[ArgIdx + 1].ConversionKind
2147 = ImplicitConversionSequence::EllipsisConversion;
2148 }
2149 }
2150}
2151
Douglas Gregor60714f92008-11-07 22:36:19 +00002152/// AddConversionCandidate - Add a C++ conversion function as a
2153/// candidate in the candidate set (C++ [over.match.conv],
2154/// C++ [over.match.copy]). From is the expression we're converting from,
2155/// and ToType is the type that we're eventually trying to convert to
2156/// (which may or may not be the same type as the type that the
2157/// conversion function produces).
2158void
2159Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2160 Expr *From, QualType ToType,
2161 OverloadCandidateSet& CandidateSet) {
2162 // Add this candidate
2163 CandidateSet.push_back(OverloadCandidate());
2164 OverloadCandidate& Candidate = CandidateSet.back();
2165 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002166 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002167 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002168 Candidate.FinalConversion.setAsIdentityConversion();
2169 Candidate.FinalConversion.FromTypePtr
2170 = Conversion->getConversionType().getAsOpaquePtr();
2171 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2172
Douglas Gregor5ed15042008-11-18 23:14:02 +00002173 // Determine the implicit conversion sequence for the implicit
2174 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002175 Candidate.Viable = true;
2176 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002177 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002178
Douglas Gregor60714f92008-11-07 22:36:19 +00002179 if (Candidate.Conversions[0].ConversionKind
2180 == ImplicitConversionSequence::BadConversion) {
2181 Candidate.Viable = false;
2182 return;
2183 }
2184
2185 // To determine what the conversion from the result of calling the
2186 // conversion function to the type we're eventually trying to
2187 // convert to (ToType), we need to synthesize a call to the
2188 // conversion function and attempt copy initialization from it. This
2189 // makes sure that we get the right semantics with respect to
2190 // lvalues/rvalues and the type. Fortunately, we can allocate this
2191 // call on the stack and we don't need its arguments to be
2192 // well-formed.
2193 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2194 SourceLocation());
2195 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregor70d26122008-11-12 17:17:38 +00002196 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002197
2198 // Note that it is safe to allocate CallExpr on the stack here because
2199 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2200 // allocator).
2201 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002202 Conversion->getConversionType().getNonReferenceType(),
2203 SourceLocation());
2204 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2205 switch (ICS.ConversionKind) {
2206 case ImplicitConversionSequence::StandardConversion:
2207 Candidate.FinalConversion = ICS.Standard;
2208 break;
2209
2210 case ImplicitConversionSequence::BadConversion:
2211 Candidate.Viable = false;
2212 break;
2213
2214 default:
2215 assert(false &&
2216 "Can only end up with a standard conversion sequence or failure");
2217 }
2218}
2219
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002220/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2221/// converts the given @c Object to a function pointer via the
2222/// conversion function @c Conversion, and then attempts to call it
2223/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2224/// the type of function that we'll eventually be calling.
2225void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2226 const FunctionTypeProto *Proto,
2227 Expr *Object, Expr **Args, unsigned NumArgs,
2228 OverloadCandidateSet& CandidateSet) {
2229 CandidateSet.push_back(OverloadCandidate());
2230 OverloadCandidate& Candidate = CandidateSet.back();
2231 Candidate.Function = 0;
2232 Candidate.Surrogate = Conversion;
2233 Candidate.Viable = true;
2234 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002235 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002236 Candidate.Conversions.resize(NumArgs + 1);
2237
2238 // Determine the implicit conversion sequence for the implicit
2239 // object parameter.
2240 ImplicitConversionSequence ObjectInit
2241 = TryObjectArgumentInitialization(Object, Conversion);
2242 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2243 Candidate.Viable = false;
2244 return;
2245 }
2246
2247 // The first conversion is actually a user-defined conversion whose
2248 // first conversion is ObjectInit's standard conversion (which is
2249 // effectively a reference binding). Record it as such.
2250 Candidate.Conversions[0].ConversionKind
2251 = ImplicitConversionSequence::UserDefinedConversion;
2252 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2253 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2254 Candidate.Conversions[0].UserDefined.After
2255 = Candidate.Conversions[0].UserDefined.Before;
2256 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2257
2258 // Find the
2259 unsigned NumArgsInProto = Proto->getNumArgs();
2260
2261 // (C++ 13.3.2p2): A candidate function having fewer than m
2262 // parameters is viable only if it has an ellipsis in its parameter
2263 // list (8.3.5).
2264 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2265 Candidate.Viable = false;
2266 return;
2267 }
2268
2269 // Function types don't have any default arguments, so just check if
2270 // we have enough arguments.
2271 if (NumArgs < NumArgsInProto) {
2272 // Not enough arguments.
2273 Candidate.Viable = false;
2274 return;
2275 }
2276
2277 // Determine the implicit conversion sequences for each of the
2278 // arguments.
2279 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2280 if (ArgIdx < NumArgsInProto) {
2281 // (C++ 13.3.2p3): for F to be a viable function, there shall
2282 // exist for each argument an implicit conversion sequence
2283 // (13.3.3.1) that converts that argument to the corresponding
2284 // parameter of F.
2285 QualType ParamType = Proto->getArgType(ArgIdx);
2286 Candidate.Conversions[ArgIdx + 1]
2287 = TryCopyInitialization(Args[ArgIdx], ParamType,
2288 /*SuppressUserConversions=*/false);
2289 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2290 == ImplicitConversionSequence::BadConversion) {
2291 Candidate.Viable = false;
2292 break;
2293 }
2294 } else {
2295 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2296 // argument for which there is no corresponding parameter is
2297 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2298 Candidate.Conversions[ArgIdx + 1].ConversionKind
2299 = ImplicitConversionSequence::EllipsisConversion;
2300 }
2301 }
2302}
2303
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002304/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2305/// an acceptable non-member overloaded operator for a call whose
2306/// arguments have types T1 (and, if non-empty, T2). This routine
2307/// implements the check in C++ [over.match.oper]p3b2 concerning
2308/// enumeration types.
2309static bool
2310IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2311 QualType T1, QualType T2,
2312 ASTContext &Context) {
2313 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2314 return true;
2315
2316 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
2317 if (Proto->getNumArgs() < 1)
2318 return false;
2319
2320 if (T1->isEnumeralType()) {
2321 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2322 if (Context.getCanonicalType(T1).getUnqualifiedType()
2323 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2324 return true;
2325 }
2326
2327 if (Proto->getNumArgs() < 2)
2328 return false;
2329
2330 if (!T2.isNull() && T2->isEnumeralType()) {
2331 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2332 if (Context.getCanonicalType(T2).getUnqualifiedType()
2333 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2334 return true;
2335 }
2336
2337 return false;
2338}
2339
Douglas Gregor5ed15042008-11-18 23:14:02 +00002340/// AddOperatorCandidates - Add the overloaded operator candidates for
2341/// the operator Op that was used in an operator expression such as "x
2342/// Op y". S is the scope in which the expression occurred (used for
2343/// name lookup of the operator), Args/NumArgs provides the operator
2344/// arguments, and CandidateSet will store the added overload
2345/// candidates. (C++ [over.match.oper]).
Douglas Gregor48a87322009-02-04 16:44:47 +00002346bool Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2347 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002348 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002349 OverloadCandidateSet& CandidateSet,
2350 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002351 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2352
2353 // C++ [over.match.oper]p3:
2354 // For a unary operator @ with an operand of a type whose
2355 // cv-unqualified version is T1, and for a binary operator @ with
2356 // a left operand of a type whose cv-unqualified version is T1 and
2357 // a right operand of a type whose cv-unqualified version is T2,
2358 // three sets of candidate functions, designated member
2359 // candidates, non-member candidates and built-in candidates, are
2360 // constructed as follows:
2361 QualType T1 = Args[0]->getType();
2362 QualType T2;
2363 if (NumArgs > 1)
2364 T2 = Args[1]->getType();
2365
2366 // -- If T1 is a class type, the set of member candidates is the
2367 // result of the qualified lookup of T1::operator@
2368 // (13.3.1.1.1); otherwise, the set of member candidates is
2369 // empty.
2370 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002371 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00002372 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002373 Oper != OperEnd; ++Oper)
2374 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2375 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002376 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002377 }
2378
2379 // -- The set of non-member candidates is the result of the
2380 // unqualified lookup of operator@ in the context of the
2381 // expression according to the usual rules for name lookup in
2382 // unqualified function calls (3.4.2) except that all member
2383 // functions are ignored. However, if no operand has a class
2384 // type, only those non-member functions in the lookup set
2385 // that have a first parameter of type T1 or “reference to
2386 // (possibly cv-qualified) T1”, when T1 is an enumeration
2387 // type, or (if there is a right operand) a second parameter
2388 // of type T2 or “reference to (possibly cv-qualified) T2”,
2389 // when T2 is an enumeration type, are candidate functions.
Douglas Gregor48a87322009-02-04 16:44:47 +00002390 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
2391
2392 if (Operators.isAmbiguous())
2393 return DiagnoseAmbiguousLookup(Operators, OpName, OpLoc, OpRange);
2394 else if (Operators) {
2395 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2396 Op != OpEnd; ++Op) {
2397 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
2398 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2399 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2400 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002401 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002402 }
2403
Douglas Gregor48a87322009-02-04 16:44:47 +00002404 // Since the set of non-member candidates corresponds to
2405 // *unqualified* lookup of the operator name, we also perform
2406 // argument-dependent lookup (C++ [basic.lookup.argdep]).
2407 AddArgumentDependentLookupCandidates(OpName, Args, NumArgs, CandidateSet);
2408
Douglas Gregor5ed15042008-11-18 23:14:02 +00002409 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002410 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor48a87322009-02-04 16:44:47 +00002411
2412 return false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002413}
2414
Douglas Gregor70d26122008-11-12 17:17:38 +00002415/// AddBuiltinCandidate - Add a candidate for a built-in
2416/// operator. ResultTy and ParamTys are the result and parameter types
2417/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002418/// arguments being passed to the candidate. IsAssignmentOperator
2419/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002420/// operator. NumContextualBoolArguments is the number of arguments
2421/// (at the beginning of the argument list) that will be contextually
2422/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002423void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2424 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002425 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002426 bool IsAssignmentOperator,
2427 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002428 // Add this candidate
2429 CandidateSet.push_back(OverloadCandidate());
2430 OverloadCandidate& Candidate = CandidateSet.back();
2431 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002432 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002433 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002434 Candidate.BuiltinTypes.ResultTy = ResultTy;
2435 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2436 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2437
2438 // Determine the implicit conversion sequences for each of the
2439 // arguments.
2440 Candidate.Viable = true;
2441 Candidate.Conversions.resize(NumArgs);
2442 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002443 // C++ [over.match.oper]p4:
2444 // For the built-in assignment operators, conversions of the
2445 // left operand are restricted as follows:
2446 // -- no temporaries are introduced to hold the left operand, and
2447 // -- no user-defined conversions are applied to the left
2448 // operand to achieve a type match with the left-most
2449 // parameter of a built-in candidate.
2450 //
2451 // We block these conversions by turning off user-defined
2452 // conversions, since that is the only way that initialization of
2453 // a reference to a non-class type can occur from something that
2454 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002455 if (ArgIdx < NumContextualBoolArguments) {
2456 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2457 "Contextual conversion to bool requires bool type");
2458 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2459 } else {
2460 Candidate.Conversions[ArgIdx]
2461 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2462 ArgIdx == 0 && IsAssignmentOperator);
2463 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002464 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002465 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002466 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002467 break;
2468 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002469 }
2470}
2471
2472/// BuiltinCandidateTypeSet - A set of types that will be used for the
2473/// candidate operator functions for built-in operators (C++
2474/// [over.built]). The types are separated into pointer types and
2475/// enumeration types.
2476class BuiltinCandidateTypeSet {
2477 /// TypeSet - A set of types.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002478 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002479
2480 /// PointerTypes - The set of pointer types that will be used in the
2481 /// built-in candidates.
2482 TypeSet PointerTypes;
2483
2484 /// EnumerationTypes - The set of enumeration types that will be
2485 /// used in the built-in candidates.
2486 TypeSet EnumerationTypes;
2487
2488 /// Context - The AST context in which we will build the type sets.
2489 ASTContext &Context;
2490
2491 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2492
2493public:
2494 /// iterator - Iterates through the types that are part of the set.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002495 class iterator {
2496 TypeSet::iterator Base;
2497
2498 public:
2499 typedef QualType value_type;
2500 typedef QualType reference;
2501 typedef QualType pointer;
2502 typedef std::ptrdiff_t difference_type;
2503 typedef std::input_iterator_tag iterator_category;
2504
2505 iterator(TypeSet::iterator B) : Base(B) { }
2506
2507 iterator& operator++() {
2508 ++Base;
2509 return *this;
2510 }
2511
2512 iterator operator++(int) {
2513 iterator tmp(*this);
2514 ++(*this);
2515 return tmp;
2516 }
2517
2518 reference operator*() const {
2519 return QualType::getFromOpaquePtr(*Base);
2520 }
2521
2522 pointer operator->() const {
2523 return **this;
2524 }
2525
2526 friend bool operator==(iterator LHS, iterator RHS) {
2527 return LHS.Base == RHS.Base;
2528 }
2529
2530 friend bool operator!=(iterator LHS, iterator RHS) {
2531 return LHS.Base != RHS.Base;
2532 }
2533 };
Douglas Gregor70d26122008-11-12 17:17:38 +00002534
2535 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2536
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002537 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2538 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002539
2540 /// pointer_begin - First pointer type found;
2541 iterator pointer_begin() { return PointerTypes.begin(); }
2542
2543 /// pointer_end - Last pointer type found;
2544 iterator pointer_end() { return PointerTypes.end(); }
2545
2546 /// enumeration_begin - First enumeration type found;
2547 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2548
2549 /// enumeration_end - Last enumeration type found;
2550 iterator enumeration_end() { return EnumerationTypes.end(); }
2551};
2552
2553/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2554/// the set of pointer types along with any more-qualified variants of
2555/// that type. For example, if @p Ty is "int const *", this routine
2556/// will add "int const *", "int const volatile *", "int const
2557/// restrict *", and "int const volatile restrict *" to the set of
2558/// pointer types. Returns true if the add of @p Ty itself succeeded,
2559/// false otherwise.
2560bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2561 // Insert this type.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002562 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregor70d26122008-11-12 17:17:38 +00002563 return false;
2564
2565 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2566 QualType PointeeTy = PointerTy->getPointeeType();
2567 // FIXME: Optimize this so that we don't keep trying to add the same types.
2568
2569 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2570 // with all pointer conversions that don't cast away constness?
2571 if (!PointeeTy.isConstQualified())
2572 AddWithMoreQualifiedTypeVariants
2573 (Context.getPointerType(PointeeTy.withConst()));
2574 if (!PointeeTy.isVolatileQualified())
2575 AddWithMoreQualifiedTypeVariants
2576 (Context.getPointerType(PointeeTy.withVolatile()));
2577 if (!PointeeTy.isRestrictQualified())
2578 AddWithMoreQualifiedTypeVariants
2579 (Context.getPointerType(PointeeTy.withRestrict()));
2580 }
2581
2582 return true;
2583}
2584
2585/// AddTypesConvertedFrom - Add each of the types to which the type @p
2586/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002587/// primarily interested in pointer types and enumeration types.
2588/// AllowUserConversions is true if we should look at the conversion
2589/// functions of a class type, and AllowExplicitConversions if we
2590/// should also include the explicit conversion functions of a class
2591/// type.
2592void
2593BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2594 bool AllowUserConversions,
2595 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002596 // Only deal with canonical types.
2597 Ty = Context.getCanonicalType(Ty);
2598
2599 // Look through reference types; they aren't part of the type of an
2600 // expression for the purposes of conversions.
2601 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2602 Ty = RefTy->getPointeeType();
2603
2604 // We don't care about qualifiers on the type.
2605 Ty = Ty.getUnqualifiedType();
2606
2607 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2608 QualType PointeeTy = PointerTy->getPointeeType();
2609
2610 // Insert our type, and its more-qualified variants, into the set
2611 // of types.
2612 if (!AddWithMoreQualifiedTypeVariants(Ty))
2613 return;
2614
2615 // Add 'cv void*' to our set of types.
2616 if (!Ty->isVoidType()) {
2617 QualType QualVoid
2618 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2619 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2620 }
2621
2622 // If this is a pointer to a class type, add pointers to its bases
2623 // (with the same level of cv-qualification as the original
2624 // derived class, of course).
2625 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2626 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2627 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2628 Base != ClassDecl->bases_end(); ++Base) {
2629 QualType BaseTy = Context.getCanonicalType(Base->getType());
2630 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2631
2632 // Add the pointer type, recursively, so that we get all of
2633 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002634 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002635 }
2636 }
2637 } else if (Ty->isEnumeralType()) {
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002638 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregor70d26122008-11-12 17:17:38 +00002639 } else if (AllowUserConversions) {
2640 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2641 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2642 // FIXME: Visit conversion functions in the base classes, too.
2643 OverloadedFunctionDecl *Conversions
2644 = ClassDecl->getConversionFunctions();
2645 for (OverloadedFunctionDecl::function_iterator Func
2646 = Conversions->function_begin();
2647 Func != Conversions->function_end(); ++Func) {
2648 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002649 if (AllowExplicitConversions || !Conv->isExplicit())
2650 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002651 }
2652 }
2653 }
2654}
2655
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002656/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2657/// operator overloads to the candidate set (C++ [over.built]), based
2658/// on the operator @p Op and the arguments given. For example, if the
2659/// operator is a binary '+', this routine might add "int
2660/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002661void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002662Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2663 Expr **Args, unsigned NumArgs,
2664 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002665 // The set of "promoted arithmetic types", which are the arithmetic
2666 // types are that preserved by promotion (C++ [over.built]p2). Note
2667 // that the first few of these types are the promoted integral
2668 // types; these types need to be first.
2669 // FIXME: What about complex?
2670 const unsigned FirstIntegralType = 0;
2671 const unsigned LastIntegralType = 13;
2672 const unsigned FirstPromotedIntegralType = 7,
2673 LastPromotedIntegralType = 13;
2674 const unsigned FirstPromotedArithmeticType = 7,
2675 LastPromotedArithmeticType = 16;
2676 const unsigned NumArithmeticTypes = 16;
2677 QualType ArithmeticTypes[NumArithmeticTypes] = {
2678 Context.BoolTy, Context.CharTy, Context.WCharTy,
2679 Context.SignedCharTy, Context.ShortTy,
2680 Context.UnsignedCharTy, Context.UnsignedShortTy,
2681 Context.IntTy, Context.LongTy, Context.LongLongTy,
2682 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2683 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2684 };
2685
2686 // Find all of the types that the arguments can convert to, but only
2687 // if the operator we're looking at has built-in operator candidates
2688 // that make use of these types.
2689 BuiltinCandidateTypeSet CandidateTypes(Context);
2690 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2691 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002692 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002693 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002694 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2695 (Op == OO_Star && NumArgs == 1)) {
2696 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002697 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2698 true,
2699 (Op == OO_Exclaim ||
2700 Op == OO_AmpAmp ||
2701 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002702 }
2703
2704 bool isComparison = false;
2705 switch (Op) {
2706 case OO_None:
2707 case NUM_OVERLOADED_OPERATORS:
2708 assert(false && "Expected an overloaded operator");
2709 break;
2710
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002711 case OO_Star: // '*' is either unary or binary
2712 if (NumArgs == 1)
2713 goto UnaryStar;
2714 else
2715 goto BinaryStar;
2716 break;
2717
2718 case OO_Plus: // '+' is either unary or binary
2719 if (NumArgs == 1)
2720 goto UnaryPlus;
2721 else
2722 goto BinaryPlus;
2723 break;
2724
2725 case OO_Minus: // '-' is either unary or binary
2726 if (NumArgs == 1)
2727 goto UnaryMinus;
2728 else
2729 goto BinaryMinus;
2730 break;
2731
2732 case OO_Amp: // '&' is either unary or binary
2733 if (NumArgs == 1)
2734 goto UnaryAmp;
2735 else
2736 goto BinaryAmp;
2737
2738 case OO_PlusPlus:
2739 case OO_MinusMinus:
2740 // C++ [over.built]p3:
2741 //
2742 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2743 // is either volatile or empty, there exist candidate operator
2744 // functions of the form
2745 //
2746 // VQ T& operator++(VQ T&);
2747 // T operator++(VQ T&, int);
2748 //
2749 // C++ [over.built]p4:
2750 //
2751 // For every pair (T, VQ), where T is an arithmetic type other
2752 // than bool, and VQ is either volatile or empty, there exist
2753 // candidate operator functions of the form
2754 //
2755 // VQ T& operator--(VQ T&);
2756 // T operator--(VQ T&, int);
2757 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2758 Arith < NumArithmeticTypes; ++Arith) {
2759 QualType ArithTy = ArithmeticTypes[Arith];
2760 QualType ParamTypes[2]
2761 = { Context.getReferenceType(ArithTy), Context.IntTy };
2762
2763 // Non-volatile version.
2764 if (NumArgs == 1)
2765 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2766 else
2767 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2768
2769 // Volatile version
2770 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2771 if (NumArgs == 1)
2772 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2773 else
2774 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2775 }
2776
2777 // C++ [over.built]p5:
2778 //
2779 // For every pair (T, VQ), where T is a cv-qualified or
2780 // cv-unqualified object type, and VQ is either volatile or
2781 // empty, there exist candidate operator functions of the form
2782 //
2783 // T*VQ& operator++(T*VQ&);
2784 // T*VQ& operator--(T*VQ&);
2785 // T* operator++(T*VQ&, int);
2786 // T* operator--(T*VQ&, int);
2787 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2788 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2789 // Skip pointer types that aren't pointers to object types.
Douglas Gregor24a90a52008-11-26 23:31:11 +00002790 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002791 continue;
2792
2793 QualType ParamTypes[2] = {
2794 Context.getReferenceType(*Ptr), Context.IntTy
2795 };
2796
2797 // Without volatile
2798 if (NumArgs == 1)
2799 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2800 else
2801 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2802
2803 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2804 // With volatile
2805 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2806 if (NumArgs == 1)
2807 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2808 else
2809 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2810 }
2811 }
2812 break;
2813
2814 UnaryStar:
2815 // C++ [over.built]p6:
2816 // For every cv-qualified or cv-unqualified object type T, there
2817 // exist candidate operator functions of the form
2818 //
2819 // T& operator*(T*);
2820 //
2821 // C++ [over.built]p7:
2822 // For every function type T, there exist candidate operator
2823 // functions of the form
2824 // T& operator*(T*);
2825 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2826 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2827 QualType ParamTy = *Ptr;
2828 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2829 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2830 &ParamTy, Args, 1, CandidateSet);
2831 }
2832 break;
2833
2834 UnaryPlus:
2835 // C++ [over.built]p8:
2836 // For every type T, there exist candidate operator functions of
2837 // the form
2838 //
2839 // T* operator+(T*);
2840 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2841 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2842 QualType ParamTy = *Ptr;
2843 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2844 }
2845
2846 // Fall through
2847
2848 UnaryMinus:
2849 // C++ [over.built]p9:
2850 // For every promoted arithmetic type T, there exist candidate
2851 // operator functions of the form
2852 //
2853 // T operator+(T);
2854 // T operator-(T);
2855 for (unsigned Arith = FirstPromotedArithmeticType;
2856 Arith < LastPromotedArithmeticType; ++Arith) {
2857 QualType ArithTy = ArithmeticTypes[Arith];
2858 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2859 }
2860 break;
2861
2862 case OO_Tilde:
2863 // C++ [over.built]p10:
2864 // For every promoted integral type T, there exist candidate
2865 // operator functions of the form
2866 //
2867 // T operator~(T);
2868 for (unsigned Int = FirstPromotedIntegralType;
2869 Int < LastPromotedIntegralType; ++Int) {
2870 QualType IntTy = ArithmeticTypes[Int];
2871 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2872 }
2873 break;
2874
Douglas Gregor70d26122008-11-12 17:17:38 +00002875 case OO_New:
2876 case OO_Delete:
2877 case OO_Array_New:
2878 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00002879 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002880 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00002881 break;
2882
2883 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002884 UnaryAmp:
2885 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00002886 // C++ [over.match.oper]p3:
2887 // -- For the operator ',', the unary operator '&', or the
2888 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00002889 break;
2890
2891 case OO_Less:
2892 case OO_Greater:
2893 case OO_LessEqual:
2894 case OO_GreaterEqual:
2895 case OO_EqualEqual:
2896 case OO_ExclaimEqual:
2897 // C++ [over.built]p15:
2898 //
2899 // For every pointer or enumeration type T, there exist
2900 // candidate operator functions of the form
2901 //
2902 // bool operator<(T, T);
2903 // bool operator>(T, T);
2904 // bool operator<=(T, T);
2905 // bool operator>=(T, T);
2906 // bool operator==(T, T);
2907 // bool operator!=(T, T);
2908 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2909 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2910 QualType ParamTypes[2] = { *Ptr, *Ptr };
2911 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2912 }
2913 for (BuiltinCandidateTypeSet::iterator Enum
2914 = CandidateTypes.enumeration_begin();
2915 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2916 QualType ParamTypes[2] = { *Enum, *Enum };
2917 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2918 }
2919
2920 // Fall through.
2921 isComparison = true;
2922
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002923 BinaryPlus:
2924 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00002925 if (!isComparison) {
2926 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2927
2928 // C++ [over.built]p13:
2929 //
2930 // For every cv-qualified or cv-unqualified object type T
2931 // there exist candidate operator functions of the form
2932 //
2933 // T* operator+(T*, ptrdiff_t);
2934 // T& operator[](T*, ptrdiff_t); [BELOW]
2935 // T* operator-(T*, ptrdiff_t);
2936 // T* operator+(ptrdiff_t, T*);
2937 // T& operator[](ptrdiff_t, T*); [BELOW]
2938 //
2939 // C++ [over.built]p14:
2940 //
2941 // For every T, where T is a pointer to object type, there
2942 // exist candidate operator functions of the form
2943 //
2944 // ptrdiff_t operator-(T, T);
2945 for (BuiltinCandidateTypeSet::iterator Ptr
2946 = CandidateTypes.pointer_begin();
2947 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2948 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2949
2950 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2951 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2952
2953 if (Op == OO_Plus) {
2954 // T* operator+(ptrdiff_t, T*);
2955 ParamTypes[0] = ParamTypes[1];
2956 ParamTypes[1] = *Ptr;
2957 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2958 } else {
2959 // ptrdiff_t operator-(T, T);
2960 ParamTypes[1] = *Ptr;
2961 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2962 Args, 2, CandidateSet);
2963 }
2964 }
2965 }
2966 // Fall through
2967
Douglas Gregor70d26122008-11-12 17:17:38 +00002968 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002969 BinaryStar:
Douglas Gregor70d26122008-11-12 17:17:38 +00002970 // C++ [over.built]p12:
2971 //
2972 // For every pair of promoted arithmetic types L and R, there
2973 // exist candidate operator functions of the form
2974 //
2975 // LR operator*(L, R);
2976 // LR operator/(L, R);
2977 // LR operator+(L, R);
2978 // LR operator-(L, R);
2979 // bool operator<(L, R);
2980 // bool operator>(L, R);
2981 // bool operator<=(L, R);
2982 // bool operator>=(L, R);
2983 // bool operator==(L, R);
2984 // bool operator!=(L, R);
2985 //
2986 // where LR is the result of the usual arithmetic conversions
2987 // between types L and R.
2988 for (unsigned Left = FirstPromotedArithmeticType;
2989 Left < LastPromotedArithmeticType; ++Left) {
2990 for (unsigned Right = FirstPromotedArithmeticType;
2991 Right < LastPromotedArithmeticType; ++Right) {
2992 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2993 QualType Result
2994 = isComparison? Context.BoolTy
2995 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2996 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2997 }
2998 }
2999 break;
3000
3001 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003002 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003003 case OO_Caret:
3004 case OO_Pipe:
3005 case OO_LessLess:
3006 case OO_GreaterGreater:
3007 // C++ [over.built]p17:
3008 //
3009 // For every pair of promoted integral types L and R, there
3010 // exist candidate operator functions of the form
3011 //
3012 // LR operator%(L, R);
3013 // LR operator&(L, R);
3014 // LR operator^(L, R);
3015 // LR operator|(L, R);
3016 // L operator<<(L, R);
3017 // L operator>>(L, R);
3018 //
3019 // where LR is the result of the usual arithmetic conversions
3020 // between types L and R.
3021 for (unsigned Left = FirstPromotedIntegralType;
3022 Left < LastPromotedIntegralType; ++Left) {
3023 for (unsigned Right = FirstPromotedIntegralType;
3024 Right < LastPromotedIntegralType; ++Right) {
3025 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3026 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3027 ? LandR[0]
3028 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3029 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3030 }
3031 }
3032 break;
3033
3034 case OO_Equal:
3035 // C++ [over.built]p20:
3036 //
3037 // For every pair (T, VQ), where T is an enumeration or
3038 // (FIXME:) pointer to member type and VQ is either volatile or
3039 // empty, there exist candidate operator functions of the form
3040 //
3041 // VQ T& operator=(VQ T&, T);
3042 for (BuiltinCandidateTypeSet::iterator Enum
3043 = CandidateTypes.enumeration_begin();
3044 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3045 QualType ParamTypes[2];
3046
3047 // T& operator=(T&, T)
3048 ParamTypes[0] = Context.getReferenceType(*Enum);
3049 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003050 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003051 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003052
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003053 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3054 // volatile T& operator=(volatile T&, T)
3055 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
3056 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003057 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003058 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003059 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003060 }
3061 // Fall through.
3062
3063 case OO_PlusEqual:
3064 case OO_MinusEqual:
3065 // C++ [over.built]p19:
3066 //
3067 // For every pair (T, VQ), where T is any type and VQ is either
3068 // volatile or empty, there exist candidate operator functions
3069 // of the form
3070 //
3071 // T*VQ& operator=(T*VQ&, T*);
3072 //
3073 // C++ [over.built]p21:
3074 //
3075 // For every pair (T, VQ), where T is a cv-qualified or
3076 // cv-unqualified object type and VQ is either volatile or
3077 // empty, there exist candidate operator functions of the form
3078 //
3079 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3080 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3081 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3082 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3083 QualType ParamTypes[2];
3084 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3085
3086 // non-volatile version
3087 ParamTypes[0] = Context.getReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003088 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3089 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003090
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003091 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3092 // volatile version
3093 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003094 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3095 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003096 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003097 }
3098 // Fall through.
3099
3100 case OO_StarEqual:
3101 case OO_SlashEqual:
3102 // C++ [over.built]p18:
3103 //
3104 // For every triple (L, VQ, R), where L is an arithmetic type,
3105 // VQ is either volatile or empty, and R is a promoted
3106 // arithmetic type, there exist candidate operator functions of
3107 // the form
3108 //
3109 // VQ L& operator=(VQ L&, R);
3110 // VQ L& operator*=(VQ L&, R);
3111 // VQ L& operator/=(VQ L&, R);
3112 // VQ L& operator+=(VQ L&, R);
3113 // VQ L& operator-=(VQ L&, R);
3114 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3115 for (unsigned Right = FirstPromotedArithmeticType;
3116 Right < LastPromotedArithmeticType; ++Right) {
3117 QualType ParamTypes[2];
3118 ParamTypes[1] = ArithmeticTypes[Right];
3119
3120 // Add this built-in operator as a candidate (VQ is empty).
3121 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003122 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3123 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003124
3125 // Add this built-in operator as a candidate (VQ is 'volatile').
3126 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
3127 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003128 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3129 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003130 }
3131 }
3132 break;
3133
3134 case OO_PercentEqual:
3135 case OO_LessLessEqual:
3136 case OO_GreaterGreaterEqual:
3137 case OO_AmpEqual:
3138 case OO_CaretEqual:
3139 case OO_PipeEqual:
3140 // C++ [over.built]p22:
3141 //
3142 // For every triple (L, VQ, R), where L is an integral type, VQ
3143 // is either volatile or empty, and R is a promoted integral
3144 // type, there exist candidate operator functions of the form
3145 //
3146 // VQ L& operator%=(VQ L&, R);
3147 // VQ L& operator<<=(VQ L&, R);
3148 // VQ L& operator>>=(VQ L&, R);
3149 // VQ L& operator&=(VQ L&, R);
3150 // VQ L& operator^=(VQ L&, R);
3151 // VQ L& operator|=(VQ L&, R);
3152 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3153 for (unsigned Right = FirstPromotedIntegralType;
3154 Right < LastPromotedIntegralType; ++Right) {
3155 QualType ParamTypes[2];
3156 ParamTypes[1] = ArithmeticTypes[Right];
3157
3158 // Add this built-in operator as a candidate (VQ is empty).
Douglas Gregor70d26122008-11-12 17:17:38 +00003159 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
3160 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3161
3162 // Add this built-in operator as a candidate (VQ is 'volatile').
3163 ParamTypes[0] = ArithmeticTypes[Left];
3164 ParamTypes[0].addVolatile();
3165 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
3166 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3167 }
3168 }
3169 break;
3170
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003171 case OO_Exclaim: {
3172 // C++ [over.operator]p23:
3173 //
3174 // There also exist candidate operator functions of the form
3175 //
3176 // bool operator!(bool);
3177 // bool operator&&(bool, bool); [BELOW]
3178 // bool operator||(bool, bool); [BELOW]
3179 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003180 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3181 /*IsAssignmentOperator=*/false,
3182 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003183 break;
3184 }
3185
Douglas Gregor70d26122008-11-12 17:17:38 +00003186 case OO_AmpAmp:
3187 case OO_PipePipe: {
3188 // C++ [over.operator]p23:
3189 //
3190 // There also exist candidate operator functions of the form
3191 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003192 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003193 // bool operator&&(bool, bool);
3194 // bool operator||(bool, bool);
3195 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003196 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3197 /*IsAssignmentOperator=*/false,
3198 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003199 break;
3200 }
3201
3202 case OO_Subscript:
3203 // C++ [over.built]p13:
3204 //
3205 // For every cv-qualified or cv-unqualified object type T there
3206 // exist candidate operator functions of the form
3207 //
3208 // T* operator+(T*, ptrdiff_t); [ABOVE]
3209 // T& operator[](T*, ptrdiff_t);
3210 // T* operator-(T*, ptrdiff_t); [ABOVE]
3211 // T* operator+(ptrdiff_t, T*); [ABOVE]
3212 // T& operator[](ptrdiff_t, T*);
3213 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3214 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3215 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3216 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
3217 QualType ResultTy = Context.getReferenceType(PointeeType);
3218
3219 // T& operator[](T*, ptrdiff_t)
3220 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3221
3222 // T& operator[](ptrdiff_t, T*);
3223 ParamTypes[0] = ParamTypes[1];
3224 ParamTypes[1] = *Ptr;
3225 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3226 }
3227 break;
3228
3229 case OO_ArrowStar:
3230 // FIXME: No support for pointer-to-members yet.
3231 break;
3232 }
3233}
3234
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003235/// \brief Add function candidates found via argument-dependent lookup
3236/// to the set of overloading candidates.
3237///
3238/// This routine performs argument-dependent name lookup based on the
3239/// given function name (which may also be an operator name) and adds
3240/// all of the overload candidates found by ADL to the overload
3241/// candidate set (C++ [basic.lookup.argdep]).
3242void
3243Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3244 Expr **Args, unsigned NumArgs,
3245 OverloadCandidateSet& CandidateSet) {
3246 // Find all of the associated namespaces and classes based on the
3247 // arguments we have.
3248 AssociatedNamespaceSet AssociatedNamespaces;
3249 AssociatedClassSet AssociatedClasses;
3250 FindAssociatedClassesAndNamespaces(Args, NumArgs,
3251 AssociatedNamespaces, AssociatedClasses);
3252
3253 // C++ [basic.lookup.argdep]p3:
3254 //
3255 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3256 // and let Y be the lookup set produced by argument dependent
3257 // lookup (defined as follows). If X contains [...] then Y is
3258 // empty. Otherwise Y is the set of declarations found in the
3259 // namespaces associated with the argument types as described
3260 // below. The set of declarations found by the lookup of the name
3261 // is the union of X and Y.
3262 //
3263 // Here, we compute Y and add its members to the overloaded
3264 // candidate set.
3265 llvm::SmallPtrSet<FunctionDecl *, 16> KnownCandidates;
3266 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
3267 NSEnd = AssociatedNamespaces.end();
3268 NS != NSEnd; ++NS) {
3269 // When considering an associated namespace, the lookup is the
3270 // same as the lookup performed when the associated namespace is
3271 // used as a qualifier (3.4.3.2) except that:
3272 //
3273 // -- Any using-directives in the associated namespace are
3274 // ignored.
3275 //
3276 // -- FIXME: Any namespace-scope friend functions declared in
3277 // associated classes are visible within their respective
3278 // namespaces even if they are not visible during an ordinary
3279 // lookup (11.4).
3280 DeclContext::lookup_iterator I, E;
3281 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
3282 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
3283 if (!Func)
3284 break;
3285
3286 if (KnownCandidates.empty()) {
3287 // Record all of the function candidates that we've already
3288 // added to the overload set, so that we don't add those same
3289 // candidates a second time.
3290 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3291 CandEnd = CandidateSet.end();
3292 Cand != CandEnd; ++Cand)
3293 KnownCandidates.insert(Cand->Function);
3294 }
3295
3296 // If we haven't seen this function before, add it as a
3297 // candidate.
3298 if (KnownCandidates.insert(Func))
3299 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3300 }
3301 }
3302}
3303
Douglas Gregord2baafd2008-10-21 16:13:35 +00003304/// isBetterOverloadCandidate - Determines whether the first overload
3305/// candidate is a better candidate than the second (C++ 13.3.3p1).
3306bool
3307Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3308 const OverloadCandidate& Cand2)
3309{
3310 // Define viable functions to be better candidates than non-viable
3311 // functions.
3312 if (!Cand2.Viable)
3313 return Cand1.Viable;
3314 else if (!Cand1.Viable)
3315 return false;
3316
Douglas Gregor3257fb52008-12-22 05:46:06 +00003317 // C++ [over.match.best]p1:
3318 //
3319 // -- if F is a static member function, ICS1(F) is defined such
3320 // that ICS1(F) is neither better nor worse than ICS1(G) for
3321 // any function G, and, symmetrically, ICS1(G) is neither
3322 // better nor worse than ICS1(F).
3323 unsigned StartArg = 0;
3324 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3325 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003326
3327 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3328 // function than another viable function F2 if for all arguments i,
3329 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3330 // then...
3331 unsigned NumArgs = Cand1.Conversions.size();
3332 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3333 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003334 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003335 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3336 Cand2.Conversions[ArgIdx])) {
3337 case ImplicitConversionSequence::Better:
3338 // Cand1 has a better conversion sequence.
3339 HasBetterConversion = true;
3340 break;
3341
3342 case ImplicitConversionSequence::Worse:
3343 // Cand1 can't be better than Cand2.
3344 return false;
3345
3346 case ImplicitConversionSequence::Indistinguishable:
3347 // Do nothing.
3348 break;
3349 }
3350 }
3351
3352 if (HasBetterConversion)
3353 return true;
3354
Douglas Gregor70d26122008-11-12 17:17:38 +00003355 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3356 // implemented, but they require template support.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003357
Douglas Gregor60714f92008-11-07 22:36:19 +00003358 // C++ [over.match.best]p1b4:
3359 //
3360 // -- the context is an initialization by user-defined conversion
3361 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3362 // from the return type of F1 to the destination type (i.e.,
3363 // the type of the entity being initialized) is a better
3364 // conversion sequence than the standard conversion sequence
3365 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003366 if (Cand1.Function && Cand2.Function &&
3367 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003368 isa<CXXConversionDecl>(Cand2.Function)) {
3369 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3370 Cand2.FinalConversion)) {
3371 case ImplicitConversionSequence::Better:
3372 // Cand1 has a better conversion sequence.
3373 return true;
3374
3375 case ImplicitConversionSequence::Worse:
3376 // Cand1 can't be better than Cand2.
3377 return false;
3378
3379 case ImplicitConversionSequence::Indistinguishable:
3380 // Do nothing
3381 break;
3382 }
3383 }
3384
Douglas Gregord2baafd2008-10-21 16:13:35 +00003385 return false;
3386}
3387
3388/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3389/// within an overload candidate set. If overloading is successful,
3390/// the result will be OR_Success and Best will be set to point to the
3391/// best viable function within the candidate set. Otherwise, one of
3392/// several kinds of errors will be returned; see
3393/// Sema::OverloadingResult.
3394Sema::OverloadingResult
3395Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3396 OverloadCandidateSet::iterator& Best)
3397{
3398 // Find the best viable function.
3399 Best = CandidateSet.end();
3400 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3401 Cand != CandidateSet.end(); ++Cand) {
3402 if (Cand->Viable) {
3403 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3404 Best = Cand;
3405 }
3406 }
3407
3408 // If we didn't find any viable functions, abort.
3409 if (Best == CandidateSet.end())
3410 return OR_No_Viable_Function;
3411
3412 // Make sure that this function is better than every other viable
3413 // function. If not, we have an ambiguity.
3414 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3415 Cand != CandidateSet.end(); ++Cand) {
3416 if (Cand->Viable &&
3417 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003418 !isBetterOverloadCandidate(*Best, *Cand)) {
3419 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003420 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003421 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003422 }
3423
3424 // Best is the best viable function.
3425 return OR_Success;
3426}
3427
3428/// PrintOverloadCandidates - When overload resolution fails, prints
3429/// diagnostic messages containing the candidates in the candidate
3430/// set. If OnlyViable is true, only viable candidates will be printed.
3431void
3432Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3433 bool OnlyViable)
3434{
3435 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3436 LastCand = CandidateSet.end();
3437 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003438 if (Cand->Viable || !OnlyViable) {
3439 if (Cand->Function) {
3440 // Normal function
3441 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003442 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003443 // Desugar the type of the surrogate down to a function type,
3444 // retaining as many typedefs as possible while still showing
3445 // the function type (and, therefore, its parameter types).
3446 QualType FnType = Cand->Surrogate->getConversionType();
3447 bool isReference = false;
3448 bool isPointer = false;
3449 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
3450 FnType = FnTypeRef->getPointeeType();
3451 isReference = true;
3452 }
3453 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3454 FnType = FnTypePtr->getPointeeType();
3455 isPointer = true;
3456 }
3457 // Desugar down to a function type.
3458 FnType = QualType(FnType->getAsFunctionType(), 0);
3459 // Reconstruct the pointer/reference as appropriate.
3460 if (isPointer) FnType = Context.getPointerType(FnType);
3461 if (isReference) FnType = Context.getReferenceType(FnType);
3462
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003463 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003464 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003465 } else {
3466 // FIXME: We need to get the identifier in here
3467 // FIXME: Do we want the error message to point at the
3468 // operator? (built-ins won't have a location)
3469 QualType FnType
3470 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3471 Cand->BuiltinTypes.ParamTypes,
3472 Cand->Conversions.size(),
3473 false, 0);
3474
Chris Lattner4bfd2232008-11-24 06:25:27 +00003475 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003476 }
3477 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003478 }
3479}
3480
Douglas Gregor45014fd2008-11-10 20:40:00 +00003481/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3482/// an overloaded function (C++ [over.over]), where @p From is an
3483/// expression with overloaded function type and @p ToType is the type
3484/// we're trying to resolve to. For example:
3485///
3486/// @code
3487/// int f(double);
3488/// int f(int);
3489///
3490/// int (*pfd)(double) = f; // selects f(double)
3491/// @endcode
3492///
3493/// This routine returns the resulting FunctionDecl if it could be
3494/// resolved, and NULL otherwise. When @p Complain is true, this
3495/// routine will emit diagnostics if there is an error.
3496FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003497Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003498 bool Complain) {
3499 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003500 bool IsMember = false;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003501 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3502 FunctionType = ToTypePtr->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003503 else if (const MemberPointerType *MemTypePtr =
3504 ToType->getAsMemberPointerType()) {
3505 FunctionType = MemTypePtr->getPointeeType();
3506 IsMember = true;
3507 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003508
3509 // We only look at pointers or references to functions.
3510 if (!FunctionType->isFunctionType())
3511 return 0;
3512
3513 // Find the actual overloaded function declaration.
3514 OverloadedFunctionDecl *Ovl = 0;
3515
3516 // C++ [over.over]p1:
3517 // [...] [Note: any redundant set of parentheses surrounding the
3518 // overloaded function name is ignored (5.1). ]
3519 Expr *OvlExpr = From->IgnoreParens();
3520
3521 // C++ [over.over]p1:
3522 // [...] The overloaded function name can be preceded by the &
3523 // operator.
3524 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3525 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3526 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3527 }
3528
3529 // Try to dig out the overloaded function.
3530 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3531 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3532
3533 // If there's no overloaded function declaration, we're done.
3534 if (!Ovl)
3535 return 0;
3536
3537 // Look through all of the overloaded functions, searching for one
3538 // whose type matches exactly.
3539 // FIXME: When templates or using declarations come along, we'll actually
3540 // have to deal with duplicates, partial ordering, etc. For now, we
3541 // can just do a simple search.
3542 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3543 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3544 Fun != Ovl->function_end(); ++Fun) {
3545 // C++ [over.over]p3:
3546 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003547 // targets of type "pointer-to-function" or "reference-to-function."
3548 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003549 // type "pointer-to-member-function."
3550 // Note that according to DR 247, the containing class does not matter.
3551 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3552 // Skip non-static functions when converting to pointer, and static
3553 // when converting to member pointer.
3554 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003555 continue;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003556 } else if (IsMember)
3557 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003558
3559 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3560 return *Fun;
3561 }
3562
3563 return 0;
3564}
3565
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003566/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003567/// (which eventually refers to the declaration Func) and the call
3568/// arguments Args/NumArgs, attempt to resolve the function call down
3569/// to a specific function. If overload resolution succeeds, returns
3570/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003571/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003572/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003573FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003574 DeclarationName UnqualifiedName,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003575 SourceLocation LParenLoc,
3576 Expr **Args, unsigned NumArgs,
3577 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003578 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003579 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003580 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003581
3582 // Add the functions denoted by Callee to the set of candidate
3583 // functions. While we're doing so, track whether argument-dependent
3584 // lookup still applies, per:
3585 //
3586 // C++0x [basic.lookup.argdep]p3:
3587 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3588 // and let Y be the lookup set produced by argument dependent
3589 // lookup (defined as follows). If X contains
3590 //
3591 // -- a declaration of a class member, or
3592 //
3593 // -- a block-scope function declaration that is not a
3594 // using-declaration, or
3595 //
3596 // -- a declaration that is neither a function or a function
3597 // template
3598 //
3599 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003600 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003601 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3602 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3603 FuncEnd = Ovl->function_end();
3604 Func != FuncEnd; ++Func) {
3605 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3606
3607 if ((*Func)->getDeclContext()->isRecord() ||
3608 (*Func)->getDeclContext()->isFunctionOrMethod())
3609 ArgumentDependentLookup = false;
3610 }
3611 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3612 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3613
3614 if (Func->getDeclContext()->isRecord() ||
3615 Func->getDeclContext()->isFunctionOrMethod())
3616 ArgumentDependentLookup = false;
3617 }
3618
3619 if (Callee)
3620 UnqualifiedName = Callee->getDeclName();
3621
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003622 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003623 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003624 CandidateSet);
3625
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003626 OverloadCandidateSet::iterator Best;
3627 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003628 case OR_Success:
3629 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003630
3631 case OR_No_Viable_Function:
3632 Diag(Fn->getSourceRange().getBegin(),
3633 diag::err_ovl_no_viable_function_in_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003634 << UnqualifiedName << (unsigned)CandidateSet.size()
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003635 << Fn->getSourceRange();
3636 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3637 break;
3638
3639 case OR_Ambiguous:
3640 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003641 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003642 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3643 break;
3644 }
3645
3646 // Overload resolution failed. Destroy all of the subexpressions and
3647 // return NULL.
3648 Fn->Destroy(Context);
3649 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3650 Args[Arg]->Destroy(Context);
3651 return 0;
3652}
3653
Douglas Gregor3257fb52008-12-22 05:46:06 +00003654/// BuildCallToMemberFunction - Build a call to a member
3655/// function. MemExpr is the expression that refers to the member
3656/// function (and includes the object parameter), Args/NumArgs are the
3657/// arguments to the function call (not including the object
3658/// parameter). The caller needs to validate that the member
3659/// expression refers to a member function or an overloaded member
3660/// function.
3661Sema::ExprResult
3662Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3663 SourceLocation LParenLoc, Expr **Args,
3664 unsigned NumArgs, SourceLocation *CommaLocs,
3665 SourceLocation RParenLoc) {
3666 // Dig out the member expression. This holds both the object
3667 // argument and the member function we're referring to.
3668 MemberExpr *MemExpr = 0;
3669 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3670 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3671 else
3672 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3673 assert(MemExpr && "Building member call without member expression");
3674
3675 // Extract the object argument.
3676 Expr *ObjectArg = MemExpr->getBase();
3677 if (MemExpr->isArrow())
Ted Kremenek0c97e042009-02-07 01:47:29 +00003678 ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref,
3679 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
3680 SourceLocation());
Douglas Gregor3257fb52008-12-22 05:46:06 +00003681 CXXMethodDecl *Method = 0;
3682 if (OverloadedFunctionDecl *Ovl
3683 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3684 // Add overload candidates
3685 OverloadCandidateSet CandidateSet;
3686 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3687 FuncEnd = Ovl->function_end();
3688 Func != FuncEnd; ++Func) {
3689 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3690 Method = cast<CXXMethodDecl>(*Func);
3691 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3692 /*SuppressUserConversions=*/false);
3693 }
3694
3695 OverloadCandidateSet::iterator Best;
3696 switch (BestViableFunction(CandidateSet, Best)) {
3697 case OR_Success:
3698 Method = cast<CXXMethodDecl>(Best->Function);
3699 break;
3700
3701 case OR_No_Viable_Function:
3702 Diag(MemExpr->getSourceRange().getBegin(),
3703 diag::err_ovl_no_viable_member_function_in_call)
3704 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3705 << MemExprE->getSourceRange();
3706 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3707 // FIXME: Leaking incoming expressions!
3708 return true;
3709
3710 case OR_Ambiguous:
3711 Diag(MemExpr->getSourceRange().getBegin(),
3712 diag::err_ovl_ambiguous_member_call)
3713 << Ovl->getDeclName() << MemExprE->getSourceRange();
3714 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3715 // FIXME: Leaking incoming expressions!
3716 return true;
3717 }
3718
3719 FixOverloadedFunctionReference(MemExpr, Method);
3720 } else {
3721 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3722 }
3723
3724 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00003725 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00003726 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
3727 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00003728 Method->getResultType().getNonReferenceType(),
3729 RParenLoc));
3730
3731 // Convert the object argument (for a non-static member function call).
3732 if (!Method->isStatic() &&
3733 PerformObjectArgumentInitialization(ObjectArg, Method))
3734 return true;
3735 MemExpr->setBase(ObjectArg);
3736
3737 // Convert the rest of the arguments
3738 const FunctionTypeProto *Proto = cast<FunctionTypeProto>(Method->getType());
3739 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
3740 RParenLoc))
3741 return true;
3742
Sebastian Redl8b769972009-01-19 00:08:26 +00003743 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00003744}
3745
Douglas Gregor10f3c502008-11-19 21:05:33 +00003746/// BuildCallToObjectOfClassType - Build a call to an object of class
3747/// type (C++ [over.call.object]), which can end up invoking an
3748/// overloaded function call operator (@c operator()) or performing a
3749/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00003750Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00003751Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3752 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00003753 Expr **Args, unsigned NumArgs,
3754 SourceLocation *CommaLocs,
3755 SourceLocation RParenLoc) {
3756 assert(Object->getType()->isRecordType() && "Requires object type argument");
3757 const RecordType *Record = Object->getType()->getAsRecordType();
3758
3759 // C++ [over.call.object]p1:
3760 // If the primary-expression E in the function call syntax
3761 // evaluates to a class object of type “cv T”, then the set of
3762 // candidate functions includes at least the function call
3763 // operators of T. The function call operators of T are obtained by
3764 // ordinary lookup of the name operator() in the context of
3765 // (E).operator().
3766 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003767 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003768 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00003769 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003770 Oper != OperEnd; ++Oper)
3771 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
3772 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003773
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003774 // C++ [over.call.object]p2:
3775 // In addition, for each conversion function declared in T of the
3776 // form
3777 //
3778 // operator conversion-type-id () cv-qualifier;
3779 //
3780 // where cv-qualifier is the same cv-qualification as, or a
3781 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00003782 // denotes the type "pointer to function of (P1,...,Pn) returning
3783 // R", or the type "reference to pointer to function of
3784 // (P1,...,Pn) returning R", or the type "reference to function
3785 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003786 // is also considered as a candidate function. Similarly,
3787 // surrogate call functions are added to the set of candidate
3788 // functions for each conversion function declared in an
3789 // accessible base class provided the function is not hidden
3790 // within T by another intervening declaration.
3791 //
3792 // FIXME: Look in base classes for more conversion operators!
3793 OverloadedFunctionDecl *Conversions
3794 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003795 for (OverloadedFunctionDecl::function_iterator
3796 Func = Conversions->function_begin(),
3797 FuncEnd = Conversions->function_end();
3798 Func != FuncEnd; ++Func) {
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003799 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3800
3801 // Strip the reference type (if any) and then the pointer type (if
3802 // any) to get down to what might be a function type.
3803 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3804 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3805 ConvType = ConvPtrType->getPointeeType();
3806
3807 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3808 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3809 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00003810
3811 // Perform overload resolution.
3812 OverloadCandidateSet::iterator Best;
3813 switch (BestViableFunction(CandidateSet, Best)) {
3814 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003815 // Overload resolution succeeded; we'll build the appropriate call
3816 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00003817 break;
3818
3819 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00003820 Diag(Object->getSourceRange().getBegin(),
3821 diag::err_ovl_no_viable_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003822 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00003823 << Object->getSourceRange();
3824 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003825 break;
3826
3827 case OR_Ambiguous:
3828 Diag(Object->getSourceRange().getBegin(),
3829 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003830 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00003831 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3832 break;
3833 }
3834
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003835 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00003836 // We had an error; delete all of the subexpressions and return
3837 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003838 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003839 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00003840 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003841 return true;
3842 }
3843
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003844 if (Best->Function == 0) {
3845 // Since there is no function declaration, this is one of the
3846 // surrogate candidates. Dig out the conversion function.
3847 CXXConversionDecl *Conv
3848 = cast<CXXConversionDecl>(
3849 Best->Conversions[0].UserDefined.ConversionFunction);
3850
3851 // We selected one of the surrogate functions that converts the
3852 // object parameter to a function pointer. Perform the conversion
3853 // on the object argument, then let ActOnCallExpr finish the job.
3854 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00003855 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003856 Conv->getConversionType().getNonReferenceType(),
3857 Conv->getConversionType()->isReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00003858 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
3859 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
3860 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003861 }
3862
3863 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3864 // that calls this method, using Object for the implicit object
3865 // parameter and passing along the remaining arguments.
3866 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003867 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3868
3869 unsigned NumArgsInProto = Proto->getNumArgs();
3870 unsigned NumArgsToCheck = NumArgs;
3871
3872 // Build the full argument list for the method call (the
3873 // implicit object parameter is placed at the beginning of the
3874 // list).
3875 Expr **MethodArgs;
3876 if (NumArgs < NumArgsInProto) {
3877 NumArgsToCheck = NumArgsInProto;
3878 MethodArgs = new Expr*[NumArgsInProto + 1];
3879 } else {
3880 MethodArgs = new Expr*[NumArgs + 1];
3881 }
3882 MethodArgs[0] = Object;
3883 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3884 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3885
Ted Kremenek0c97e042009-02-07 01:47:29 +00003886 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
3887 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00003888 UsualUnaryConversions(NewFn);
3889
3890 // Once we've built TheCall, all of the expressions are properly
3891 // owned.
3892 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00003893 ExprOwningPtr<CXXOperatorCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00003894 TheCall(this, new (Context) CXXOperatorCallExpr(Context, NewFn, MethodArgs,
Ted Kremenek0c97e042009-02-07 01:47:29 +00003895 NumArgs + 1,
3896 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00003897 delete [] MethodArgs;
3898
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003899 // We may have default arguments. If so, we need to allocate more
3900 // slots in the call for them.
3901 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00003902 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003903 else if (NumArgs > NumArgsInProto)
3904 NumArgsToCheck = NumArgsInProto;
3905
Douglas Gregor10f3c502008-11-19 21:05:33 +00003906 // Initialize the implicit object parameter.
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003907 if (PerformObjectArgumentInitialization(Object, Method))
Douglas Gregor10f3c502008-11-19 21:05:33 +00003908 return true;
3909 TheCall->setArg(0, Object);
3910
3911 // Check the argument types.
3912 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00003913 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003914 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00003915 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003916
3917 // Pass the argument.
3918 QualType ProtoArgType = Proto->getArgType(i);
3919 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3920 return true;
3921 } else {
Ted Kremenek0c97e042009-02-07 01:47:29 +00003922 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003923 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00003924
3925 TheCall->setArg(i + 1, Arg);
3926 }
3927
3928 // If this is a variadic call, handle args passed through "...".
3929 if (Proto->isVariadic()) {
3930 // Promote the arguments (C99 6.5.2.2p7).
3931 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3932 Expr *Arg = Args[i];
Anders Carlssonfde627e2009-01-13 05:48:52 +00003933
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00003934 DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003935 TheCall->setArg(i + 1, Arg);
3936 }
3937 }
3938
Sebastian Redl8b769972009-01-19 00:08:26 +00003939 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00003940}
3941
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003942/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3943/// (if one exists), where @c Base is an expression of class type and
3944/// @c Member is the name of the member we're trying to find.
3945Action::ExprResult
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003946Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003947 SourceLocation MemberLoc,
3948 IdentifierInfo &Member) {
3949 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3950
3951 // C++ [over.ref]p1:
3952 //
3953 // [...] An expression x->m is interpreted as (x.operator->())->m
3954 // for a class object x of type T if T::operator->() exists and if
3955 // the operator is selected as the best match function by the
3956 // overload resolution mechanism (13.3).
3957 // FIXME: look in base classes.
3958 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3959 OverloadCandidateSet CandidateSet;
3960 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003961
3962 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00003963 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003964 Oper != OperEnd; ++Oper)
3965 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003966 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003967
Ted Kremenek0c97e042009-02-07 01:47:29 +00003968 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregor9c690e92008-11-21 03:04:22 +00003969
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003970 // Perform overload resolution.
3971 OverloadCandidateSet::iterator Best;
3972 switch (BestViableFunction(CandidateSet, Best)) {
3973 case OR_Success:
3974 // Overload resolution succeeded; we'll build the call below.
3975 break;
3976
3977 case OR_No_Viable_Function:
3978 if (CandidateSet.empty())
3979 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003980 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003981 else
3982 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00003983 << "operator->" << (unsigned)CandidateSet.size()
3984 << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003985 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003986 return true;
3987
3988 case OR_Ambiguous:
3989 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003990 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003991 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003992 return true;
3993 }
3994
3995 // Convert the object parameter.
3996 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00003997 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003998 return true;
Douglas Gregor9c690e92008-11-21 03:04:22 +00003999
4000 // No concerns about early exits now.
4001 BasePtr.take();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004002
4003 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004004 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4005 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004006 UsualUnaryConversions(FnExpr);
Ted Kremenek362abcd2009-02-09 20:51:47 +00004007 Base = new (Context) CXXOperatorCallExpr(Context, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004008 Method->getResultType().getNonReferenceType(),
4009 OpLoc);
Sebastian Redl8b769972009-01-19 00:08:26 +00004010 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
4011 MemberLoc, Member).release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004012}
4013
Douglas Gregor45014fd2008-11-10 20:40:00 +00004014/// FixOverloadedFunctionReference - E is an expression that refers to
4015/// a C++ overloaded function (possibly with some parentheses and
4016/// perhaps a '&' around it). We have resolved the overloaded function
4017/// to the function declaration Fn, so patch up the expression E to
4018/// refer (possibly indirectly) to Fn.
4019void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4020 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4021 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4022 E->setType(PE->getSubExpr()->getType());
4023 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4024 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4025 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004026 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4027 if (Method->isStatic()) {
4028 // Do nothing: static member functions aren't any different
4029 // from non-member functions.
4030 }
4031 else if (QualifiedDeclRefExpr *DRE
4032 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4033 // We have taken the address of a pointer to member
4034 // function. Perform the computation here so that we get the
4035 // appropriate pointer to member type.
4036 DRE->setDecl(Fn);
4037 DRE->setType(Fn->getType());
4038 QualType ClassType
4039 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4040 E->setType(Context.getMemberPointerType(Fn->getType(),
4041 ClassType.getTypePtr()));
4042 return;
4043 }
4044 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004045 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004046 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004047 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4048 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4049 "Expected overloaded function");
4050 DR->setDecl(Fn);
4051 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004052 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4053 MemExpr->setMemberDecl(Fn);
4054 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004055 } else {
4056 assert(false && "Invalid reference to overloaded function");
4057 }
4058}
4059
Douglas Gregord2baafd2008-10-21 16:13:35 +00004060} // end namespace clang