blob: ab66939656ec879ee014bddceceb2d4f516e957c [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;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +0000119 RRefBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000120 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000121}
122
Douglas Gregord2baafd2008-10-21 16:13:35 +0000123/// getRank - Retrieve the rank of this standard conversion sequence
124/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
125/// implicit conversions.
126ImplicitConversionRank StandardConversionSequence::getRank() const {
127 ImplicitConversionRank Rank = ICR_Exact_Match;
128 if (GetConversionRank(First) > Rank)
129 Rank = GetConversionRank(First);
130 if (GetConversionRank(Second) > Rank)
131 Rank = GetConversionRank(Second);
132 if (GetConversionRank(Third) > Rank)
133 Rank = GetConversionRank(Third);
134 return Rank;
135}
136
137/// isPointerConversionToBool - Determines whether this conversion is
138/// a conversion of a pointer or pointer-to-member to bool. This is
139/// used as part of the ranking of standard conversion sequences
140/// (C++ 13.3.3.2p4).
141bool StandardConversionSequence::isPointerConversionToBool() const
142{
143 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
144 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
145
146 // Note that FromType has not necessarily been transformed by the
147 // array-to-pointer or function-to-pointer implicit conversions, so
148 // check for their presence as well as checking whether FromType is
149 // a pointer.
150 if (ToType->isBooleanType() &&
Douglas Gregor80402cf2008-12-23 00:53:59 +0000151 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000152 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
153 return true;
154
155 return false;
156}
157
Douglas Gregor14046502008-10-23 00:40:37 +0000158/// isPointerConversionToVoidPointer - Determines whether this
159/// conversion is a conversion of a pointer to a void pointer. This is
160/// used as part of the ranking of standard conversion sequences (C++
161/// 13.3.3.2p4).
162bool
163StandardConversionSequence::
164isPointerConversionToVoidPointer(ASTContext& Context) const
165{
166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
176 if (const PointerType* ToPtrType = ToType->getAsPointerType())
177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregord2baafd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
263// FunctionDecl that New cannot be overloaded with.
264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
272// so IsOverload will not be used.
273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl)
288{
289 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
290 // Is this new function an overload of every function in the
291 // overload set?
292 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
293 FuncEnd = Ovl->function_end();
294 for (; Func != FuncEnd; ++Func) {
295 if (!IsOverload(New, *Func, MatchedDecl)) {
296 MatchedDecl = Func;
297 return false;
298 }
299 }
300
301 // This function overloads every function in the overload set.
302 return true;
303 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
304 // Is the function New an overload of the function Old?
305 QualType OldQType = Context.getCanonicalType(Old->getType());
306 QualType NewQType = Context.getCanonicalType(New->getType());
307
308 // Compare the signatures (C++ 1.3.10) of the two functions to
309 // determine whether they are overloads. If we find any mismatch
310 // in the signature, they are overloads.
311
312 // If either of these functions is a K&R-style function (no
313 // prototype), then we consider them to have matching signatures.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000314 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
315 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000316 return false;
317
Douglas Gregor4fa58902009-02-26 23:50:07 +0000318 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType.getTypePtr());
319 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType.getTypePtr());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000320
321 // The signature of a function includes the types of its
322 // parameters (C++ 1.3.10), which includes the presence or absence
323 // of the ellipsis; see C++ DR 357).
324 if (OldQType != NewQType &&
325 (OldType->getNumArgs() != NewType->getNumArgs() ||
326 OldType->isVariadic() != NewType->isVariadic() ||
327 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
328 NewType->arg_type_begin())))
329 return true;
330
331 // If the function is a class member, its signature includes the
332 // cv-qualifiers (if any) on the function itself.
333 //
334 // As part of this, also check whether one of the member functions
335 // is static, in which case they are not overloads (C++
336 // 13.1p2). While not part of the definition of the signature,
337 // this check is important to determine whether these functions
338 // can be overloaded.
339 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
340 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
341 if (OldMethod && NewMethod &&
342 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000343 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000344 return true;
345
346 // The signatures match; this is not an overload.
347 return false;
348 } else {
349 // (C++ 13p1):
350 // Only function declarations can be overloaded; object and type
351 // declarations cannot be overloaded.
352 return false;
353 }
354}
355
Douglas Gregor81c29152008-10-29 00:13:59 +0000356/// TryImplicitConversion - Attempt to perform an implicit conversion
357/// from the given expression (Expr) to the given type (ToType). This
358/// function returns an implicit conversion sequence that can be used
359/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000360///
361/// void f(float f);
362/// void g(int i) { f(i); }
363///
364/// this routine would produce an implicit conversion sequence to
365/// describe the initialization of f from i, which will be a standard
366/// conversion sequence containing an lvalue-to-rvalue conversion (C++
367/// 4.1) followed by a floating-integral conversion (C++ 4.9).
368//
369/// Note that this routine only determines how the conversion can be
370/// performed; it does not actually perform the conversion. As such,
371/// it will not produce any diagnostics if no conversion is available,
372/// but will instead return an implicit conversion sequence of kind
373/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000374///
375/// If @p SuppressUserConversions, then user-defined conversions are
376/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000377/// If @p AllowExplicit, then explicit user-defined conversions are
378/// permitted.
Sebastian Redla55834a2009-04-12 17:16:29 +0000379/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
380/// no matter its actual lvalueness.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000381ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000382Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000383 bool SuppressUserConversions,
Sebastian Redla55834a2009-04-12 17:16:29 +0000384 bool AllowExplicit, bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000385{
386 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000387 if (IsStandardConversion(From, ToType, ICS.Standard))
388 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000389 else if (getLangOptions().CPlusPlus &&
390 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redla55834a2009-04-12 17:16:29 +0000391 !SuppressUserConversions, AllowExplicit,
392 ForceRValue)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000393 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000394 // C++ [over.ics.user]p4:
395 // A conversion of an expression of class type to the same class
396 // type is given Exact Match rank, and a conversion of an
397 // expression of class type to a base class of that type is
398 // given Conversion rank, in spite of the fact that a copy
399 // constructor (i.e., a user-defined conversion function) is
400 // called for those cases.
401 if (CXXConstructorDecl *Constructor
402 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregord9176392009-02-02 22:11:10 +0000403 QualType FromCanon
404 = Context.getCanonicalType(From->getType().getUnqualifiedType());
405 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
406 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000407 // Turn this into a "standard" conversion sequence, so that it
408 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000409 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
410 ICS.Standard.setAsIdentityConversion();
411 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
412 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000413 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000414 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000415 ICS.Standard.Second = ICK_Derived_To_Base;
416 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000417 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000418
419 // C++ [over.best.ics]p4:
420 // However, when considering the argument of a user-defined
421 // conversion function that is a candidate by 13.3.1.3 when
422 // invoked for the copying of the temporary in the second step
423 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
424 // 13.3.1.6 in all cases, only standard conversion sequences and
425 // ellipsis conversion sequences are allowed.
426 if (SuppressUserConversions &&
427 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
428 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000429 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000430 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000431
432 return ICS;
433}
434
435/// IsStandardConversion - Determines whether there is a standard
436/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
437/// expression From to the type ToType. Standard conversion sequences
438/// only consider non-class types; for conversions that involve class
439/// types, use TryImplicitConversion. If a conversion exists, SCS will
440/// contain the standard conversion sequence required to perform this
441/// conversion and this routine will return true. Otherwise, this
442/// routine will return false and the value of SCS is unspecified.
443bool
444Sema::IsStandardConversion(Expr* From, QualType ToType,
445 StandardConversionSequence &SCS)
446{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000447 QualType FromType = From->getType();
448
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000449 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000450 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000451 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000452 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000453 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000454 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000455
Douglas Gregorfcb19192009-02-11 23:02:49 +0000456 // There are no standard conversions for class types in C++, so
457 // abort early. When overloading in C, however, we do permit
458 if (FromType->isRecordType() || ToType->isRecordType()) {
459 if (getLangOptions().CPlusPlus)
460 return false;
461
462 // When we're overloading in C, we allow, as standard conversions,
463 }
464
Douglas Gregord2baafd2008-10-21 16:13:35 +0000465 // The first conversion can be an lvalue-to-rvalue conversion,
466 // array-to-pointer conversion, or function-to-pointer conversion
467 // (C++ 4p1).
468
469 // Lvalue-to-rvalue conversion (C++ 4.1):
470 // An lvalue (3.10) of a non-function, non-array type T can be
471 // converted to an rvalue.
472 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
473 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000474 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000475 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000476 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000477
478 // If T is a non-class type, the type of the rvalue is the
479 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000480 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
481 // just strip the qualifiers because they don't matter.
482
483 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000484 FromType = FromType.getUnqualifiedType();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000485 }
486 // Array-to-pointer conversion (C++ 4.2)
487 else if (FromType->isArrayType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000488 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000489
490 // An lvalue or rvalue of type "array of N T" or "array of unknown
491 // bound of T" can be converted to an rvalue of type "pointer to
492 // T" (C++ 4.2p1).
493 FromType = Context.getArrayDecayedType(FromType);
494
495 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
496 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000497 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000498
499 // For the purpose of ranking in overload resolution
500 // (13.3.3.1.1), this conversion is considered an
501 // array-to-pointer conversion followed by a qualification
502 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000503 SCS.Second = ICK_Identity;
504 SCS.Third = ICK_Qualification;
505 SCS.ToTypePtr = ToType.getAsOpaquePtr();
506 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000507 }
508 }
509 // Function-to-pointer conversion (C++ 4.3).
510 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000511 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000512
513 // An lvalue of function type T can be converted to an rvalue of
514 // type "pointer to T." The result is a pointer to the
515 // function. (C++ 4.3p1).
516 FromType = Context.getPointerType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000517 }
Douglas Gregor45014fd2008-11-10 20:40:00 +0000518 // Address of overloaded function (C++ [over.over]).
519 else if (FunctionDecl *Fn
520 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
521 SCS.First = ICK_Function_To_Pointer;
522
523 // We were able to resolve the address of the overloaded function,
524 // so we can convert to the type of that function.
525 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000526 if (ToType->isLValueReferenceType())
527 FromType = Context.getLValueReferenceType(FromType);
528 else if (ToType->isRValueReferenceType())
529 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000530 else if (ToType->isMemberPointerType()) {
531 // Resolve address only succeeds if both sides are member pointers,
532 // but it doesn't have to be the same class. See DR 247.
533 // Note that this means that the type of &Derived::fn can be
534 // Ret (Base::*)(Args) if the fn overload actually found is from the
535 // base class, even if it was brought into the derived class via a
536 // using declaration. The standard isn't clear on this issue at all.
537 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
538 FromType = Context.getMemberPointerType(FromType,
539 Context.getTypeDeclType(M->getParent()).getTypePtr());
540 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000541 FromType = Context.getPointerType(FromType);
542 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000543 // We don't require any conversions for the first step.
544 else {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000545 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000546 }
547
548 // The second conversion can be an integral promotion, floating
549 // point promotion, integral conversion, floating point conversion,
550 // floating-integral conversion, pointer conversion,
551 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000552 // For overloading in C, this can also be a "compatible-type"
553 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000554 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000555 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000556 // The unqualified versions of the types are the same: there's no
557 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000558 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000559 }
560 // Integral promotion (C++ 4.5).
561 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000562 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000563 FromType = ToType.getUnqualifiedType();
564 }
565 // Floating point promotion (C++ 4.6).
566 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000567 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000568 FromType = ToType.getUnqualifiedType();
569 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000570 // Complex promotion (Clang extension)
571 else if (IsComplexPromotion(FromType, ToType)) {
572 SCS.Second = ICK_Complex_Promotion;
573 FromType = ToType.getUnqualifiedType();
574 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000575 // Integral conversions (C++ 4.7).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000576 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000577 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000578 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000579 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000580 FromType = ToType.getUnqualifiedType();
581 }
582 // Floating point conversions (C++ 4.8).
583 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000584 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000585 FromType = ToType.getUnqualifiedType();
586 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000587 // Complex conversions (C99 6.3.1.6)
588 else if (FromType->isComplexType() && ToType->isComplexType()) {
589 SCS.Second = ICK_Complex_Conversion;
590 FromType = ToType.getUnqualifiedType();
591 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000592 // Floating-integral conversions (C++ 4.9).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000593 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000594 else if ((FromType->isFloatingType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000595 ToType->isIntegralType() && !ToType->isBooleanType() &&
596 !ToType->isEnumeralType()) ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000597 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
598 ToType->isFloatingType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000599 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000600 FromType = ToType.getUnqualifiedType();
601 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000602 // Complex-real conversions (C99 6.3.1.7)
603 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
604 (ToType->isComplexType() && FromType->isArithmeticType())) {
605 SCS.Second = ICK_Complex_Real;
606 FromType = ToType.getUnqualifiedType();
607 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000608 // Pointer conversions (C++ 4.10).
Douglas Gregor6fd35572008-12-19 17:40:08 +0000609 else if (IsPointerConversion(From, FromType, ToType, FromType,
610 IncompatibleObjC)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000611 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000612 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000613 }
Sebastian Redlba387562009-01-25 19:43:20 +0000614 // Pointer to member conversions (4.11).
615 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
616 SCS.Second = ICK_Pointer_Member;
617 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000618 // Boolean conversions (C++ 4.12).
Douglas Gregord2baafd2008-10-21 16:13:35 +0000619 else if (ToType->isBooleanType() &&
620 (FromType->isArithmeticType() ||
621 FromType->isEnumeralType() ||
Douglas Gregor80402cf2008-12-23 00:53:59 +0000622 FromType->isPointerType() ||
Sebastian Redlba387562009-01-25 19:43:20 +0000623 FromType->isBlockPointerType() ||
624 FromType->isMemberPointerType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000625 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000626 FromType = Context.BoolTy;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000627 }
628 // Compatible conversions (Clang extension for C function overloading)
629 else if (!getLangOptions().CPlusPlus &&
630 Context.typesAreCompatible(ToType, FromType)) {
631 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000632 } else {
633 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000634 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000635 }
636
Douglas Gregor81c29152008-10-29 00:13:59 +0000637 QualType CanonFrom;
638 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000639 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000640 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000641 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000642 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000643 CanonFrom = Context.getCanonicalType(FromType);
644 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000645 } else {
646 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000647 SCS.Third = ICK_Identity;
648
649 // C++ [over.best.ics]p6:
650 // [...] Any difference in top-level cv-qualification is
651 // subsumed by the initialization itself and does not constitute
652 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000653 CanonFrom = Context.getCanonicalType(FromType);
654 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000655 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000656 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
657 FromType = ToType;
658 CanonFrom = CanonTo;
659 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000660 }
661
662 // If we have not converted the argument type to the parameter type,
663 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000664 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000665 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000666
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000667 SCS.ToTypePtr = FromType.getAsOpaquePtr();
668 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000669}
670
671/// IsIntegralPromotion - Determines whether the conversion from the
672/// expression From (whose potentially-adjusted type is FromType) to
673/// ToType is an integral promotion (C++ 4.5). If so, returns true and
674/// sets PromotedType to the promoted type.
675bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
676{
677 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000678 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000679 if (!To) {
680 return false;
681 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000682
683 // An rvalue of type char, signed char, unsigned char, short int, or
684 // unsigned short int can be converted to an rvalue of type int if
685 // int can represent all the values of the source type; otherwise,
686 // the source rvalue can be converted to an rvalue of type unsigned
687 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000688 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000689 if (// We can promote any signed, promotable integer type to an int
690 (FromType->isSignedIntegerType() ||
691 // We can promote any unsigned integer type whose size is
692 // less than int to an int.
693 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000694 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000695 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000696 }
697
Douglas Gregord2baafd2008-10-21 16:13:35 +0000698 return To->getKind() == BuiltinType::UInt;
699 }
700
701 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
702 // can be converted to an rvalue of the first of the following types
703 // that can represent all the values of its underlying type: int,
704 // unsigned int, long, or unsigned long (C++ 4.5p2).
705 if ((FromType->isEnumeralType() || FromType->isWideCharType())
706 && ToType->isIntegerType()) {
707 // Determine whether the type we're converting from is signed or
708 // unsigned.
709 bool FromIsSigned;
710 uint64_t FromSize = Context.getTypeSize(FromType);
711 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
712 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
713 FromIsSigned = UnderlyingType->isSignedIntegerType();
714 } else {
715 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
716 FromIsSigned = true;
717 }
718
719 // The types we'll try to promote to, in the appropriate
720 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000721 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000722 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000723 Context.LongTy, Context.UnsignedLongTy ,
724 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000725 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000726 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000727 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
728 if (FromSize < ToSize ||
729 (FromSize == ToSize &&
730 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
731 // We found the type that we can promote to. If this is the
732 // type we wanted, we have a promotion. Otherwise, no
733 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000734 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000735 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
736 }
737 }
738 }
739
740 // An rvalue for an integral bit-field (9.6) can be converted to an
741 // rvalue of type int if int can represent all the values of the
742 // bit-field; otherwise, it can be converted to unsigned int if
743 // unsigned int can represent all the values of the bit-field. If
744 // the bit-field is larger yet, no integral promotion applies to
745 // it. If the bit-field has an enumerated type, it is treated as any
746 // other value of that type for promotion purposes (C++ 4.5p3).
Douglas Gregor4ff48512009-02-12 00:26:06 +0000747 // FIXME: We should delay checking of bit-fields until we actually
748 // perform the conversion.
749 if (MemberExpr *MemRef = dyn_cast_or_null<MemberExpr>(From)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000750 using llvm::APSInt;
Douglas Gregor82d44772008-12-20 23:49:58 +0000751 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
752 APSInt BitWidth;
753 if (MemberDecl->isBitField() &&
754 FromType->isIntegralType() && !FromType->isEnumeralType() &&
755 From->isIntegerConstantExpr(BitWidth, Context)) {
756 APSInt ToSize(Context.getTypeSize(ToType));
757
758 // Are we promoting to an int from a bitfield that fits in an int?
759 if (BitWidth < ToSize ||
760 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
761 return To->getKind() == BuiltinType::Int;
762 }
763
764 // Are we promoting to an unsigned int from an unsigned bitfield
765 // that fits into an unsigned int?
766 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
767 return To->getKind() == BuiltinType::UInt;
768 }
769
770 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000771 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000772 }
773 }
774
775 // An rvalue of type bool can be converted to an rvalue of type int,
776 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000777 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000778 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000779 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000780
781 return false;
782}
783
784/// IsFloatingPointPromotion - Determines whether the conversion from
785/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
786/// returns true and sets PromotedType to the promoted type.
787bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
788{
789 /// An rvalue of type float can be converted to an rvalue of type
790 /// double. (C++ 4.6p1).
791 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000792 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000793 if (FromBuiltin->getKind() == BuiltinType::Float &&
794 ToBuiltin->getKind() == BuiltinType::Double)
795 return true;
796
Douglas Gregore819caf2009-02-12 00:15:05 +0000797 // C99 6.3.1.5p1:
798 // When a float is promoted to double or long double, or a
799 // double is promoted to long double [...].
800 if (!getLangOptions().CPlusPlus &&
801 (FromBuiltin->getKind() == BuiltinType::Float ||
802 FromBuiltin->getKind() == BuiltinType::Double) &&
803 (ToBuiltin->getKind() == BuiltinType::LongDouble))
804 return true;
805 }
806
Douglas Gregord2baafd2008-10-21 16:13:35 +0000807 return false;
808}
809
Douglas Gregore819caf2009-02-12 00:15:05 +0000810/// \brief Determine if a conversion is a complex promotion.
811///
812/// A complex promotion is defined as a complex -> complex conversion
813/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000814/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000815bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
816 const ComplexType *FromComplex = FromType->getAsComplexType();
817 if (!FromComplex)
818 return false;
819
820 const ComplexType *ToComplex = ToType->getAsComplexType();
821 if (!ToComplex)
822 return false;
823
824 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000825 ToComplex->getElementType()) ||
826 IsIntegralPromotion(0, FromComplex->getElementType(),
827 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000828}
829
Douglas Gregor24a90a52008-11-26 23:31:11 +0000830/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
831/// the pointer type FromPtr to a pointer to type ToPointee, with the
832/// same type qualifiers as FromPtr has on its pointee type. ToType,
833/// if non-empty, will be a pointer to ToType that may or may not have
834/// the right set of qualifiers on its pointee.
835static QualType
836BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
837 QualType ToPointee, QualType ToType,
838 ASTContext &Context) {
839 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
840 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
841 unsigned Quals = CanonFromPointee.getCVRQualifiers();
842
843 // Exact qualifier match -> return the pointer type we're converting to.
844 if (CanonToPointee.getCVRQualifiers() == Quals) {
845 // ToType is exactly what we need. Return it.
846 if (ToType.getTypePtr())
847 return ToType;
848
849 // Build a pointer to ToPointee. It has the right qualifiers
850 // already.
851 return Context.getPointerType(ToPointee);
852 }
853
854 // Just build a canonical type that has the right qualifiers.
855 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
856}
857
Douglas Gregord2baafd2008-10-21 16:13:35 +0000858/// IsPointerConversion - Determines whether the conversion of the
859/// expression From, which has the (possibly adjusted) type FromType,
860/// can be converted to the type ToType via a pointer conversion (C++
861/// 4.10). If so, returns true and places the converted type (that
862/// might differ from ToType in its cv-qualifiers at some level) into
863/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000864///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000865/// This routine also supports conversions to and from block pointers
866/// and conversions with Objective-C's 'id', 'id<protocols...>', and
867/// pointers to interfaces. FIXME: Once we've determined the
868/// appropriate overloading rules for Objective-C, we may want to
869/// split the Objective-C checks into a different routine; however,
870/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000871/// conversions, so for now they live here. IncompatibleObjC will be
872/// set if the conversion is an allowed Objective-C conversion that
873/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000874bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000875 QualType& ConvertedType,
876 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000877{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000878 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000879 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
880 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000881
Douglas Gregorf1d75712008-12-22 20:51:52 +0000882 // Conversion from a null pointer constant to any Objective-C pointer type.
883 if (Context.isObjCObjectPointerType(ToType) &&
884 From->isNullPointerConstant(Context)) {
885 ConvertedType = ToType;
886 return true;
887 }
888
Douglas Gregor9036ef72008-11-27 00:15:41 +0000889 // Blocks: Block pointers can be converted to void*.
890 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
891 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
892 ConvertedType = ToType;
893 return true;
894 }
895 // Blocks: A null pointer constant can be converted to a block
896 // pointer type.
897 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
898 ConvertedType = ToType;
899 return true;
900 }
901
Douglas Gregord2baafd2008-10-21 16:13:35 +0000902 const PointerType* ToTypePtr = ToType->getAsPointerType();
903 if (!ToTypePtr)
904 return false;
905
906 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
907 if (From->isNullPointerConstant(Context)) {
908 ConvertedType = ToType;
909 return true;
910 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000911
Douglas Gregor24a90a52008-11-26 23:31:11 +0000912 // Beyond this point, both types need to be pointers.
913 const PointerType *FromTypePtr = FromType->getAsPointerType();
914 if (!FromTypePtr)
915 return false;
916
917 QualType FromPointeeType = FromTypePtr->getPointeeType();
918 QualType ToPointeeType = ToTypePtr->getPointeeType();
919
Douglas Gregord2baafd2008-10-21 16:13:35 +0000920 // An rvalue of type "pointer to cv T," where T is an object type,
921 // can be converted to an rvalue of type "pointer to cv void" (C++
922 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000923 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000924 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
925 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000926 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000927 return true;
928 }
929
Douglas Gregorfcb19192009-02-11 23:02:49 +0000930 // When we're overloading in C, we allow a special kind of pointer
931 // conversion for compatible-but-not-identical pointee types.
932 if (!getLangOptions().CPlusPlus &&
933 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
934 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
935 ToPointeeType,
936 ToType, Context);
937 return true;
938 }
939
Douglas Gregor14046502008-10-23 00:40:37 +0000940 // C++ [conv.ptr]p3:
941 //
942 // An rvalue of type "pointer to cv D," where D is a class type,
943 // can be converted to an rvalue of type "pointer to cv B," where
944 // B is a base class (clause 10) of D. If B is an inaccessible
945 // (clause 11) or ambiguous (10.2) base class of D, a program that
946 // necessitates this conversion is ill-formed. The result of the
947 // conversion is a pointer to the base class sub-object of the
948 // derived class object. The null pointer value is converted to
949 // the null pointer value of the destination type.
950 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000951 // Note that we do not check for ambiguity or inaccessibility
952 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000953 if (getLangOptions().CPlusPlus &&
954 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000955 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000956 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
957 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000958 ToType, Context);
959 return true;
960 }
Douglas Gregor14046502008-10-23 00:40:37 +0000961
Douglas Gregor932778b2008-12-19 19:13:09 +0000962 return false;
963}
964
965/// isObjCPointerConversion - Determines whether this is an
966/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
967/// with the same arguments and return values.
968bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
969 QualType& ConvertedType,
970 bool &IncompatibleObjC) {
971 if (!getLangOptions().ObjC1)
972 return false;
973
974 // Conversions with Objective-C's id<...>.
975 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
976 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
977 ConvertedType = ToType;
978 return true;
979 }
980
Douglas Gregor80402cf2008-12-23 00:53:59 +0000981 // Beyond this point, both types need to be pointers or block pointers.
982 QualType ToPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000983 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000984 if (ToTypePtr)
985 ToPointeeType = ToTypePtr->getPointeeType();
986 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
987 ToPointeeType = ToBlockPtr->getPointeeType();
988 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000989 return false;
990
Douglas Gregor80402cf2008-12-23 00:53:59 +0000991 QualType FromPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000992 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000993 if (FromTypePtr)
994 FromPointeeType = FromTypePtr->getPointeeType();
995 else if (const BlockPointerType *FromBlockPtr
996 = FromType->getAsBlockPointerType())
997 FromPointeeType = FromBlockPtr->getPointeeType();
998 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000999 return false;
1000
Douglas Gregor24a90a52008-11-26 23:31:11 +00001001 // Objective C++: We're able to convert from a pointer to an
1002 // interface to a pointer to a different interface.
1003 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
1004 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1005 if (FromIface && ToIface &&
1006 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor80402cf2008-12-23 00:53:59 +00001007 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001008 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001009 ToType, Context);
1010 return true;
1011 }
1012
Douglas Gregor6fd35572008-12-19 17:40:08 +00001013 if (FromIface && ToIface &&
1014 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1015 // Okay: this is some kind of implicit downcast of Objective-C
1016 // interfaces, which is permitted. However, we're going to
1017 // complain about it.
1018 IncompatibleObjC = true;
Douglas Gregor80402cf2008-12-23 00:53:59 +00001019 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor6fd35572008-12-19 17:40:08 +00001020 ToPointeeType,
1021 ToType, Context);
1022 return true;
1023 }
1024
Douglas Gregor24a90a52008-11-26 23:31:11 +00001025 // Objective C++: We're able to convert between "id" and a pointer
1026 // to any interface (in both directions).
Steve Naroff17c03822009-02-12 17:52:19 +00001027 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1028 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001029 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1030 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001031 ToType, Context);
1032 return true;
1033 }
Douglas Gregor14046502008-10-23 00:40:37 +00001034
Douglas Gregord0c653a2008-12-18 23:43:31 +00001035 // Objective C++: Allow conversions between the Objective-C "id" and
1036 // "Class", in either direction.
Steve Naroff17c03822009-02-12 17:52:19 +00001037 if ((Context.isObjCIdStructType(FromPointeeType) &&
1038 Context.isObjCClassStructType(ToPointeeType)) ||
1039 (Context.isObjCClassStructType(FromPointeeType) &&
1040 Context.isObjCIdStructType(ToPointeeType))) {
Douglas Gregord0c653a2008-12-18 23:43:31 +00001041 ConvertedType = ToType;
1042 return true;
1043 }
1044
Douglas Gregor932778b2008-12-19 19:13:09 +00001045 // If we have pointers to pointers, recursively check whether this
1046 // is an Objective-C conversion.
1047 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1048 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1049 IncompatibleObjC)) {
1050 // We always complain about this conversion.
1051 IncompatibleObjC = true;
1052 ConvertedType = ToType;
1053 return true;
1054 }
1055
Douglas Gregor80402cf2008-12-23 00:53:59 +00001056 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001057 // differences in the argument and result types are in Objective-C
1058 // pointer conversions. If so, we permit the conversion (but
1059 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001060 const FunctionProtoType *FromFunctionType
1061 = FromPointeeType->getAsFunctionProtoType();
1062 const FunctionProtoType *ToFunctionType
1063 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001064 if (FromFunctionType && ToFunctionType) {
1065 // If the function types are exactly the same, this isn't an
1066 // Objective-C pointer conversion.
1067 if (Context.getCanonicalType(FromPointeeType)
1068 == Context.getCanonicalType(ToPointeeType))
1069 return false;
1070
1071 // Perform the quick checks that will tell us whether these
1072 // function types are obviously different.
1073 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1074 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1075 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1076 return false;
1077
1078 bool HasObjCConversion = false;
1079 if (Context.getCanonicalType(FromFunctionType->getResultType())
1080 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1081 // Okay, the types match exactly. Nothing to do.
1082 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1083 ToFunctionType->getResultType(),
1084 ConvertedType, IncompatibleObjC)) {
1085 // Okay, we have an Objective-C pointer conversion.
1086 HasObjCConversion = true;
1087 } else {
1088 // Function types are too different. Abort.
1089 return false;
1090 }
1091
1092 // Check argument types.
1093 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1094 ArgIdx != NumArgs; ++ArgIdx) {
1095 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1096 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1097 if (Context.getCanonicalType(FromArgType)
1098 == Context.getCanonicalType(ToArgType)) {
1099 // Okay, the types match exactly. Nothing to do.
1100 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1101 ConvertedType, IncompatibleObjC)) {
1102 // Okay, we have an Objective-C pointer conversion.
1103 HasObjCConversion = true;
1104 } else {
1105 // Argument types are too different. Abort.
1106 return false;
1107 }
1108 }
1109
1110 if (HasObjCConversion) {
1111 // We had an Objective-C conversion. Allow this pointer
1112 // conversion, but complain about it.
1113 ConvertedType = ToType;
1114 IncompatibleObjC = true;
1115 return true;
1116 }
1117 }
1118
Sebastian Redlba387562009-01-25 19:43:20 +00001119 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001120}
1121
Douglas Gregorbb461502008-10-24 04:54:22 +00001122/// CheckPointerConversion - Check the pointer conversion from the
1123/// expression From to the type ToType. This routine checks for
1124/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1125/// conversions for which IsPointerConversion has already returned
1126/// true. It returns true and produces a diagnostic if there was an
1127/// error, or returns false otherwise.
1128bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1129 QualType FromType = From->getType();
1130
1131 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1132 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001133 QualType FromPointeeType = FromPtrType->getPointeeType(),
1134 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001135
1136 // Objective-C++ conversions are always okay.
1137 // FIXME: We should have a different class of conversions for
1138 // the Objective-C++ implicit conversions.
Steve Naroff17c03822009-02-12 17:52:19 +00001139 if (Context.isObjCIdStructType(FromPointeeType) ||
1140 Context.isObjCIdStructType(ToPointeeType) ||
1141 Context.isObjCClassStructType(FromPointeeType) ||
1142 Context.isObjCClassStructType(ToPointeeType))
Douglas Gregord0c653a2008-12-18 23:43:31 +00001143 return false;
1144
Douglas Gregorbb461502008-10-24 04:54:22 +00001145 if (FromPointeeType->isRecordType() &&
1146 ToPointeeType->isRecordType()) {
1147 // We must have a derived-to-base conversion. Check an
1148 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001149 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1150 From->getExprLoc(),
1151 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001152 }
1153 }
1154
1155 return false;
1156}
1157
Sebastian Redlba387562009-01-25 19:43:20 +00001158/// IsMemberPointerConversion - Determines whether the conversion of the
1159/// expression From, which has the (possibly adjusted) type FromType, can be
1160/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1161/// If so, returns true and places the converted type (that might differ from
1162/// ToType in its cv-qualifiers at some level) into ConvertedType.
1163bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1164 QualType ToType, QualType &ConvertedType)
1165{
1166 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1167 if (!ToTypePtr)
1168 return false;
1169
1170 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1171 if (From->isNullPointerConstant(Context)) {
1172 ConvertedType = ToType;
1173 return true;
1174 }
1175
1176 // Otherwise, both types have to be member pointers.
1177 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1178 if (!FromTypePtr)
1179 return false;
1180
1181 // A pointer to member of B can be converted to a pointer to member of D,
1182 // where D is derived from B (C++ 4.11p2).
1183 QualType FromClass(FromTypePtr->getClass(), 0);
1184 QualType ToClass(ToTypePtr->getClass(), 0);
1185 // FIXME: What happens when these are dependent? Is this function even called?
1186
1187 if (IsDerivedFrom(ToClass, FromClass)) {
1188 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1189 ToClass.getTypePtr());
1190 return true;
1191 }
1192
1193 return false;
1194}
1195
1196/// CheckMemberPointerConversion - Check the member pointer conversion from the
1197/// expression From to the type ToType. This routine checks for ambiguous or
1198/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1199/// for which IsMemberPointerConversion has already returned true. It returns
1200/// true and produces a diagnostic if there was an error, or returns false
1201/// otherwise.
1202bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1203 QualType FromType = From->getType();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001204 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1205 if (!FromPtrType)
1206 return false;
Sebastian Redlba387562009-01-25 19:43:20 +00001207
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001208 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1209 assert(ToPtrType && "No member pointer cast has a target type "
1210 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001211
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001212 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1213 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001214
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001215 // FIXME: What about dependent types?
1216 assert(FromClass->isRecordType() && "Pointer into non-class.");
1217 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001218
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001219 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1220 /*DetectVirtual=*/true);
1221 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1222 assert(DerivationOkay &&
1223 "Should not have been called if derivation isn't OK.");
1224 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001225
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001226 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1227 getUnqualifiedType())) {
1228 // Derivation is ambiguous. Redo the check to find the exact paths.
1229 Paths.clear();
1230 Paths.setRecordingPaths(true);
1231 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1232 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1233 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001234
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001235 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1236 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1237 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1238 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001239 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001240
Douglas Gregor2e047592009-02-28 01:32:25 +00001241 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001242 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1243 << FromClass << ToClass << QualType(VBase, 0)
1244 << From->getSourceRange();
1245 return true;
1246 }
1247
Sebastian Redlba387562009-01-25 19:43:20 +00001248 return false;
1249}
1250
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001251/// IsQualificationConversion - Determines whether the conversion from
1252/// an rvalue of type FromType to ToType is a qualification conversion
1253/// (C++ 4.4).
1254bool
1255Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1256{
1257 FromType = Context.getCanonicalType(FromType);
1258 ToType = Context.getCanonicalType(ToType);
1259
1260 // If FromType and ToType are the same type, this is not a
1261 // qualification conversion.
1262 if (FromType == ToType)
1263 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001264
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001265 // (C++ 4.4p4):
1266 // A conversion can add cv-qualifiers at levels other than the first
1267 // in multi-level pointers, subject to the following rules: [...]
1268 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001269 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001270 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001271 // Within each iteration of the loop, we check the qualifiers to
1272 // determine if this still looks like a qualification
1273 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001274 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001275 // until there are no more pointers or pointers-to-members left to
1276 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001277 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001278
1279 // -- for every j > 0, if const is in cv 1,j then const is in cv
1280 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001281 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001282 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001283
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001284 // -- if the cv 1,j and cv 2,j are different, then const is in
1285 // every cv for 0 < k < j.
1286 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001287 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001288 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001289
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001290 // Keep track of whether all prior cv-qualifiers in the "to" type
1291 // include const.
1292 PreviousToQualsIncludeConst
1293 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001294 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001295
1296 // We are left with FromType and ToType being the pointee types
1297 // after unwrapping the original FromType and ToType the same number
1298 // of types. If we unwrapped any pointers, and if FromType and
1299 // ToType have the same unqualified type (since we checked
1300 // qualifiers above), then this is a qualification conversion.
1301 return UnwrappedAnyPointer &&
1302 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1303}
1304
Douglas Gregorb206cc42009-01-30 23:27:23 +00001305/// Determines whether there is a user-defined conversion sequence
1306/// (C++ [over.ics.user]) that converts expression From to the type
1307/// ToType. If such a conversion exists, User will contain the
1308/// user-defined conversion sequence that performs such a conversion
1309/// and this routine will return true. Otherwise, this routine returns
1310/// false and User is unspecified.
1311///
1312/// \param AllowConversionFunctions true if the conversion should
1313/// consider conversion functions at all. If false, only constructors
1314/// will be considered.
1315///
1316/// \param AllowExplicit true if the conversion should consider C++0x
1317/// "explicit" conversion functions as well as non-explicit conversion
1318/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001319///
1320/// \param ForceRValue true if the expression should be treated as an rvalue
1321/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001322bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001323 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001324 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001325 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001326{
1327 OverloadCandidateSet CandidateSet;
Douglas Gregor2e047592009-02-28 01:32:25 +00001328 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1329 if (CXXRecordDecl *ToRecordDecl
1330 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1331 // C++ [over.match.ctor]p1:
1332 // When objects of class type are direct-initialized (8.5), or
1333 // copy-initialized from an expression of the same or a
1334 // derived class type (8.5), overload resolution selects the
1335 // constructor. [...] For copy-initialization, the candidate
1336 // functions are all the converting constructors (12.3.1) of
1337 // that class. The argument list is the expression-list within
1338 // the parentheses of the initializer.
1339 DeclarationName ConstructorName
1340 = Context.DeclarationNames.getCXXConstructorName(
1341 Context.getCanonicalType(ToType).getUnqualifiedType());
1342 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001343 for (llvm::tie(Con, ConEnd)
1344 = ToRecordDecl->lookup(Context, ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001345 Con != ConEnd; ++Con) {
1346 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1347 if (Constructor->isConvertingConstructor())
1348 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00001349 /*SuppressUserConversions=*/true, ForceRValue);
Douglas Gregor2e047592009-02-28 01:32:25 +00001350 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001351 }
1352 }
1353
Douglas Gregorb206cc42009-01-30 23:27:23 +00001354 if (!AllowConversionFunctions) {
1355 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-02-28 01:32:25 +00001356 } else if (const RecordType *FromRecordType
1357 = From->getType()->getAsRecordType()) {
1358 if (CXXRecordDecl *FromRecordDecl
1359 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1360 // Add all of the conversion functions as candidates.
1361 // FIXME: Look for conversions in base classes!
1362 OverloadedFunctionDecl *Conversions
1363 = FromRecordDecl->getConversionFunctions();
1364 for (OverloadedFunctionDecl::function_iterator Func
1365 = Conversions->function_begin();
1366 Func != Conversions->function_end(); ++Func) {
1367 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1368 if (AllowExplicit || !Conv->isExplicit())
1369 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1370 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001371 }
1372 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001373
1374 OverloadCandidateSet::iterator Best;
1375 switch (BestViableFunction(CandidateSet, Best)) {
1376 case OR_Success:
1377 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001378 if (CXXConstructorDecl *Constructor
1379 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1380 // C++ [over.ics.user]p1:
1381 // If the user-defined conversion is specified by a
1382 // constructor (12.3.1), the initial standard conversion
1383 // sequence converts the source type to the type required by
1384 // the argument of the constructor.
1385 //
1386 // FIXME: What about ellipsis conversions?
1387 QualType ThisType = Constructor->getThisType(Context);
1388 User.Before = Best->Conversions[0].Standard;
1389 User.ConversionFunction = Constructor;
1390 User.After.setAsIdentityConversion();
1391 User.After.FromTypePtr
1392 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1393 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1394 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001395 } else if (CXXConversionDecl *Conversion
1396 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1397 // C++ [over.ics.user]p1:
1398 //
1399 // [...] If the user-defined conversion is specified by a
1400 // conversion function (12.3.2), the initial standard
1401 // conversion sequence converts the source type to the
1402 // implicit object parameter of the conversion function.
1403 User.Before = Best->Conversions[0].Standard;
1404 User.ConversionFunction = Conversion;
1405
1406 // C++ [over.ics.user]p2:
1407 // The second standard conversion sequence converts the
1408 // result of the user-defined conversion to the target type
1409 // for the sequence. Since an implicit conversion sequence
1410 // is an initialization, the special rules for
1411 // initialization by user-defined conversion apply when
1412 // selecting the best user-defined conversion for a
1413 // user-defined conversion sequence (see 13.3.3 and
1414 // 13.3.3.1).
1415 User.After = Best->FinalConversion;
1416 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001417 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001418 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001419 return false;
1420 }
1421
1422 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001423 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001424 // No conversion here! We're done.
1425 return false;
1426
1427 case OR_Ambiguous:
1428 // FIXME: See C++ [over.best.ics]p10 for the handling of
1429 // ambiguous conversion sequences.
1430 return false;
1431 }
1432
1433 return false;
1434}
1435
Douglas Gregord2baafd2008-10-21 16:13:35 +00001436/// CompareImplicitConversionSequences - Compare two implicit
1437/// conversion sequences to determine whether one is better than the
1438/// other or if they are indistinguishable (C++ 13.3.3.2).
1439ImplicitConversionSequence::CompareKind
1440Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1441 const ImplicitConversionSequence& ICS2)
1442{
1443 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1444 // conversion sequences (as defined in 13.3.3.1)
1445 // -- a standard conversion sequence (13.3.3.1.1) is a better
1446 // conversion sequence than a user-defined conversion sequence or
1447 // an ellipsis conversion sequence, and
1448 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1449 // conversion sequence than an ellipsis conversion sequence
1450 // (13.3.3.1.3).
1451 //
1452 if (ICS1.ConversionKind < ICS2.ConversionKind)
1453 return ImplicitConversionSequence::Better;
1454 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1455 return ImplicitConversionSequence::Worse;
1456
1457 // Two implicit conversion sequences of the same form are
1458 // indistinguishable conversion sequences unless one of the
1459 // following rules apply: (C++ 13.3.3.2p3):
1460 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1461 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1462 else if (ICS1.ConversionKind ==
1463 ImplicitConversionSequence::UserDefinedConversion) {
1464 // User-defined conversion sequence U1 is a better conversion
1465 // sequence than another user-defined conversion sequence U2 if
1466 // they contain the same user-defined conversion function or
1467 // constructor and if the second standard conversion sequence of
1468 // U1 is better than the second standard conversion sequence of
1469 // U2 (C++ 13.3.3.2p3).
1470 if (ICS1.UserDefined.ConversionFunction ==
1471 ICS2.UserDefined.ConversionFunction)
1472 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1473 ICS2.UserDefined.After);
1474 }
1475
1476 return ImplicitConversionSequence::Indistinguishable;
1477}
1478
1479/// CompareStandardConversionSequences - Compare two standard
1480/// conversion sequences to determine whether one is better than the
1481/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1482ImplicitConversionSequence::CompareKind
1483Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1484 const StandardConversionSequence& SCS2)
1485{
1486 // Standard conversion sequence S1 is a better conversion sequence
1487 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1488
1489 // -- S1 is a proper subsequence of S2 (comparing the conversion
1490 // sequences in the canonical form defined by 13.3.3.1.1,
1491 // excluding any Lvalue Transformation; the identity conversion
1492 // sequence is considered to be a subsequence of any
1493 // non-identity conversion sequence) or, if not that,
1494 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1495 // Neither is a proper subsequence of the other. Do nothing.
1496 ;
1497 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1498 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1499 (SCS1.Second == ICK_Identity &&
1500 SCS1.Third == ICK_Identity))
1501 // SCS1 is a proper subsequence of SCS2.
1502 return ImplicitConversionSequence::Better;
1503 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1504 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1505 (SCS2.Second == ICK_Identity &&
1506 SCS2.Third == ICK_Identity))
1507 // SCS2 is a proper subsequence of SCS1.
1508 return ImplicitConversionSequence::Worse;
1509
1510 // -- the rank of S1 is better than the rank of S2 (by the rules
1511 // defined below), or, if not that,
1512 ImplicitConversionRank Rank1 = SCS1.getRank();
1513 ImplicitConversionRank Rank2 = SCS2.getRank();
1514 if (Rank1 < Rank2)
1515 return ImplicitConversionSequence::Better;
1516 else if (Rank2 < Rank1)
1517 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001518
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001519 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1520 // are indistinguishable unless one of the following rules
1521 // applies:
1522
1523 // A conversion that is not a conversion of a pointer, or
1524 // pointer to member, to bool is better than another conversion
1525 // that is such a conversion.
1526 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1527 return SCS2.isPointerConversionToBool()
1528 ? ImplicitConversionSequence::Better
1529 : ImplicitConversionSequence::Worse;
1530
Douglas Gregor14046502008-10-23 00:40:37 +00001531 // C++ [over.ics.rank]p4b2:
1532 //
1533 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001534 // conversion of B* to A* is better than conversion of B* to
1535 // void*, and conversion of A* to void* is better than conversion
1536 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001537 bool SCS1ConvertsToVoid
1538 = SCS1.isPointerConversionToVoidPointer(Context);
1539 bool SCS2ConvertsToVoid
1540 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001541 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1542 // Exactly one of the conversion sequences is a conversion to
1543 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001544 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1545 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001546 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1547 // Neither conversion sequence converts to a void pointer; compare
1548 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001549 if (ImplicitConversionSequence::CompareKind DerivedCK
1550 = CompareDerivedToBaseConversions(SCS1, SCS2))
1551 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001552 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1553 // Both conversion sequences are conversions to void
1554 // pointers. Compare the source types to determine if there's an
1555 // inheritance relationship in their sources.
1556 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1557 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1558
1559 // Adjust the types we're converting from via the array-to-pointer
1560 // conversion, if we need to.
1561 if (SCS1.First == ICK_Array_To_Pointer)
1562 FromType1 = Context.getArrayDecayedType(FromType1);
1563 if (SCS2.First == ICK_Array_To_Pointer)
1564 FromType2 = Context.getArrayDecayedType(FromType2);
1565
1566 QualType FromPointee1
1567 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1568 QualType FromPointee2
1569 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1570
1571 if (IsDerivedFrom(FromPointee2, FromPointee1))
1572 return ImplicitConversionSequence::Better;
1573 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1574 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001575
1576 // Objective-C++: If one interface is more specific than the
1577 // other, it is the better one.
1578 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1579 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1580 if (FromIface1 && FromIface1) {
1581 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1582 return ImplicitConversionSequence::Better;
1583 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1584 return ImplicitConversionSequence::Worse;
1585 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001586 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001587
1588 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1589 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001590 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001591 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001592 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001593
Douglas Gregor0e343382008-10-29 14:50:44 +00001594 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001595 // C++0x [over.ics.rank]p3b4:
1596 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1597 // implicit object parameter of a non-static member function declared
1598 // without a ref-qualifier, and S1 binds an rvalue reference to an
1599 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001600 // FIXME: We don't know if we're dealing with the implicit object parameter,
1601 // or if the member function in this case has a ref qualifier.
1602 // (Of course, we don't have ref qualifiers yet.)
1603 if (SCS1.RRefBinding != SCS2.RRefBinding)
1604 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1605 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001606
1607 // C++ [over.ics.rank]p3b4:
1608 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1609 // which the references refer are the same type except for
1610 // top-level cv-qualifiers, and the type to which the reference
1611 // initialized by S2 refers is more cv-qualified than the type
1612 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001613 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1614 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001615 T1 = Context.getCanonicalType(T1);
1616 T2 = Context.getCanonicalType(T2);
1617 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1618 if (T2.isMoreQualifiedThan(T1))
1619 return ImplicitConversionSequence::Better;
1620 else if (T1.isMoreQualifiedThan(T2))
1621 return ImplicitConversionSequence::Worse;
1622 }
1623 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001624
1625 return ImplicitConversionSequence::Indistinguishable;
1626}
1627
1628/// CompareQualificationConversions - Compares two standard conversion
1629/// sequences to determine whether they can be ranked based on their
1630/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1631ImplicitConversionSequence::CompareKind
1632Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1633 const StandardConversionSequence& SCS2)
1634{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001635 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001636 // -- S1 and S2 differ only in their qualification conversion and
1637 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1638 // cv-qualification signature of type T1 is a proper subset of
1639 // the cv-qualification signature of type T2, and S1 is not the
1640 // deprecated string literal array-to-pointer conversion (4.2).
1641 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1642 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1643 return ImplicitConversionSequence::Indistinguishable;
1644
1645 // FIXME: the example in the standard doesn't use a qualification
1646 // conversion (!)
1647 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1648 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1649 T1 = Context.getCanonicalType(T1);
1650 T2 = Context.getCanonicalType(T2);
1651
1652 // If the types are the same, we won't learn anything by unwrapped
1653 // them.
1654 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1655 return ImplicitConversionSequence::Indistinguishable;
1656
1657 ImplicitConversionSequence::CompareKind Result
1658 = ImplicitConversionSequence::Indistinguishable;
1659 while (UnwrapSimilarPointerTypes(T1, T2)) {
1660 // Within each iteration of the loop, we check the qualifiers to
1661 // determine if this still looks like a qualification
1662 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001663 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001664 // until there are no more pointers or pointers-to-members left
1665 // to unwrap. This essentially mimics what
1666 // IsQualificationConversion does, but here we're checking for a
1667 // strict subset of qualifiers.
1668 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1669 // The qualifiers are the same, so this doesn't tell us anything
1670 // about how the sequences rank.
1671 ;
1672 else if (T2.isMoreQualifiedThan(T1)) {
1673 // T1 has fewer qualifiers, so it could be the better sequence.
1674 if (Result == ImplicitConversionSequence::Worse)
1675 // Neither has qualifiers that are a subset of the other's
1676 // qualifiers.
1677 return ImplicitConversionSequence::Indistinguishable;
1678
1679 Result = ImplicitConversionSequence::Better;
1680 } else if (T1.isMoreQualifiedThan(T2)) {
1681 // T2 has fewer qualifiers, so it could be the better sequence.
1682 if (Result == ImplicitConversionSequence::Better)
1683 // Neither has qualifiers that are a subset of the other's
1684 // qualifiers.
1685 return ImplicitConversionSequence::Indistinguishable;
1686
1687 Result = ImplicitConversionSequence::Worse;
1688 } else {
1689 // Qualifiers are disjoint.
1690 return ImplicitConversionSequence::Indistinguishable;
1691 }
1692
1693 // If the types after this point are equivalent, we're done.
1694 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1695 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001696 }
1697
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001698 // Check that the winning standard conversion sequence isn't using
1699 // the deprecated string literal array to pointer conversion.
1700 switch (Result) {
1701 case ImplicitConversionSequence::Better:
1702 if (SCS1.Deprecated)
1703 Result = ImplicitConversionSequence::Indistinguishable;
1704 break;
1705
1706 case ImplicitConversionSequence::Indistinguishable:
1707 break;
1708
1709 case ImplicitConversionSequence::Worse:
1710 if (SCS2.Deprecated)
1711 Result = ImplicitConversionSequence::Indistinguishable;
1712 break;
1713 }
1714
1715 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001716}
1717
Douglas Gregor14046502008-10-23 00:40:37 +00001718/// CompareDerivedToBaseConversions - Compares two standard conversion
1719/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001720/// various kinds of derived-to-base conversions (C++
1721/// [over.ics.rank]p4b3). As part of these checks, we also look at
1722/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001723ImplicitConversionSequence::CompareKind
1724Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1725 const StandardConversionSequence& SCS2) {
1726 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1727 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1728 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1729 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1730
1731 // Adjust the types we're converting from via the array-to-pointer
1732 // conversion, if we need to.
1733 if (SCS1.First == ICK_Array_To_Pointer)
1734 FromType1 = Context.getArrayDecayedType(FromType1);
1735 if (SCS2.First == ICK_Array_To_Pointer)
1736 FromType2 = Context.getArrayDecayedType(FromType2);
1737
1738 // Canonicalize all of the types.
1739 FromType1 = Context.getCanonicalType(FromType1);
1740 ToType1 = Context.getCanonicalType(ToType1);
1741 FromType2 = Context.getCanonicalType(FromType2);
1742 ToType2 = Context.getCanonicalType(ToType2);
1743
Douglas Gregor0e343382008-10-29 14:50:44 +00001744 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001745 //
1746 // If class B is derived directly or indirectly from class A and
1747 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001748 //
1749 // For Objective-C, we let A, B, and C also be Objective-C
1750 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001751
1752 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001753 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001754 SCS2.Second == ICK_Pointer_Conversion &&
1755 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1756 FromType1->isPointerType() && FromType2->isPointerType() &&
1757 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001758 QualType FromPointee1
1759 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1760 QualType ToPointee1
1761 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1762 QualType FromPointee2
1763 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1764 QualType ToPointee2
1765 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001766
1767 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1768 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1769 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1770 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1771
Douglas Gregor0e343382008-10-29 14:50:44 +00001772 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001773 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1774 if (IsDerivedFrom(ToPointee1, ToPointee2))
1775 return ImplicitConversionSequence::Better;
1776 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1777 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001778
1779 if (ToIface1 && ToIface2) {
1780 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1781 return ImplicitConversionSequence::Better;
1782 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1783 return ImplicitConversionSequence::Worse;
1784 }
Douglas Gregor14046502008-10-23 00:40:37 +00001785 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001786
1787 // -- conversion of B* to A* is better than conversion of C* to A*,
1788 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1789 if (IsDerivedFrom(FromPointee2, FromPointee1))
1790 return ImplicitConversionSequence::Better;
1791 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1792 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001793
1794 if (FromIface1 && FromIface2) {
1795 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1796 return ImplicitConversionSequence::Better;
1797 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1798 return ImplicitConversionSequence::Worse;
1799 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001800 }
Douglas Gregor14046502008-10-23 00:40:37 +00001801 }
1802
Douglas Gregor0e343382008-10-29 14:50:44 +00001803 // Compare based on reference bindings.
1804 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1805 SCS1.Second == ICK_Derived_To_Base) {
1806 // -- binding of an expression of type C to a reference of type
1807 // B& is better than binding an expression of type C to a
1808 // reference of type A&,
1809 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1810 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1811 if (IsDerivedFrom(ToType1, ToType2))
1812 return ImplicitConversionSequence::Better;
1813 else if (IsDerivedFrom(ToType2, ToType1))
1814 return ImplicitConversionSequence::Worse;
1815 }
1816
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001817 // -- binding of an expression of type B to a reference of type
1818 // A& is better than binding an expression of type C to a
1819 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001820 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 }
1828
1829
1830 // FIXME: conversion of A::* to B::* is better than conversion of
1831 // A::* to C::*,
1832
1833 // FIXME: conversion of B::* to C::* is better than conversion of
1834 // A::* to C::*, and
1835
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001836 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1837 SCS1.Second == ICK_Derived_To_Base) {
1838 // -- conversion of C to B is better than conversion of C to A,
1839 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1840 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1841 if (IsDerivedFrom(ToType1, ToType2))
1842 return ImplicitConversionSequence::Better;
1843 else if (IsDerivedFrom(ToType2, ToType1))
1844 return ImplicitConversionSequence::Worse;
1845 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001846
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001847 // -- conversion of B to A is better than conversion of C to A.
1848 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1849 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1850 if (IsDerivedFrom(FromType2, FromType1))
1851 return ImplicitConversionSequence::Better;
1852 else if (IsDerivedFrom(FromType1, FromType2))
1853 return ImplicitConversionSequence::Worse;
1854 }
1855 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001856
Douglas Gregor14046502008-10-23 00:40:37 +00001857 return ImplicitConversionSequence::Indistinguishable;
1858}
1859
Douglas Gregor81c29152008-10-29 00:13:59 +00001860/// TryCopyInitialization - Try to copy-initialize a value of type
1861/// ToType from the expression From. Return the implicit conversion
1862/// sequence required to pass this argument, which may be a bad
1863/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001864/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001865/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1866/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001867ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001868Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001869 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001870 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001871 ImplicitConversionSequence ICS;
Sebastian Redla55834a2009-04-12 17:16:29 +00001872 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1873 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001874 return ICS;
1875 } else {
Sebastian Redla55834a2009-04-12 17:16:29 +00001876 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1877 ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001878 }
1879}
1880
Sebastian Redla55834a2009-04-12 17:16:29 +00001881/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1882/// the expression @p From. Returns true (and emits a diagnostic) if there was
1883/// an error, returns false if the initialization succeeded. Elidable should
1884/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1885/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001886bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001887 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001888 if (!getLangOptions().CPlusPlus) {
1889 // In C, argument passing is the same as performing an assignment.
1890 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001891
Douglas Gregor81c29152008-10-29 00:13:59 +00001892 AssignConvertType ConvTy =
1893 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001894 if (ConvTy != Compatible &&
1895 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1896 ConvTy = Compatible;
1897
Douglas Gregor81c29152008-10-29 00:13:59 +00001898 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1899 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001900 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001901
Chris Lattner271d4c22008-11-24 05:29:24 +00001902 if (ToType->isReferenceType())
1903 return CheckReferenceInit(From, ToType);
1904
Sebastian Redla55834a2009-04-12 17:16:29 +00001905 if (!PerformImplicitConversion(From, ToType, Flavor,
1906 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001907 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001908
Chris Lattner271d4c22008-11-24 05:29:24 +00001909 return Diag(From->getSourceRange().getBegin(),
1910 diag::err_typecheck_convert_incompatible)
1911 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001912}
1913
Douglas Gregor5ed15042008-11-18 23:14:02 +00001914/// TryObjectArgumentInitialization - Try to initialize the object
1915/// parameter of the given member function (@c Method) from the
1916/// expression @p From.
1917ImplicitConversionSequence
1918Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1919 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1920 unsigned MethodQuals = Method->getTypeQualifiers();
1921 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1922
1923 // Set up the conversion sequence as a "bad" conversion, to allow us
1924 // to exit early.
1925 ImplicitConversionSequence ICS;
1926 ICS.Standard.setAsIdentityConversion();
1927 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1928
1929 // We need to have an object of class type.
1930 QualType FromType = From->getType();
1931 if (!FromType->isRecordType())
1932 return ICS;
1933
1934 // The implicit object parmeter is has the type "reference to cv X",
1935 // where X is the class of which the function is a member
1936 // (C++ [over.match.funcs]p4). However, when finding an implicit
1937 // conversion sequence for the argument, we are not allowed to
1938 // create temporaries or perform user-defined conversions
1939 // (C++ [over.match.funcs]p5). We perform a simplified version of
1940 // reference binding here, that allows class rvalues to bind to
1941 // non-constant references.
1942
1943 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1944 // with the implicit object parameter (C++ [over.match.funcs]p5).
1945 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1946 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1947 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1948 return ICS;
1949
1950 // Check that we have either the same type or a derived type. It
1951 // affects the conversion rank.
1952 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1953 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1954 ICS.Standard.Second = ICK_Identity;
1955 else if (IsDerivedFrom(FromType, ClassType))
1956 ICS.Standard.Second = ICK_Derived_To_Base;
1957 else
1958 return ICS;
1959
1960 // Success. Mark this as a reference binding.
1961 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1962 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1963 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1964 ICS.Standard.ReferenceBinding = true;
1965 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00001966 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00001967 return ICS;
1968}
1969
1970/// PerformObjectArgumentInitialization - Perform initialization of
1971/// the implicit object parameter for the given Method with the given
1972/// expression.
1973bool
1974Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1975 QualType ImplicitParamType
1976 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1977 ImplicitConversionSequence ICS
1978 = TryObjectArgumentInitialization(From, Method);
1979 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1980 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001981 diag::err_implicit_object_parameter_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001982 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor5ed15042008-11-18 23:14:02 +00001983
1984 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1985 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1986 From->getSourceRange().getBegin(),
1987 From->getSourceRange()))
1988 return true;
1989
1990 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1991 return false;
1992}
1993
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001994/// TryContextuallyConvertToBool - Attempt to contextually convert the
1995/// expression From to bool (C++0x [conv]p3).
1996ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1997 return TryImplicitConversion(From, Context.BoolTy, false, true);
1998}
1999
2000/// PerformContextuallyConvertToBool - Perform a contextual conversion
2001/// of the expression From to bool (C++0x [conv]p3).
2002bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2003 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2004 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2005 return false;
2006
2007 return Diag(From->getSourceRange().getBegin(),
2008 diag::err_typecheck_bool_condition)
2009 << From->getType() << From->getSourceRange();
2010}
2011
Douglas Gregord2baafd2008-10-21 16:13:35 +00002012/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002013/// candidate functions, using the given function call arguments. If
2014/// @p SuppressUserConversions, then don't allow user-defined
2015/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002016/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2017/// hacky way to implement the overloading rules for elidable copy
2018/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002019void
2020Sema::AddOverloadCandidate(FunctionDecl *Function,
2021 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002022 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002023 bool SuppressUserConversions,
2024 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002025{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002026 const FunctionProtoType* Proto
2027 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002028 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002029 assert(!isa<CXXConversionDecl>(Function) &&
2030 "Use AddConversionCandidate for conversion functions");
Douglas Gregord2baafd2008-10-21 16:13:35 +00002031
Douglas Gregor3257fb52008-12-22 05:46:06 +00002032 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002033 if (!isa<CXXConstructorDecl>(Method)) {
2034 // If we get here, it's because we're calling a member function
2035 // that is named without a member access expression (e.g.,
2036 // "this->f") that was either written explicitly or created
2037 // implicitly. This can happen with a qualified call to a member
2038 // function, e.g., X::f(). We use a NULL object as the implied
2039 // object argument (C++ [over.call.func]p3).
2040 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2041 SuppressUserConversions, ForceRValue);
2042 return;
2043 }
2044 // We treat a constructor like a non-member function, since its object
2045 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002046 }
2047
2048
Douglas Gregord2baafd2008-10-21 16:13:35 +00002049 // Add this candidate
2050 CandidateSet.push_back(OverloadCandidate());
2051 OverloadCandidate& Candidate = CandidateSet.back();
2052 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002053 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002054 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002055 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002056
2057 unsigned NumArgsInProto = Proto->getNumArgs();
2058
2059 // (C++ 13.3.2p2): A candidate function having fewer than m
2060 // parameters is viable only if it has an ellipsis in its parameter
2061 // list (8.3.5).
2062 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2063 Candidate.Viable = false;
2064 return;
2065 }
2066
2067 // (C++ 13.3.2p2): A candidate function having more than m parameters
2068 // is viable only if the (m+1)st parameter has a default argument
2069 // (8.3.6). For the purposes of overload resolution, the
2070 // parameter list is truncated on the right, so that there are
2071 // exactly m parameters.
2072 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2073 if (NumArgs < MinRequiredArgs) {
2074 // Not enough arguments.
2075 Candidate.Viable = false;
2076 return;
2077 }
2078
2079 // Determine the implicit conversion sequences for each of the
2080 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002081 Candidate.Conversions.resize(NumArgs);
2082 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2083 if (ArgIdx < NumArgsInProto) {
2084 // (C++ 13.3.2p3): for F to be a viable function, there shall
2085 // exist for each argument an implicit conversion sequence
2086 // (13.3.3.1) that converts that argument to the corresponding
2087 // parameter of F.
2088 QualType ParamType = Proto->getArgType(ArgIdx);
2089 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002090 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002091 SuppressUserConversions, ForceRValue);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002092 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002093 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002094 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002095 break;
2096 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002097 } else {
2098 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2099 // argument for which there is no corresponding parameter is
2100 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2101 Candidate.Conversions[ArgIdx].ConversionKind
2102 = ImplicitConversionSequence::EllipsisConversion;
2103 }
2104 }
2105}
2106
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002107/// \brief Add all of the function declarations in the given function set to
2108/// the overload canddiate set.
2109void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2110 Expr **Args, unsigned NumArgs,
2111 OverloadCandidateSet& CandidateSet,
2112 bool SuppressUserConversions) {
2113 for (FunctionSet::const_iterator F = Functions.begin(),
2114 FEnd = Functions.end();
2115 F != FEnd; ++F)
2116 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2117 SuppressUserConversions);
2118}
2119
Douglas Gregor5ed15042008-11-18 23:14:02 +00002120/// AddMethodCandidate - Adds the given C++ member function to the set
2121/// of candidate functions, using the given function call arguments
2122/// and the object argument (@c Object). For example, in a call
2123/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2124/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2125/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002126/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2127/// a slightly hacky way to implement the overloading rules for elidable copy
2128/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002129void
2130Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2131 Expr **Args, unsigned NumArgs,
2132 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002133 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002134{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002135 const FunctionProtoType* Proto
2136 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002137 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002138 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002139 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002140 assert(!isa<CXXConstructorDecl>(Method) &&
2141 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002142
2143 // Add this candidate
2144 CandidateSet.push_back(OverloadCandidate());
2145 OverloadCandidate& Candidate = CandidateSet.back();
2146 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002147 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002148 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002149
2150 unsigned NumArgsInProto = Proto->getNumArgs();
2151
2152 // (C++ 13.3.2p2): A candidate function having fewer than m
2153 // parameters is viable only if it has an ellipsis in its parameter
2154 // list (8.3.5).
2155 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2156 Candidate.Viable = false;
2157 return;
2158 }
2159
2160 // (C++ 13.3.2p2): A candidate function having more than m parameters
2161 // is viable only if the (m+1)st parameter has a default argument
2162 // (8.3.6). For the purposes of overload resolution, the
2163 // parameter list is truncated on the right, so that there are
2164 // exactly m parameters.
2165 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2166 if (NumArgs < MinRequiredArgs) {
2167 // Not enough arguments.
2168 Candidate.Viable = false;
2169 return;
2170 }
2171
2172 Candidate.Viable = true;
2173 Candidate.Conversions.resize(NumArgs + 1);
2174
Douglas Gregor3257fb52008-12-22 05:46:06 +00002175 if (Method->isStatic() || !Object)
2176 // The implicit object argument is ignored.
2177 Candidate.IgnoreObjectArgument = true;
2178 else {
2179 // Determine the implicit conversion sequence for the object
2180 // parameter.
2181 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2182 if (Candidate.Conversions[0].ConversionKind
2183 == ImplicitConversionSequence::BadConversion) {
2184 Candidate.Viable = false;
2185 return;
2186 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002187 }
2188
2189 // Determine the implicit conversion sequences for each of the
2190 // arguments.
2191 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2192 if (ArgIdx < NumArgsInProto) {
2193 // (C++ 13.3.2p3): for F to be a viable function, there shall
2194 // exist for each argument an implicit conversion sequence
2195 // (13.3.3.1) that converts that argument to the corresponding
2196 // parameter of F.
2197 QualType ParamType = Proto->getArgType(ArgIdx);
2198 Candidate.Conversions[ArgIdx + 1]
2199 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002200 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002201 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2202 == ImplicitConversionSequence::BadConversion) {
2203 Candidate.Viable = false;
2204 break;
2205 }
2206 } else {
2207 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2208 // argument for which there is no corresponding parameter is
2209 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2210 Candidate.Conversions[ArgIdx + 1].ConversionKind
2211 = ImplicitConversionSequence::EllipsisConversion;
2212 }
2213 }
2214}
2215
Douglas Gregor60714f92008-11-07 22:36:19 +00002216/// AddConversionCandidate - Add a C++ conversion function as a
2217/// candidate in the candidate set (C++ [over.match.conv],
2218/// C++ [over.match.copy]). From is the expression we're converting from,
2219/// and ToType is the type that we're eventually trying to convert to
2220/// (which may or may not be the same type as the type that the
2221/// conversion function produces).
2222void
2223Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2224 Expr *From, QualType ToType,
2225 OverloadCandidateSet& CandidateSet) {
2226 // Add this candidate
2227 CandidateSet.push_back(OverloadCandidate());
2228 OverloadCandidate& Candidate = CandidateSet.back();
2229 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002230 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002231 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002232 Candidate.FinalConversion.setAsIdentityConversion();
2233 Candidate.FinalConversion.FromTypePtr
2234 = Conversion->getConversionType().getAsOpaquePtr();
2235 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2236
Douglas Gregor5ed15042008-11-18 23:14:02 +00002237 // Determine the implicit conversion sequence for the implicit
2238 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002239 Candidate.Viable = true;
2240 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002241 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002242
Douglas Gregor60714f92008-11-07 22:36:19 +00002243 if (Candidate.Conversions[0].ConversionKind
2244 == ImplicitConversionSequence::BadConversion) {
2245 Candidate.Viable = false;
2246 return;
2247 }
2248
2249 // To determine what the conversion from the result of calling the
2250 // conversion function to the type we're eventually trying to
2251 // convert to (ToType), we need to synthesize a call to the
2252 // conversion function and attempt copy initialization from it. This
2253 // makes sure that we get the right semantics with respect to
2254 // lvalues/rvalues and the type. Fortunately, we can allocate this
2255 // call on the stack and we don't need its arguments to be
2256 // well-formed.
2257 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2258 SourceLocation());
2259 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregor70d26122008-11-12 17:17:38 +00002260 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002261
2262 // Note that it is safe to allocate CallExpr on the stack here because
2263 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2264 // allocator).
2265 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002266 Conversion->getConversionType().getNonReferenceType(),
2267 SourceLocation());
2268 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2269 switch (ICS.ConversionKind) {
2270 case ImplicitConversionSequence::StandardConversion:
2271 Candidate.FinalConversion = ICS.Standard;
2272 break;
2273
2274 case ImplicitConversionSequence::BadConversion:
2275 Candidate.Viable = false;
2276 break;
2277
2278 default:
2279 assert(false &&
2280 "Can only end up with a standard conversion sequence or failure");
2281 }
2282}
2283
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002284/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2285/// converts the given @c Object to a function pointer via the
2286/// conversion function @c Conversion, and then attempts to call it
2287/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2288/// the type of function that we'll eventually be calling.
2289void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002290 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002291 Expr *Object, Expr **Args, unsigned NumArgs,
2292 OverloadCandidateSet& CandidateSet) {
2293 CandidateSet.push_back(OverloadCandidate());
2294 OverloadCandidate& Candidate = CandidateSet.back();
2295 Candidate.Function = 0;
2296 Candidate.Surrogate = Conversion;
2297 Candidate.Viable = true;
2298 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002299 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002300 Candidate.Conversions.resize(NumArgs + 1);
2301
2302 // Determine the implicit conversion sequence for the implicit
2303 // object parameter.
2304 ImplicitConversionSequence ObjectInit
2305 = TryObjectArgumentInitialization(Object, Conversion);
2306 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2307 Candidate.Viable = false;
2308 return;
2309 }
2310
2311 // The first conversion is actually a user-defined conversion whose
2312 // first conversion is ObjectInit's standard conversion (which is
2313 // effectively a reference binding). Record it as such.
2314 Candidate.Conversions[0].ConversionKind
2315 = ImplicitConversionSequence::UserDefinedConversion;
2316 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2317 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2318 Candidate.Conversions[0].UserDefined.After
2319 = Candidate.Conversions[0].UserDefined.Before;
2320 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2321
2322 // Find the
2323 unsigned NumArgsInProto = Proto->getNumArgs();
2324
2325 // (C++ 13.3.2p2): A candidate function having fewer than m
2326 // parameters is viable only if it has an ellipsis in its parameter
2327 // list (8.3.5).
2328 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2329 Candidate.Viable = false;
2330 return;
2331 }
2332
2333 // Function types don't have any default arguments, so just check if
2334 // we have enough arguments.
2335 if (NumArgs < NumArgsInProto) {
2336 // Not enough arguments.
2337 Candidate.Viable = false;
2338 return;
2339 }
2340
2341 // Determine the implicit conversion sequences for each of the
2342 // arguments.
2343 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2344 if (ArgIdx < NumArgsInProto) {
2345 // (C++ 13.3.2p3): for F to be a viable function, there shall
2346 // exist for each argument an implicit conversion sequence
2347 // (13.3.3.1) that converts that argument to the corresponding
2348 // parameter of F.
2349 QualType ParamType = Proto->getArgType(ArgIdx);
2350 Candidate.Conversions[ArgIdx + 1]
2351 = TryCopyInitialization(Args[ArgIdx], ParamType,
2352 /*SuppressUserConversions=*/false);
2353 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2354 == ImplicitConversionSequence::BadConversion) {
2355 Candidate.Viable = false;
2356 break;
2357 }
2358 } else {
2359 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2360 // argument for which there is no corresponding parameter is
2361 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2362 Candidate.Conversions[ArgIdx + 1].ConversionKind
2363 = ImplicitConversionSequence::EllipsisConversion;
2364 }
2365 }
2366}
2367
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002368// FIXME: This will eventually be removed, once we've migrated all of
2369// the operator overloading logic over to the scheme used by binary
2370// operators, which works for template instantiation.
2371void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002372 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002373 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002374 OverloadCandidateSet& CandidateSet,
2375 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002376
2377 FunctionSet Functions;
2378
2379 QualType T1 = Args[0]->getType();
2380 QualType T2;
2381 if (NumArgs > 1)
2382 T2 = Args[1]->getType();
2383
2384 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2385 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2386 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2387 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2388 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2389 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2390}
2391
2392/// \brief Add overload candidates for overloaded operators that are
2393/// member functions.
2394///
2395/// Add the overloaded operator candidates that are member functions
2396/// for the operator Op that was used in an operator expression such
2397/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2398/// CandidateSet will store the added overload candidates. (C++
2399/// [over.match.oper]).
2400void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2401 SourceLocation OpLoc,
2402 Expr **Args, unsigned NumArgs,
2403 OverloadCandidateSet& CandidateSet,
2404 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002405 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2406
2407 // C++ [over.match.oper]p3:
2408 // For a unary operator @ with an operand of a type whose
2409 // cv-unqualified version is T1, and for a binary operator @ with
2410 // a left operand of a type whose cv-unqualified version is T1 and
2411 // a right operand of a type whose cv-unqualified version is T2,
2412 // three sets of candidate functions, designated member
2413 // candidates, non-member candidates and built-in candidates, are
2414 // constructed as follows:
2415 QualType T1 = Args[0]->getType();
2416 QualType T2;
2417 if (NumArgs > 1)
2418 T2 = Args[1]->getType();
2419
2420 // -- If T1 is a class type, the set of member candidates is the
2421 // result of the qualified lookup of T1::operator@
2422 // (13.3.1.1.1); otherwise, the set of member candidates is
2423 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002424 // FIXME: Lookup in base classes, too!
Douglas Gregor5ed15042008-11-18 23:14:02 +00002425 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002426 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002427 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002428 Oper != OperEnd; ++Oper)
2429 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2430 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002431 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002432 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002433}
2434
Douglas Gregor70d26122008-11-12 17:17:38 +00002435/// AddBuiltinCandidate - Add a candidate for a built-in
2436/// operator. ResultTy and ParamTys are the result and parameter types
2437/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002438/// arguments being passed to the candidate. IsAssignmentOperator
2439/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002440/// operator. NumContextualBoolArguments is the number of arguments
2441/// (at the beginning of the argument list) that will be contextually
2442/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002443void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2444 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002445 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002446 bool IsAssignmentOperator,
2447 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002448 // Add this candidate
2449 CandidateSet.push_back(OverloadCandidate());
2450 OverloadCandidate& Candidate = CandidateSet.back();
2451 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002452 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002453 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002454 Candidate.BuiltinTypes.ResultTy = ResultTy;
2455 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2456 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2457
2458 // Determine the implicit conversion sequences for each of the
2459 // arguments.
2460 Candidate.Viable = true;
2461 Candidate.Conversions.resize(NumArgs);
2462 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002463 // C++ [over.match.oper]p4:
2464 // For the built-in assignment operators, conversions of the
2465 // left operand are restricted as follows:
2466 // -- no temporaries are introduced to hold the left operand, and
2467 // -- no user-defined conversions are applied to the left
2468 // operand to achieve a type match with the left-most
2469 // parameter of a built-in candidate.
2470 //
2471 // We block these conversions by turning off user-defined
2472 // conversions, since that is the only way that initialization of
2473 // a reference to a non-class type can occur from something that
2474 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002475 if (ArgIdx < NumContextualBoolArguments) {
2476 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2477 "Contextual conversion to bool requires bool type");
2478 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2479 } else {
2480 Candidate.Conversions[ArgIdx]
2481 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2482 ArgIdx == 0 && IsAssignmentOperator);
2483 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002484 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002485 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002486 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002487 break;
2488 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002489 }
2490}
2491
2492/// BuiltinCandidateTypeSet - A set of types that will be used for the
2493/// candidate operator functions for built-in operators (C++
2494/// [over.built]). The types are separated into pointer types and
2495/// enumeration types.
2496class BuiltinCandidateTypeSet {
2497 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002498 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002499
2500 /// PointerTypes - The set of pointer types that will be used in the
2501 /// built-in candidates.
2502 TypeSet PointerTypes;
2503
Sebastian Redl674d1b72009-04-19 21:53:20 +00002504 /// MemberPointerTypes - The set of member pointer types that will be
2505 /// used in the built-in candidates.
2506 TypeSet MemberPointerTypes;
2507
Douglas Gregor70d26122008-11-12 17:17:38 +00002508 /// EnumerationTypes - The set of enumeration types that will be
2509 /// used in the built-in candidates.
2510 TypeSet EnumerationTypes;
2511
2512 /// Context - The AST context in which we will build the type sets.
2513 ASTContext &Context;
2514
Sebastian Redl674d1b72009-04-19 21:53:20 +00002515 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2516 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002517
2518public:
2519 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002520 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002521
2522 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2523
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002524 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2525 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002526
2527 /// pointer_begin - First pointer type found;
2528 iterator pointer_begin() { return PointerTypes.begin(); }
2529
Sebastian Redl674d1b72009-04-19 21:53:20 +00002530 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002531 iterator pointer_end() { return PointerTypes.end(); }
2532
Sebastian Redl674d1b72009-04-19 21:53:20 +00002533 /// member_pointer_begin - First member pointer type found;
2534 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2535
2536 /// member_pointer_end - Past the last member pointer type found;
2537 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2538
Douglas Gregor70d26122008-11-12 17:17:38 +00002539 /// enumeration_begin - First enumeration type found;
2540 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2541
Sebastian Redl674d1b72009-04-19 21:53:20 +00002542 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002543 iterator enumeration_end() { return EnumerationTypes.end(); }
2544};
2545
Sebastian Redl674d1b72009-04-19 21:53:20 +00002546/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002547/// the set of pointer types along with any more-qualified variants of
2548/// that type. For example, if @p Ty is "int const *", this routine
2549/// will add "int const *", "int const volatile *", "int const
2550/// restrict *", and "int const volatile restrict *" to the set of
2551/// pointer types. Returns true if the add of @p Ty itself succeeded,
2552/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002553bool
2554BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002555 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002556 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002557 return false;
2558
2559 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2560 QualType PointeeTy = PointerTy->getPointeeType();
2561 // FIXME: Optimize this so that we don't keep trying to add the same types.
2562
2563 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2564 // with all pointer conversions that don't cast away constness?
2565 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002566 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002567 (Context.getPointerType(PointeeTy.withConst()));
2568 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002569 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002570 (Context.getPointerType(PointeeTy.withVolatile()));
2571 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002572 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002573 (Context.getPointerType(PointeeTy.withRestrict()));
2574 }
2575
2576 return true;
2577}
2578
Sebastian Redl674d1b72009-04-19 21:53:20 +00002579/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2580/// to the set of pointer types along with any more-qualified variants of
2581/// that type. For example, if @p Ty is "int const *", this routine
2582/// will add "int const *", "int const volatile *", "int const
2583/// restrict *", and "int const volatile restrict *" to the set of
2584/// pointer types. Returns true if the add of @p Ty itself succeeded,
2585/// false otherwise.
2586bool
2587BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2588 QualType Ty) {
2589 // Insert this type.
2590 if (!MemberPointerTypes.insert(Ty))
2591 return false;
2592
2593 if (const MemberPointerType *PointerTy = Ty->getAsMemberPointerType()) {
2594 QualType PointeeTy = PointerTy->getPointeeType();
2595 const Type *ClassTy = PointerTy->getClass();
2596 // FIXME: Optimize this so that we don't keep trying to add the same types.
2597
2598 if (!PointeeTy.isConstQualified())
2599 AddMemberPointerWithMoreQualifiedTypeVariants
2600 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2601 if (!PointeeTy.isVolatileQualified())
2602 AddMemberPointerWithMoreQualifiedTypeVariants
2603 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2604 if (!PointeeTy.isRestrictQualified())
2605 AddMemberPointerWithMoreQualifiedTypeVariants
2606 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2607 }
2608
2609 return true;
2610}
2611
Douglas Gregor70d26122008-11-12 17:17:38 +00002612/// AddTypesConvertedFrom - Add each of the types to which the type @p
2613/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002614/// primarily interested in pointer types and enumeration types. We also
2615/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002616/// AllowUserConversions is true if we should look at the conversion
2617/// functions of a class type, and AllowExplicitConversions if we
2618/// should also include the explicit conversion functions of a class
2619/// type.
2620void
2621BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2622 bool AllowUserConversions,
2623 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002624 // Only deal with canonical types.
2625 Ty = Context.getCanonicalType(Ty);
2626
2627 // Look through reference types; they aren't part of the type of an
2628 // expression for the purposes of conversions.
2629 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2630 Ty = RefTy->getPointeeType();
2631
2632 // We don't care about qualifiers on the type.
2633 Ty = Ty.getUnqualifiedType();
2634
2635 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2636 QualType PointeeTy = PointerTy->getPointeeType();
2637
2638 // Insert our type, and its more-qualified variants, into the set
2639 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002640 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002641 return;
2642
2643 // Add 'cv void*' to our set of types.
2644 if (!Ty->isVoidType()) {
2645 QualType QualVoid
2646 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002647 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002648 }
2649
2650 // If this is a pointer to a class type, add pointers to its bases
2651 // (with the same level of cv-qualification as the original
2652 // derived class, of course).
2653 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2654 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2655 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2656 Base != ClassDecl->bases_end(); ++Base) {
2657 QualType BaseTy = Context.getCanonicalType(Base->getType());
2658 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2659
2660 // Add the pointer type, recursively, so that we get all of
2661 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002662 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002663 }
2664 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002665 } else if (Ty->isMemberPointerType()) {
2666 // Member pointers are far easier, since the pointee can't be converted.
2667 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2668 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002669 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002670 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002671 } else if (AllowUserConversions) {
2672 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2673 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2674 // FIXME: Visit conversion functions in the base classes, too.
2675 OverloadedFunctionDecl *Conversions
2676 = ClassDecl->getConversionFunctions();
2677 for (OverloadedFunctionDecl::function_iterator Func
2678 = Conversions->function_begin();
2679 Func != Conversions->function_end(); ++Func) {
2680 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002681 if (AllowExplicitConversions || !Conv->isExplicit())
2682 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002683 }
2684 }
2685 }
2686}
2687
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002688/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2689/// operator overloads to the candidate set (C++ [over.built]), based
2690/// on the operator @p Op and the arguments given. For example, if the
2691/// operator is a binary '+', this routine might add "int
2692/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002693void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002694Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2695 Expr **Args, unsigned NumArgs,
2696 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002697 // The set of "promoted arithmetic types", which are the arithmetic
2698 // types are that preserved by promotion (C++ [over.built]p2). Note
2699 // that the first few of these types are the promoted integral
2700 // types; these types need to be first.
2701 // FIXME: What about complex?
2702 const unsigned FirstIntegralType = 0;
2703 const unsigned LastIntegralType = 13;
2704 const unsigned FirstPromotedIntegralType = 7,
2705 LastPromotedIntegralType = 13;
2706 const unsigned FirstPromotedArithmeticType = 7,
2707 LastPromotedArithmeticType = 16;
2708 const unsigned NumArithmeticTypes = 16;
2709 QualType ArithmeticTypes[NumArithmeticTypes] = {
2710 Context.BoolTy, Context.CharTy, Context.WCharTy,
2711 Context.SignedCharTy, Context.ShortTy,
2712 Context.UnsignedCharTy, Context.UnsignedShortTy,
2713 Context.IntTy, Context.LongTy, Context.LongLongTy,
2714 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2715 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2716 };
2717
2718 // Find all of the types that the arguments can convert to, but only
2719 // if the operator we're looking at has built-in operator candidates
2720 // that make use of these types.
2721 BuiltinCandidateTypeSet CandidateTypes(Context);
2722 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2723 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002724 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002725 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002726 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00002727 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002728 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002729 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2730 true,
2731 (Op == OO_Exclaim ||
2732 Op == OO_AmpAmp ||
2733 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002734 }
2735
2736 bool isComparison = false;
2737 switch (Op) {
2738 case OO_None:
2739 case NUM_OVERLOADED_OPERATORS:
2740 assert(false && "Expected an overloaded operator");
2741 break;
2742
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002743 case OO_Star: // '*' is either unary or binary
2744 if (NumArgs == 1)
2745 goto UnaryStar;
2746 else
2747 goto BinaryStar;
2748 break;
2749
2750 case OO_Plus: // '+' is either unary or binary
2751 if (NumArgs == 1)
2752 goto UnaryPlus;
2753 else
2754 goto BinaryPlus;
2755 break;
2756
2757 case OO_Minus: // '-' is either unary or binary
2758 if (NumArgs == 1)
2759 goto UnaryMinus;
2760 else
2761 goto BinaryMinus;
2762 break;
2763
2764 case OO_Amp: // '&' is either unary or binary
2765 if (NumArgs == 1)
2766 goto UnaryAmp;
2767 else
2768 goto BinaryAmp;
2769
2770 case OO_PlusPlus:
2771 case OO_MinusMinus:
2772 // C++ [over.built]p3:
2773 //
2774 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2775 // is either volatile or empty, there exist candidate operator
2776 // functions of the form
2777 //
2778 // VQ T& operator++(VQ T&);
2779 // T operator++(VQ T&, int);
2780 //
2781 // C++ [over.built]p4:
2782 //
2783 // For every pair (T, VQ), where T is an arithmetic type other
2784 // than bool, and VQ is either volatile or empty, there exist
2785 // candidate operator functions of the form
2786 //
2787 // VQ T& operator--(VQ T&);
2788 // T operator--(VQ T&, int);
2789 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2790 Arith < NumArithmeticTypes; ++Arith) {
2791 QualType ArithTy = ArithmeticTypes[Arith];
2792 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00002793 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002794
2795 // Non-volatile version.
2796 if (NumArgs == 1)
2797 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2798 else
2799 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2800
2801 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00002802 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002803 if (NumArgs == 1)
2804 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2805 else
2806 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2807 }
2808
2809 // C++ [over.built]p5:
2810 //
2811 // For every pair (T, VQ), where T is a cv-qualified or
2812 // cv-unqualified object type, and VQ is either volatile or
2813 // empty, there exist candidate operator functions of the form
2814 //
2815 // T*VQ& operator++(T*VQ&);
2816 // T*VQ& operator--(T*VQ&);
2817 // T* operator++(T*VQ&, int);
2818 // T* operator--(T*VQ&, int);
2819 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2820 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2821 // Skip pointer types that aren't pointers to object types.
Douglas Gregor26ea1222009-03-24 20:32:41 +00002822 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002823 continue;
2824
2825 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002826 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002827 };
2828
2829 // Without volatile
2830 if (NumArgs == 1)
2831 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2832 else
2833 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2834
2835 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2836 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00002837 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002838 if (NumArgs == 1)
2839 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2840 else
2841 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2842 }
2843 }
2844 break;
2845
2846 UnaryStar:
2847 // C++ [over.built]p6:
2848 // For every cv-qualified or cv-unqualified object type T, there
2849 // exist candidate operator functions of the form
2850 //
2851 // T& operator*(T*);
2852 //
2853 // C++ [over.built]p7:
2854 // For every function type T, there exist candidate operator
2855 // functions of the form
2856 // T& operator*(T*);
2857 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2858 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2859 QualType ParamTy = *Ptr;
2860 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00002861 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002862 &ParamTy, Args, 1, CandidateSet);
2863 }
2864 break;
2865
2866 UnaryPlus:
2867 // C++ [over.built]p8:
2868 // For every type T, there exist candidate operator functions of
2869 // the form
2870 //
2871 // T* operator+(T*);
2872 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2873 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2874 QualType ParamTy = *Ptr;
2875 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2876 }
2877
2878 // Fall through
2879
2880 UnaryMinus:
2881 // C++ [over.built]p9:
2882 // For every promoted arithmetic type T, there exist candidate
2883 // operator functions of the form
2884 //
2885 // T operator+(T);
2886 // T operator-(T);
2887 for (unsigned Arith = FirstPromotedArithmeticType;
2888 Arith < LastPromotedArithmeticType; ++Arith) {
2889 QualType ArithTy = ArithmeticTypes[Arith];
2890 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2891 }
2892 break;
2893
2894 case OO_Tilde:
2895 // C++ [over.built]p10:
2896 // For every promoted integral type T, there exist candidate
2897 // operator functions of the form
2898 //
2899 // T operator~(T);
2900 for (unsigned Int = FirstPromotedIntegralType;
2901 Int < LastPromotedIntegralType; ++Int) {
2902 QualType IntTy = ArithmeticTypes[Int];
2903 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2904 }
2905 break;
2906
Douglas Gregor70d26122008-11-12 17:17:38 +00002907 case OO_New:
2908 case OO_Delete:
2909 case OO_Array_New:
2910 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00002911 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002912 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00002913 break;
2914
2915 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002916 UnaryAmp:
2917 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00002918 // C++ [over.match.oper]p3:
2919 // -- For the operator ',', the unary operator '&', or the
2920 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00002921 break;
2922
2923 case OO_Less:
2924 case OO_Greater:
2925 case OO_LessEqual:
2926 case OO_GreaterEqual:
2927 case OO_EqualEqual:
2928 case OO_ExclaimEqual:
2929 // C++ [over.built]p15:
2930 //
2931 // For every pointer or enumeration type T, there exist
2932 // candidate operator functions of the form
2933 //
2934 // bool operator<(T, T);
2935 // bool operator>(T, T);
2936 // bool operator<=(T, T);
2937 // bool operator>=(T, T);
2938 // bool operator==(T, T);
2939 // bool operator!=(T, T);
2940 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2941 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2942 QualType ParamTypes[2] = { *Ptr, *Ptr };
2943 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2944 }
2945 for (BuiltinCandidateTypeSet::iterator Enum
2946 = CandidateTypes.enumeration_begin();
2947 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2948 QualType ParamTypes[2] = { *Enum, *Enum };
2949 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2950 }
2951
2952 // Fall through.
2953 isComparison = true;
2954
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002955 BinaryPlus:
2956 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00002957 if (!isComparison) {
2958 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2959
2960 // C++ [over.built]p13:
2961 //
2962 // For every cv-qualified or cv-unqualified object type T
2963 // there exist candidate operator functions of the form
2964 //
2965 // T* operator+(T*, ptrdiff_t);
2966 // T& operator[](T*, ptrdiff_t); [BELOW]
2967 // T* operator-(T*, ptrdiff_t);
2968 // T* operator+(ptrdiff_t, T*);
2969 // T& operator[](ptrdiff_t, T*); [BELOW]
2970 //
2971 // C++ [over.built]p14:
2972 //
2973 // For every T, where T is a pointer to object type, there
2974 // exist candidate operator functions of the form
2975 //
2976 // ptrdiff_t operator-(T, T);
2977 for (BuiltinCandidateTypeSet::iterator Ptr
2978 = CandidateTypes.pointer_begin();
2979 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2980 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2981
2982 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2983 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2984
2985 if (Op == OO_Plus) {
2986 // T* operator+(ptrdiff_t, T*);
2987 ParamTypes[0] = ParamTypes[1];
2988 ParamTypes[1] = *Ptr;
2989 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2990 } else {
2991 // ptrdiff_t operator-(T, T);
2992 ParamTypes[1] = *Ptr;
2993 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2994 Args, 2, CandidateSet);
2995 }
2996 }
2997 }
2998 // Fall through
2999
Douglas Gregor70d26122008-11-12 17:17:38 +00003000 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003001 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003002 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003003 // C++ [over.built]p12:
3004 //
3005 // For every pair of promoted arithmetic types L and R, there
3006 // exist candidate operator functions of the form
3007 //
3008 // LR operator*(L, R);
3009 // LR operator/(L, R);
3010 // LR operator+(L, R);
3011 // LR operator-(L, R);
3012 // bool operator<(L, R);
3013 // bool operator>(L, R);
3014 // bool operator<=(L, R);
3015 // bool operator>=(L, R);
3016 // bool operator==(L, R);
3017 // bool operator!=(L, R);
3018 //
3019 // where LR is the result of the usual arithmetic conversions
3020 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003021 //
3022 // C++ [over.built]p24:
3023 //
3024 // For every pair of promoted arithmetic types L and R, there exist
3025 // candidate operator functions of the form
3026 //
3027 // LR operator?(bool, L, R);
3028 //
3029 // where LR is the result of the usual arithmetic conversions
3030 // between types L and R.
3031 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003032 for (unsigned Left = FirstPromotedArithmeticType;
3033 Left < LastPromotedArithmeticType; ++Left) {
3034 for (unsigned Right = FirstPromotedArithmeticType;
3035 Right < LastPromotedArithmeticType; ++Right) {
3036 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3037 QualType Result
3038 = isComparison? Context.BoolTy
3039 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3040 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3041 }
3042 }
3043 break;
3044
3045 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003046 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003047 case OO_Caret:
3048 case OO_Pipe:
3049 case OO_LessLess:
3050 case OO_GreaterGreater:
3051 // C++ [over.built]p17:
3052 //
3053 // For every pair of promoted integral types L and R, there
3054 // exist candidate operator functions of the form
3055 //
3056 // LR operator%(L, R);
3057 // LR operator&(L, R);
3058 // LR operator^(L, R);
3059 // LR operator|(L, R);
3060 // L operator<<(L, R);
3061 // L operator>>(L, R);
3062 //
3063 // where LR is the result of the usual arithmetic conversions
3064 // between types L and R.
3065 for (unsigned Left = FirstPromotedIntegralType;
3066 Left < LastPromotedIntegralType; ++Left) {
3067 for (unsigned Right = FirstPromotedIntegralType;
3068 Right < LastPromotedIntegralType; ++Right) {
3069 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3070 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3071 ? LandR[0]
3072 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3073 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3074 }
3075 }
3076 break;
3077
3078 case OO_Equal:
3079 // C++ [over.built]p20:
3080 //
3081 // For every pair (T, VQ), where T is an enumeration or
3082 // (FIXME:) pointer to member type and VQ is either volatile or
3083 // empty, there exist candidate operator functions of the form
3084 //
3085 // VQ T& operator=(VQ T&, T);
3086 for (BuiltinCandidateTypeSet::iterator Enum
3087 = CandidateTypes.enumeration_begin();
3088 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3089 QualType ParamTypes[2];
3090
3091 // T& operator=(T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003092 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregor70d26122008-11-12 17:17:38 +00003093 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003094 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003095 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003096
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003097 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3098 // volatile T& operator=(volatile T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003099 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003100 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003101 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003102 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003103 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003104 }
3105 // Fall through.
3106
3107 case OO_PlusEqual:
3108 case OO_MinusEqual:
3109 // C++ [over.built]p19:
3110 //
3111 // For every pair (T, VQ), where T is any type and VQ is either
3112 // volatile or empty, there exist candidate operator functions
3113 // of the form
3114 //
3115 // T*VQ& operator=(T*VQ&, T*);
3116 //
3117 // C++ [over.built]p21:
3118 //
3119 // For every pair (T, VQ), where T is a cv-qualified or
3120 // cv-unqualified object type and VQ is either volatile or
3121 // empty, there exist candidate operator functions of the form
3122 //
3123 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3124 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3125 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3126 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3127 QualType ParamTypes[2];
3128 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3129
3130 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003131 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003132 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3133 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003134
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003135 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3136 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003137 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003138 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3139 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003140 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003141 }
3142 // Fall through.
3143
3144 case OO_StarEqual:
3145 case OO_SlashEqual:
3146 // C++ [over.built]p18:
3147 //
3148 // For every triple (L, VQ, R), where L is an arithmetic type,
3149 // VQ is either volatile or empty, and R is a promoted
3150 // arithmetic type, there exist candidate operator functions of
3151 // the form
3152 //
3153 // VQ L& operator=(VQ L&, R);
3154 // VQ L& operator*=(VQ L&, R);
3155 // VQ L& operator/=(VQ L&, R);
3156 // VQ L& operator+=(VQ L&, R);
3157 // VQ L& operator-=(VQ L&, R);
3158 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3159 for (unsigned Right = FirstPromotedArithmeticType;
3160 Right < LastPromotedArithmeticType; ++Right) {
3161 QualType ParamTypes[2];
3162 ParamTypes[1] = ArithmeticTypes[Right];
3163
3164 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003165 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003166 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3167 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003168
3169 // Add this built-in operator as a candidate (VQ is 'volatile').
3170 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003171 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003172 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3173 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003174 }
3175 }
3176 break;
3177
3178 case OO_PercentEqual:
3179 case OO_LessLessEqual:
3180 case OO_GreaterGreaterEqual:
3181 case OO_AmpEqual:
3182 case OO_CaretEqual:
3183 case OO_PipeEqual:
3184 // C++ [over.built]p22:
3185 //
3186 // For every triple (L, VQ, R), where L is an integral type, VQ
3187 // is either volatile or empty, and R is a promoted integral
3188 // type, there exist candidate operator functions of the form
3189 //
3190 // VQ L& operator%=(VQ L&, R);
3191 // VQ L& operator<<=(VQ L&, R);
3192 // VQ L& operator>>=(VQ L&, R);
3193 // VQ L& operator&=(VQ L&, R);
3194 // VQ L& operator^=(VQ L&, R);
3195 // VQ L& operator|=(VQ L&, R);
3196 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3197 for (unsigned Right = FirstPromotedIntegralType;
3198 Right < LastPromotedIntegralType; ++Right) {
3199 QualType ParamTypes[2];
3200 ParamTypes[1] = ArithmeticTypes[Right];
3201
3202 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003203 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003204 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3205
3206 // Add this built-in operator as a candidate (VQ is 'volatile').
3207 ParamTypes[0] = ArithmeticTypes[Left];
3208 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003209 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003210 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3211 }
3212 }
3213 break;
3214
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003215 case OO_Exclaim: {
3216 // C++ [over.operator]p23:
3217 //
3218 // There also exist candidate operator functions of the form
3219 //
3220 // bool operator!(bool);
3221 // bool operator&&(bool, bool); [BELOW]
3222 // bool operator||(bool, bool); [BELOW]
3223 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003224 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3225 /*IsAssignmentOperator=*/false,
3226 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003227 break;
3228 }
3229
Douglas Gregor70d26122008-11-12 17:17:38 +00003230 case OO_AmpAmp:
3231 case OO_PipePipe: {
3232 // C++ [over.operator]p23:
3233 //
3234 // There also exist candidate operator functions of the form
3235 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003236 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003237 // bool operator&&(bool, bool);
3238 // bool operator||(bool, bool);
3239 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003240 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3241 /*IsAssignmentOperator=*/false,
3242 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003243 break;
3244 }
3245
3246 case OO_Subscript:
3247 // C++ [over.built]p13:
3248 //
3249 // For every cv-qualified or cv-unqualified object type T there
3250 // exist candidate operator functions of the form
3251 //
3252 // T* operator+(T*, ptrdiff_t); [ABOVE]
3253 // T& operator[](T*, ptrdiff_t);
3254 // T* operator-(T*, ptrdiff_t); [ABOVE]
3255 // T* operator+(ptrdiff_t, T*); [ABOVE]
3256 // T& operator[](ptrdiff_t, T*);
3257 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3258 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3259 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3260 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003261 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003262
3263 // T& operator[](T*, ptrdiff_t)
3264 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3265
3266 // T& operator[](ptrdiff_t, T*);
3267 ParamTypes[0] = ParamTypes[1];
3268 ParamTypes[1] = *Ptr;
3269 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3270 }
3271 break;
3272
3273 case OO_ArrowStar:
3274 // FIXME: No support for pointer-to-members yet.
3275 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003276
3277 case OO_Conditional:
3278 // Note that we don't consider the first argument, since it has been
3279 // contextually converted to bool long ago. The candidates below are
3280 // therefore added as binary.
3281 //
3282 // C++ [over.built]p24:
3283 // For every type T, where T is a pointer or pointer-to-member type,
3284 // there exist candidate operator functions of the form
3285 //
3286 // T operator?(bool, T, T);
3287 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003288 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3289 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3290 QualType ParamTypes[2] = { *Ptr, *Ptr };
3291 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3292 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003293 for (BuiltinCandidateTypeSet::iterator Ptr =
3294 CandidateTypes.member_pointer_begin(),
3295 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3296 QualType ParamTypes[2] = { *Ptr, *Ptr };
3297 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3298 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003299 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003300 }
3301}
3302
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003303/// \brief Add function candidates found via argument-dependent lookup
3304/// to the set of overloading candidates.
3305///
3306/// This routine performs argument-dependent name lookup based on the
3307/// given function name (which may also be an operator name) and adds
3308/// all of the overload candidates found by ADL to the overload
3309/// candidate set (C++ [basic.lookup.argdep]).
3310void
3311Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3312 Expr **Args, unsigned NumArgs,
3313 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003314 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003315
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003316 // Record all of the function candidates that we've already
3317 // added to the overload set, so that we don't add those same
3318 // candidates a second time.
3319 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3320 CandEnd = CandidateSet.end();
3321 Cand != CandEnd; ++Cand)
3322 if (Cand->Function)
3323 Functions.insert(Cand->Function);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003324
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003325 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003326
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003327 // Erase all of the candidates we already knew about.
3328 // FIXME: This is suboptimal. Is there a better way?
3329 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3330 CandEnd = CandidateSet.end();
3331 Cand != CandEnd; ++Cand)
3332 if (Cand->Function)
3333 Functions.erase(Cand->Function);
3334
3335 // For each of the ADL candidates we found, add it to the overload
3336 // set.
3337 for (FunctionSet::iterator Func = Functions.begin(),
3338 FuncEnd = Functions.end();
3339 Func != FuncEnd; ++Func)
3340 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003341}
3342
Douglas Gregord2baafd2008-10-21 16:13:35 +00003343/// isBetterOverloadCandidate - Determines whether the first overload
3344/// candidate is a better candidate than the second (C++ 13.3.3p1).
3345bool
3346Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3347 const OverloadCandidate& Cand2)
3348{
3349 // Define viable functions to be better candidates than non-viable
3350 // functions.
3351 if (!Cand2.Viable)
3352 return Cand1.Viable;
3353 else if (!Cand1.Viable)
3354 return false;
3355
Douglas Gregor3257fb52008-12-22 05:46:06 +00003356 // C++ [over.match.best]p1:
3357 //
3358 // -- if F is a static member function, ICS1(F) is defined such
3359 // that ICS1(F) is neither better nor worse than ICS1(G) for
3360 // any function G, and, symmetrically, ICS1(G) is neither
3361 // better nor worse than ICS1(F).
3362 unsigned StartArg = 0;
3363 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3364 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003365
3366 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3367 // function than another viable function F2 if for all arguments i,
3368 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3369 // then...
3370 unsigned NumArgs = Cand1.Conversions.size();
3371 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3372 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003373 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003374 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3375 Cand2.Conversions[ArgIdx])) {
3376 case ImplicitConversionSequence::Better:
3377 // Cand1 has a better conversion sequence.
3378 HasBetterConversion = true;
3379 break;
3380
3381 case ImplicitConversionSequence::Worse:
3382 // Cand1 can't be better than Cand2.
3383 return false;
3384
3385 case ImplicitConversionSequence::Indistinguishable:
3386 // Do nothing.
3387 break;
3388 }
3389 }
3390
3391 if (HasBetterConversion)
3392 return true;
3393
Douglas Gregor70d26122008-11-12 17:17:38 +00003394 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3395 // implemented, but they require template support.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003396
Douglas Gregor60714f92008-11-07 22:36:19 +00003397 // C++ [over.match.best]p1b4:
3398 //
3399 // -- the context is an initialization by user-defined conversion
3400 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3401 // from the return type of F1 to the destination type (i.e.,
3402 // the type of the entity being initialized) is a better
3403 // conversion sequence than the standard conversion sequence
3404 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003405 if (Cand1.Function && Cand2.Function &&
3406 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003407 isa<CXXConversionDecl>(Cand2.Function)) {
3408 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3409 Cand2.FinalConversion)) {
3410 case ImplicitConversionSequence::Better:
3411 // Cand1 has a better conversion sequence.
3412 return true;
3413
3414 case ImplicitConversionSequence::Worse:
3415 // Cand1 can't be better than Cand2.
3416 return false;
3417
3418 case ImplicitConversionSequence::Indistinguishable:
3419 // Do nothing
3420 break;
3421 }
3422 }
3423
Douglas Gregord2baafd2008-10-21 16:13:35 +00003424 return false;
3425}
3426
3427/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3428/// within an overload candidate set. If overloading is successful,
3429/// the result will be OR_Success and Best will be set to point to the
3430/// best viable function within the candidate set. Otherwise, one of
3431/// several kinds of errors will be returned; see
3432/// Sema::OverloadingResult.
3433Sema::OverloadingResult
3434Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3435 OverloadCandidateSet::iterator& Best)
3436{
3437 // Find the best viable function.
3438 Best = CandidateSet.end();
3439 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3440 Cand != CandidateSet.end(); ++Cand) {
3441 if (Cand->Viable) {
3442 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3443 Best = Cand;
3444 }
3445 }
3446
3447 // If we didn't find any viable functions, abort.
3448 if (Best == CandidateSet.end())
3449 return OR_No_Viable_Function;
3450
3451 // Make sure that this function is better than every other viable
3452 // function. If not, we have an ambiguity.
3453 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3454 Cand != CandidateSet.end(); ++Cand) {
3455 if (Cand->Viable &&
3456 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003457 !isBetterOverloadCandidate(*Best, *Cand)) {
3458 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003459 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003460 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003461 }
3462
3463 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003464 if (Best->Function &&
3465 (Best->Function->isDeleted() ||
3466 Best->Function->getAttr<UnavailableAttr>()))
3467 return OR_Deleted;
3468
3469 // If Best refers to a function that is either deleted (C++0x) or
3470 // unavailable (Clang extension) report an error.
3471
Douglas Gregord2baafd2008-10-21 16:13:35 +00003472 return OR_Success;
3473}
3474
3475/// PrintOverloadCandidates - When overload resolution fails, prints
3476/// diagnostic messages containing the candidates in the candidate
3477/// set. If OnlyViable is true, only viable candidates will be printed.
3478void
3479Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3480 bool OnlyViable)
3481{
3482 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3483 LastCand = CandidateSet.end();
3484 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003485 if (Cand->Viable || !OnlyViable) {
3486 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003487 if (Cand->Function->isDeleted() ||
3488 Cand->Function->getAttr<UnavailableAttr>()) {
3489 // Deleted or "unavailable" function.
3490 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3491 << Cand->Function->isDeleted();
3492 } else {
3493 // Normal function
3494 // FIXME: Give a better reason!
3495 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3496 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003497 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003498 // Desugar the type of the surrogate down to a function type,
3499 // retaining as many typedefs as possible while still showing
3500 // the function type (and, therefore, its parameter types).
3501 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003502 bool isLValueReference = false;
3503 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003504 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003505 if (const LValueReferenceType *FnTypeRef =
3506 FnType->getAsLValueReferenceType()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003507 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003508 isLValueReference = true;
3509 } else if (const RValueReferenceType *FnTypeRef =
3510 FnType->getAsRValueReferenceType()) {
3511 FnType = FnTypeRef->getPointeeType();
3512 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003513 }
3514 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3515 FnType = FnTypePtr->getPointeeType();
3516 isPointer = true;
3517 }
3518 // Desugar down to a function type.
3519 FnType = QualType(FnType->getAsFunctionType(), 0);
3520 // Reconstruct the pointer/reference as appropriate.
3521 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003522 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3523 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003524
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003525 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003526 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003527 } else {
3528 // FIXME: We need to get the identifier in here
3529 // FIXME: Do we want the error message to point at the
3530 // operator? (built-ins won't have a location)
3531 QualType FnType
3532 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3533 Cand->BuiltinTypes.ParamTypes,
3534 Cand->Conversions.size(),
3535 false, 0);
3536
Chris Lattner4bfd2232008-11-24 06:25:27 +00003537 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003538 }
3539 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003540 }
3541}
3542
Douglas Gregor45014fd2008-11-10 20:40:00 +00003543/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3544/// an overloaded function (C++ [over.over]), where @p From is an
3545/// expression with overloaded function type and @p ToType is the type
3546/// we're trying to resolve to. For example:
3547///
3548/// @code
3549/// int f(double);
3550/// int f(int);
3551///
3552/// int (*pfd)(double) = f; // selects f(double)
3553/// @endcode
3554///
3555/// This routine returns the resulting FunctionDecl if it could be
3556/// resolved, and NULL otherwise. When @p Complain is true, this
3557/// routine will emit diagnostics if there is an error.
3558FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003559Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003560 bool Complain) {
3561 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003562 bool IsMember = false;
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003563 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003564 FunctionType = ToTypePtr->getPointeeType();
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003565 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3566 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003567 else if (const MemberPointerType *MemTypePtr =
3568 ToType->getAsMemberPointerType()) {
3569 FunctionType = MemTypePtr->getPointeeType();
3570 IsMember = true;
3571 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003572
3573 // We only look at pointers or references to functions.
3574 if (!FunctionType->isFunctionType())
3575 return 0;
3576
3577 // Find the actual overloaded function declaration.
3578 OverloadedFunctionDecl *Ovl = 0;
3579
3580 // C++ [over.over]p1:
3581 // [...] [Note: any redundant set of parentheses surrounding the
3582 // overloaded function name is ignored (5.1). ]
3583 Expr *OvlExpr = From->IgnoreParens();
3584
3585 // C++ [over.over]p1:
3586 // [...] The overloaded function name can be preceded by the &
3587 // operator.
3588 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3589 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3590 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3591 }
3592
3593 // Try to dig out the overloaded function.
3594 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3595 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3596
3597 // If there's no overloaded function declaration, we're done.
3598 if (!Ovl)
3599 return 0;
3600
3601 // Look through all of the overloaded functions, searching for one
3602 // whose type matches exactly.
3603 // FIXME: When templates or using declarations come along, we'll actually
3604 // have to deal with duplicates, partial ordering, etc. For now, we
3605 // can just do a simple search.
3606 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3607 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3608 Fun != Ovl->function_end(); ++Fun) {
3609 // C++ [over.over]p3:
3610 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003611 // targets of type "pointer-to-function" or "reference-to-function."
3612 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003613 // type "pointer-to-member-function."
3614 // Note that according to DR 247, the containing class does not matter.
3615 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3616 // Skip non-static functions when converting to pointer, and static
3617 // when converting to member pointer.
3618 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003619 continue;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003620 } else if (IsMember)
3621 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003622
3623 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3624 return *Fun;
3625 }
3626
3627 return 0;
3628}
3629
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003630/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003631/// (which eventually refers to the declaration Func) and the call
3632/// arguments Args/NumArgs, attempt to resolve the function call down
3633/// to a specific function. If overload resolution succeeds, returns
3634/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003635/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003636/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003637FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003638 DeclarationName UnqualifiedName,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003639 SourceLocation LParenLoc,
3640 Expr **Args, unsigned NumArgs,
3641 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003642 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003643 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003644 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003645
3646 // Add the functions denoted by Callee to the set of candidate
3647 // functions. While we're doing so, track whether argument-dependent
3648 // lookup still applies, per:
3649 //
3650 // C++0x [basic.lookup.argdep]p3:
3651 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3652 // and let Y be the lookup set produced by argument dependent
3653 // lookup (defined as follows). If X contains
3654 //
3655 // -- a declaration of a class member, or
3656 //
3657 // -- a block-scope function declaration that is not a
3658 // using-declaration, or
3659 //
3660 // -- a declaration that is neither a function or a function
3661 // template
3662 //
3663 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003664 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003665 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3666 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3667 FuncEnd = Ovl->function_end();
3668 Func != FuncEnd; ++Func) {
3669 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3670
3671 if ((*Func)->getDeclContext()->isRecord() ||
3672 (*Func)->getDeclContext()->isFunctionOrMethod())
3673 ArgumentDependentLookup = false;
3674 }
3675 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3676 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3677
3678 if (Func->getDeclContext()->isRecord() ||
3679 Func->getDeclContext()->isFunctionOrMethod())
3680 ArgumentDependentLookup = false;
3681 }
3682
3683 if (Callee)
3684 UnqualifiedName = Callee->getDeclName();
3685
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003686 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003687 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003688 CandidateSet);
3689
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003690 OverloadCandidateSet::iterator Best;
3691 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003692 case OR_Success:
3693 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003694
3695 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00003696 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003697 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00003698 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003699 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3700 break;
3701
3702 case OR_Ambiguous:
3703 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003704 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003705 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3706 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00003707
3708 case OR_Deleted:
3709 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3710 << Best->Function->isDeleted()
3711 << UnqualifiedName
3712 << Fn->getSourceRange();
3713 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3714 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003715 }
3716
3717 // Overload resolution failed. Destroy all of the subexpressions and
3718 // return NULL.
3719 Fn->Destroy(Context);
3720 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3721 Args[Arg]->Destroy(Context);
3722 return 0;
3723}
3724
Douglas Gregorc78182d2009-03-13 23:49:33 +00003725/// \brief Create a unary operation that may resolve to an overloaded
3726/// operator.
3727///
3728/// \param OpLoc The location of the operator itself (e.g., '*').
3729///
3730/// \param OpcIn The UnaryOperator::Opcode that describes this
3731/// operator.
3732///
3733/// \param Functions The set of non-member functions that will be
3734/// considered by overload resolution. The caller needs to build this
3735/// set based on the context using, e.g.,
3736/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3737/// set should not contain any member functions; those will be added
3738/// by CreateOverloadedUnaryOp().
3739///
3740/// \param input The input argument.
3741Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3742 unsigned OpcIn,
3743 FunctionSet &Functions,
3744 ExprArg input) {
3745 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3746 Expr *Input = (Expr *)input.get();
3747
3748 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3749 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3750 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3751
3752 Expr *Args[2] = { Input, 0 };
3753 unsigned NumArgs = 1;
3754
3755 // For post-increment and post-decrement, add the implicit '0' as
3756 // the second argument, so that we know this is a post-increment or
3757 // post-decrement.
3758 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3759 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3760 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3761 SourceLocation());
3762 NumArgs = 2;
3763 }
3764
3765 if (Input->isTypeDependent()) {
3766 OverloadedFunctionDecl *Overloads
3767 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3768 for (FunctionSet::iterator Func = Functions.begin(),
3769 FuncEnd = Functions.end();
3770 Func != FuncEnd; ++Func)
3771 Overloads->addOverload(*Func);
3772
3773 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3774 OpLoc, false, false);
3775
3776 input.release();
3777 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3778 &Args[0], NumArgs,
3779 Context.DependentTy,
3780 OpLoc));
3781 }
3782
3783 // Build an empty overload set.
3784 OverloadCandidateSet CandidateSet;
3785
3786 // Add the candidates from the given function set.
3787 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3788
3789 // Add operator candidates that are member functions.
3790 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3791
3792 // Add builtin operator candidates.
3793 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3794
3795 // Perform overload resolution.
3796 OverloadCandidateSet::iterator Best;
3797 switch (BestViableFunction(CandidateSet, Best)) {
3798 case OR_Success: {
3799 // We found a built-in operator or an overloaded operator.
3800 FunctionDecl *FnDecl = Best->Function;
3801
3802 if (FnDecl) {
3803 // We matched an overloaded operator. Build a call to that
3804 // operator.
3805
3806 // Convert the arguments.
3807 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3808 if (PerformObjectArgumentInitialization(Input, Method))
3809 return ExprError();
3810 } else {
3811 // Convert the arguments.
3812 if (PerformCopyInitialization(Input,
3813 FnDecl->getParamDecl(0)->getType(),
3814 "passing"))
3815 return ExprError();
3816 }
3817
3818 // Determine the result type
3819 QualType ResultTy
3820 = FnDecl->getType()->getAsFunctionType()->getResultType();
3821 ResultTy = ResultTy.getNonReferenceType();
3822
3823 // Build the actual expression node.
3824 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3825 SourceLocation());
3826 UsualUnaryConversions(FnExpr);
3827
3828 input.release();
3829 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3830 &Input, 1, ResultTy,
3831 OpLoc));
3832 } else {
3833 // We matched a built-in operator. Convert the arguments, then
3834 // break out so that we will build the appropriate built-in
3835 // operator node.
3836 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3837 Best->Conversions[0], "passing"))
3838 return ExprError();
3839
3840 break;
3841 }
3842 }
3843
3844 case OR_No_Viable_Function:
3845 // No viable function; fall through to handling this as a
3846 // built-in operator, which will produce an error message for us.
3847 break;
3848
3849 case OR_Ambiguous:
3850 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3851 << UnaryOperator::getOpcodeStr(Opc)
3852 << Input->getSourceRange();
3853 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3854 return ExprError();
3855
3856 case OR_Deleted:
3857 Diag(OpLoc, diag::err_ovl_deleted_oper)
3858 << Best->Function->isDeleted()
3859 << UnaryOperator::getOpcodeStr(Opc)
3860 << Input->getSourceRange();
3861 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3862 return ExprError();
3863 }
3864
3865 // Either we found no viable overloaded operator or we matched a
3866 // built-in operator. In either case, fall through to trying to
3867 // build a built-in operation.
3868 input.release();
3869 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
3870}
3871
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003872/// \brief Create a binary operation that may resolve to an overloaded
3873/// operator.
3874///
3875/// \param OpLoc The location of the operator itself (e.g., '+').
3876///
3877/// \param OpcIn The BinaryOperator::Opcode that describes this
3878/// operator.
3879///
3880/// \param Functions The set of non-member functions that will be
3881/// considered by overload resolution. The caller needs to build this
3882/// set based on the context using, e.g.,
3883/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3884/// set should not contain any member functions; those will be added
3885/// by CreateOverloadedBinOp().
3886///
3887/// \param LHS Left-hand argument.
3888/// \param RHS Right-hand argument.
3889Sema::OwningExprResult
3890Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
3891 unsigned OpcIn,
3892 FunctionSet &Functions,
3893 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003894 Expr *Args[2] = { LHS, RHS };
3895
3896 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
3897 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
3898 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3899
3900 // If either side is type-dependent, create an appropriate dependent
3901 // expression.
3902 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
3903 // .* cannot be overloaded.
3904 if (Opc == BinaryOperator::PtrMemD)
3905 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
3906 Context.DependentTy, OpLoc));
3907
3908 OverloadedFunctionDecl *Overloads
3909 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3910 for (FunctionSet::iterator Func = Functions.begin(),
3911 FuncEnd = Functions.end();
3912 Func != FuncEnd; ++Func)
3913 Overloads->addOverload(*Func);
3914
3915 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3916 OpLoc, false, false);
3917
3918 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3919 Args, 2,
3920 Context.DependentTy,
3921 OpLoc));
3922 }
3923
3924 // If this is the .* operator, which is not overloadable, just
3925 // create a built-in binary operator.
3926 if (Opc == BinaryOperator::PtrMemD)
3927 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3928
3929 // If this is one of the assignment operators, we only perform
3930 // overload resolution if the left-hand side is a class or
3931 // enumeration type (C++ [expr.ass]p3).
3932 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3933 !LHS->getType()->isOverloadableType())
3934 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3935
Douglas Gregorc78182d2009-03-13 23:49:33 +00003936 // Build an empty overload set.
3937 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003938
3939 // Add the candidates from the given function set.
3940 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
3941
3942 // Add operator candidates that are member functions.
3943 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
3944
3945 // Add builtin operator candidates.
3946 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
3947
3948 // Perform overload resolution.
3949 OverloadCandidateSet::iterator Best;
3950 switch (BestViableFunction(CandidateSet, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003951 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003952 // We found a built-in operator or an overloaded operator.
3953 FunctionDecl *FnDecl = Best->Function;
3954
3955 if (FnDecl) {
3956 // We matched an overloaded operator. Build a call to that
3957 // operator.
3958
3959 // Convert the arguments.
3960 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3961 if (PerformObjectArgumentInitialization(LHS, Method) ||
3962 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
3963 "passing"))
3964 return ExprError();
3965 } else {
3966 // Convert the arguments.
3967 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
3968 "passing") ||
3969 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
3970 "passing"))
3971 return ExprError();
3972 }
3973
3974 // Determine the result type
3975 QualType ResultTy
3976 = FnDecl->getType()->getAsFunctionType()->getResultType();
3977 ResultTy = ResultTy.getNonReferenceType();
3978
3979 // Build the actual expression node.
3980 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3981 SourceLocation());
3982 UsualUnaryConversions(FnExpr);
3983
3984 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3985 Args, 2, ResultTy,
3986 OpLoc));
3987 } else {
3988 // We matched a built-in operator. Convert the arguments, then
3989 // break out so that we will build the appropriate built-in
3990 // operator node.
3991 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
3992 Best->Conversions[0], "passing") ||
3993 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
3994 Best->Conversions[1], "passing"))
3995 return ExprError();
3996
3997 break;
3998 }
3999 }
4000
4001 case OR_No_Viable_Function:
4002 // No viable function; fall through to handling this as a
4003 // built-in operator, which will produce an error message for us.
4004 break;
4005
4006 case OR_Ambiguous:
4007 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4008 << BinaryOperator::getOpcodeStr(Opc)
4009 << LHS->getSourceRange() << RHS->getSourceRange();
4010 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4011 return ExprError();
4012
4013 case OR_Deleted:
4014 Diag(OpLoc, diag::err_ovl_deleted_oper)
4015 << Best->Function->isDeleted()
4016 << BinaryOperator::getOpcodeStr(Opc)
4017 << LHS->getSourceRange() << RHS->getSourceRange();
4018 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4019 return ExprError();
4020 }
4021
4022 // Either we found no viable overloaded operator or we matched a
4023 // built-in operator. In either case, try to build a built-in
4024 // operation.
4025 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4026}
4027
Douglas Gregor3257fb52008-12-22 05:46:06 +00004028/// BuildCallToMemberFunction - Build a call to a member
4029/// function. MemExpr is the expression that refers to the member
4030/// function (and includes the object parameter), Args/NumArgs are the
4031/// arguments to the function call (not including the object
4032/// parameter). The caller needs to validate that the member
4033/// expression refers to a member function or an overloaded member
4034/// function.
4035Sema::ExprResult
4036Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4037 SourceLocation LParenLoc, Expr **Args,
4038 unsigned NumArgs, SourceLocation *CommaLocs,
4039 SourceLocation RParenLoc) {
4040 // Dig out the member expression. This holds both the object
4041 // argument and the member function we're referring to.
4042 MemberExpr *MemExpr = 0;
4043 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4044 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4045 else
4046 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4047 assert(MemExpr && "Building member call without member expression");
4048
4049 // Extract the object argument.
4050 Expr *ObjectArg = MemExpr->getBase();
4051 if (MemExpr->isArrow())
Ted Kremenek0c97e042009-02-07 01:47:29 +00004052 ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref,
4053 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
Douglas Gregor8d103492009-02-19 00:52:42 +00004054 ObjectArg->getLocStart());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004055 CXXMethodDecl *Method = 0;
4056 if (OverloadedFunctionDecl *Ovl
4057 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
4058 // Add overload candidates
4059 OverloadCandidateSet CandidateSet;
4060 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4061 FuncEnd = Ovl->function_end();
4062 Func != FuncEnd; ++Func) {
4063 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
4064 Method = cast<CXXMethodDecl>(*Func);
4065 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4066 /*SuppressUserConversions=*/false);
4067 }
4068
4069 OverloadCandidateSet::iterator Best;
4070 switch (BestViableFunction(CandidateSet, Best)) {
4071 case OR_Success:
4072 Method = cast<CXXMethodDecl>(Best->Function);
4073 break;
4074
4075 case OR_No_Viable_Function:
4076 Diag(MemExpr->getSourceRange().getBegin(),
4077 diag::err_ovl_no_viable_member_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004078 << Ovl->getDeclName() << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004079 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4080 // FIXME: Leaking incoming expressions!
4081 return true;
4082
4083 case OR_Ambiguous:
4084 Diag(MemExpr->getSourceRange().getBegin(),
4085 diag::err_ovl_ambiguous_member_call)
4086 << Ovl->getDeclName() << MemExprE->getSourceRange();
4087 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4088 // FIXME: Leaking incoming expressions!
4089 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004090
4091 case OR_Deleted:
4092 Diag(MemExpr->getSourceRange().getBegin(),
4093 diag::err_ovl_deleted_member_call)
4094 << Best->Function->isDeleted()
4095 << Ovl->getDeclName() << MemExprE->getSourceRange();
4096 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4097 // FIXME: Leaking incoming expressions!
4098 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004099 }
4100
4101 FixOverloadedFunctionReference(MemExpr, Method);
4102 } else {
4103 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4104 }
4105
4106 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004107 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004108 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4109 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004110 Method->getResultType().getNonReferenceType(),
4111 RParenLoc));
4112
4113 // Convert the object argument (for a non-static member function call).
4114 if (!Method->isStatic() &&
4115 PerformObjectArgumentInitialization(ObjectArg, Method))
4116 return true;
4117 MemExpr->setBase(ObjectArg);
4118
4119 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004120 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004121 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4122 RParenLoc))
4123 return true;
4124
Sebastian Redl8b769972009-01-19 00:08:26 +00004125 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004126}
4127
Douglas Gregor10f3c502008-11-19 21:05:33 +00004128/// BuildCallToObjectOfClassType - Build a call to an object of class
4129/// type (C++ [over.call.object]), which can end up invoking an
4130/// overloaded function call operator (@c operator()) or performing a
4131/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004132Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004133Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4134 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004135 Expr **Args, unsigned NumArgs,
4136 SourceLocation *CommaLocs,
4137 SourceLocation RParenLoc) {
4138 assert(Object->getType()->isRecordType() && "Requires object type argument");
4139 const RecordType *Record = Object->getType()->getAsRecordType();
4140
4141 // C++ [over.call.object]p1:
4142 // If the primary-expression E in the function call syntax
4143 // evaluates to a class object of type “cv T”, then the set of
4144 // candidate functions includes at least the function call
4145 // operators of T. The function call operators of T are obtained by
4146 // ordinary lookup of the name operator() in the context of
4147 // (E).operator().
4148 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004149 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004150 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004151 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004152 Oper != OperEnd; ++Oper)
4153 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4154 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004155
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004156 // C++ [over.call.object]p2:
4157 // In addition, for each conversion function declared in T of the
4158 // form
4159 //
4160 // operator conversion-type-id () cv-qualifier;
4161 //
4162 // where cv-qualifier is the same cv-qualification as, or a
4163 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004164 // denotes the type "pointer to function of (P1,...,Pn) returning
4165 // R", or the type "reference to pointer to function of
4166 // (P1,...,Pn) returning R", or the type "reference to function
4167 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004168 // is also considered as a candidate function. Similarly,
4169 // surrogate call functions are added to the set of candidate
4170 // functions for each conversion function declared in an
4171 // accessible base class provided the function is not hidden
4172 // within T by another intervening declaration.
4173 //
4174 // FIXME: Look in base classes for more conversion operators!
4175 OverloadedFunctionDecl *Conversions
4176 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004177 for (OverloadedFunctionDecl::function_iterator
4178 Func = Conversions->function_begin(),
4179 FuncEnd = Conversions->function_end();
4180 Func != FuncEnd; ++Func) {
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004181 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4182
4183 // Strip the reference type (if any) and then the pointer type (if
4184 // any) to get down to what might be a function type.
4185 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4186 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4187 ConvType = ConvPtrType->getPointeeType();
4188
Douglas Gregor4fa58902009-02-26 23:50:07 +00004189 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004190 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4191 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004192
4193 // Perform overload resolution.
4194 OverloadCandidateSet::iterator Best;
4195 switch (BestViableFunction(CandidateSet, Best)) {
4196 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004197 // Overload resolution succeeded; we'll build the appropriate call
4198 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004199 break;
4200
4201 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004202 Diag(Object->getSourceRange().getBegin(),
4203 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004204 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004205 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004206 break;
4207
4208 case OR_Ambiguous:
4209 Diag(Object->getSourceRange().getBegin(),
4210 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004211 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004212 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4213 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004214
4215 case OR_Deleted:
4216 Diag(Object->getSourceRange().getBegin(),
4217 diag::err_ovl_deleted_object_call)
4218 << Best->Function->isDeleted()
4219 << Object->getType() << Object->getSourceRange();
4220 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4221 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004222 }
4223
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004224 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004225 // We had an error; delete all of the subexpressions and return
4226 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004227 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004228 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004229 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004230 return true;
4231 }
4232
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004233 if (Best->Function == 0) {
4234 // Since there is no function declaration, this is one of the
4235 // surrogate candidates. Dig out the conversion function.
4236 CXXConversionDecl *Conv
4237 = cast<CXXConversionDecl>(
4238 Best->Conversions[0].UserDefined.ConversionFunction);
4239
4240 // We selected one of the surrogate functions that converts the
4241 // object parameter to a function pointer. Perform the conversion
4242 // on the object argument, then let ActOnCallExpr finish the job.
4243 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004244 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004245 Conv->getConversionType().getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +00004246 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004247 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4248 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4249 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004250 }
4251
4252 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4253 // that calls this method, using Object for the implicit object
4254 // parameter and passing along the remaining arguments.
4255 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004256 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004257
4258 unsigned NumArgsInProto = Proto->getNumArgs();
4259 unsigned NumArgsToCheck = NumArgs;
4260
4261 // Build the full argument list for the method call (the
4262 // implicit object parameter is placed at the beginning of the
4263 // list).
4264 Expr **MethodArgs;
4265 if (NumArgs < NumArgsInProto) {
4266 NumArgsToCheck = NumArgsInProto;
4267 MethodArgs = new Expr*[NumArgsInProto + 1];
4268 } else {
4269 MethodArgs = new Expr*[NumArgs + 1];
4270 }
4271 MethodArgs[0] = Object;
4272 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4273 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4274
Ted Kremenek0c97e042009-02-07 01:47:29 +00004275 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4276 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004277 UsualUnaryConversions(NewFn);
4278
4279 // Once we've built TheCall, all of the expressions are properly
4280 // owned.
4281 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004282 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004283 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4284 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004285 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004286 delete [] MethodArgs;
4287
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004288 // We may have default arguments. If so, we need to allocate more
4289 // slots in the call for them.
4290 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004291 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004292 else if (NumArgs > NumArgsInProto)
4293 NumArgsToCheck = NumArgsInProto;
4294
Chris Lattner81f00ed2009-04-12 08:11:20 +00004295 bool IsError = false;
4296
Douglas Gregor10f3c502008-11-19 21:05:33 +00004297 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004298 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004299 TheCall->setArg(0, Object);
4300
Chris Lattner81f00ed2009-04-12 08:11:20 +00004301
Douglas Gregor10f3c502008-11-19 21:05:33 +00004302 // Check the argument types.
4303 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004304 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004305 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004306 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004307
4308 // Pass the argument.
4309 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004310 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004311 } else {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004312 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004313 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004314
4315 TheCall->setArg(i + 1, Arg);
4316 }
4317
4318 // If this is a variadic call, handle args passed through "...".
4319 if (Proto->isVariadic()) {
4320 // Promote the arguments (C99 6.5.2.2p7).
4321 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4322 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004323 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004324 TheCall->setArg(i + 1, Arg);
4325 }
4326 }
4327
Chris Lattner81f00ed2009-04-12 08:11:20 +00004328 if (IsError) return true;
4329
Sebastian Redl8b769972009-01-19 00:08:26 +00004330 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004331}
4332
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004333/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4334/// (if one exists), where @c Base is an expression of class type and
4335/// @c Member is the name of the member we're trying to find.
4336Action::ExprResult
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004337Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004338 SourceLocation MemberLoc,
4339 IdentifierInfo &Member) {
4340 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4341
4342 // C++ [over.ref]p1:
4343 //
4344 // [...] An expression x->m is interpreted as (x.operator->())->m
4345 // for a class object x of type T if T::operator->() exists and if
4346 // the operator is selected as the best match function by the
4347 // overload resolution mechanism (13.3).
4348 // FIXME: look in base classes.
4349 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4350 OverloadCandidateSet CandidateSet;
4351 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004352
4353 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004354 for (llvm::tie(Oper, OperEnd)
4355 = BaseRecord->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004356 Oper != OperEnd; ++Oper)
4357 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004358 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004359
Ted Kremenek0c97e042009-02-07 01:47:29 +00004360 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004361
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004362 // Perform overload resolution.
4363 OverloadCandidateSet::iterator Best;
4364 switch (BestViableFunction(CandidateSet, Best)) {
4365 case OR_Success:
4366 // Overload resolution succeeded; we'll build the call below.
4367 break;
4368
4369 case OR_No_Viable_Function:
4370 if (CandidateSet.empty())
4371 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004372 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004373 else
4374 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Chris Lattner4a526112009-02-17 07:29:20 +00004375 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004376 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004377 return true;
4378
4379 case OR_Ambiguous:
4380 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004381 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004382 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004383 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004384
4385 case OR_Deleted:
4386 Diag(OpLoc, diag::err_ovl_deleted_oper)
4387 << Best->Function->isDeleted()
4388 << "operator->" << BasePtr->getSourceRange();
4389 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4390 return true;
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004391 }
4392
4393 // Convert the object parameter.
4394 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004395 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004396 return true;
Douglas Gregor9c690e92008-11-21 03:04:22 +00004397
4398 // No concerns about early exits now.
4399 BasePtr.take();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004400
4401 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004402 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4403 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004404 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004405 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004406 Method->getResultType().getNonReferenceType(),
4407 OpLoc);
Sebastian Redl8b769972009-01-19 00:08:26 +00004408 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
Chris Lattner5261d0c2009-03-28 19:18:32 +00004409 MemberLoc, Member, DeclPtrTy()).release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004410}
4411
Douglas Gregor45014fd2008-11-10 20:40:00 +00004412/// FixOverloadedFunctionReference - E is an expression that refers to
4413/// a C++ overloaded function (possibly with some parentheses and
4414/// perhaps a '&' around it). We have resolved the overloaded function
4415/// to the function declaration Fn, so patch up the expression E to
4416/// refer (possibly indirectly) to Fn.
4417void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4418 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4419 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4420 E->setType(PE->getSubExpr()->getType());
4421 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4422 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4423 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004424 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4425 if (Method->isStatic()) {
4426 // Do nothing: static member functions aren't any different
4427 // from non-member functions.
4428 }
4429 else if (QualifiedDeclRefExpr *DRE
4430 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4431 // We have taken the address of a pointer to member
4432 // function. Perform the computation here so that we get the
4433 // appropriate pointer to member type.
4434 DRE->setDecl(Fn);
4435 DRE->setType(Fn->getType());
4436 QualType ClassType
4437 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4438 E->setType(Context.getMemberPointerType(Fn->getType(),
4439 ClassType.getTypePtr()));
4440 return;
4441 }
4442 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004443 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004444 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004445 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4446 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4447 "Expected overloaded function");
4448 DR->setDecl(Fn);
4449 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004450 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4451 MemExpr->setMemberDecl(Fn);
4452 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004453 } else {
4454 assert(false && "Invalid reference to overloaded function");
4455 }
4456}
4457
Douglas Gregord2baafd2008-10-21 16:13:35 +00004458} // end namespace clang