blob: e6b8056a428a11883ab8f757e19cad1c07dc0eb8 [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.
Douglas Gregor531434b2009-05-02 02:18:30 +0000749 using llvm::APSInt;
750 if (From)
751 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000752 APSInt BitWidth;
Douglas Gregor531434b2009-05-02 02:18:30 +0000753 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
754 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
755 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
756 ToSize = Context.getTypeSize(ToType);
Douglas Gregor82d44772008-12-20 23:49:58 +0000757
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 }
Douglas Gregor531434b2009-05-02 02:18:30 +0000773
Douglas Gregord2baafd2008-10-21 16:13:35 +0000774 // An rvalue of type bool can be converted to an rvalue of type int,
775 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000776 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000777 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000778 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000779
780 return false;
781}
782
783/// IsFloatingPointPromotion - Determines whether the conversion from
784/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
785/// returns true and sets PromotedType to the promoted type.
786bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
787{
788 /// An rvalue of type float can be converted to an rvalue of type
789 /// double. (C++ 4.6p1).
790 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000791 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000792 if (FromBuiltin->getKind() == BuiltinType::Float &&
793 ToBuiltin->getKind() == BuiltinType::Double)
794 return true;
795
Douglas Gregore819caf2009-02-12 00:15:05 +0000796 // C99 6.3.1.5p1:
797 // When a float is promoted to double or long double, or a
798 // double is promoted to long double [...].
799 if (!getLangOptions().CPlusPlus &&
800 (FromBuiltin->getKind() == BuiltinType::Float ||
801 FromBuiltin->getKind() == BuiltinType::Double) &&
802 (ToBuiltin->getKind() == BuiltinType::LongDouble))
803 return true;
804 }
805
Douglas Gregord2baafd2008-10-21 16:13:35 +0000806 return false;
807}
808
Douglas Gregore819caf2009-02-12 00:15:05 +0000809/// \brief Determine if a conversion is a complex promotion.
810///
811/// A complex promotion is defined as a complex -> complex conversion
812/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000813/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000814bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
815 const ComplexType *FromComplex = FromType->getAsComplexType();
816 if (!FromComplex)
817 return false;
818
819 const ComplexType *ToComplex = ToType->getAsComplexType();
820 if (!ToComplex)
821 return false;
822
823 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000824 ToComplex->getElementType()) ||
825 IsIntegralPromotion(0, FromComplex->getElementType(),
826 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000827}
828
Douglas Gregor24a90a52008-11-26 23:31:11 +0000829/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
830/// the pointer type FromPtr to a pointer to type ToPointee, with the
831/// same type qualifiers as FromPtr has on its pointee type. ToType,
832/// if non-empty, will be a pointer to ToType that may or may not have
833/// the right set of qualifiers on its pointee.
834static QualType
835BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
836 QualType ToPointee, QualType ToType,
837 ASTContext &Context) {
838 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
839 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
840 unsigned Quals = CanonFromPointee.getCVRQualifiers();
841
842 // Exact qualifier match -> return the pointer type we're converting to.
843 if (CanonToPointee.getCVRQualifiers() == Quals) {
844 // ToType is exactly what we need. Return it.
845 if (ToType.getTypePtr())
846 return ToType;
847
848 // Build a pointer to ToPointee. It has the right qualifiers
849 // already.
850 return Context.getPointerType(ToPointee);
851 }
852
853 // Just build a canonical type that has the right qualifiers.
854 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
855}
856
Douglas Gregord2baafd2008-10-21 16:13:35 +0000857/// IsPointerConversion - Determines whether the conversion of the
858/// expression From, which has the (possibly adjusted) type FromType,
859/// can be converted to the type ToType via a pointer conversion (C++
860/// 4.10). If so, returns true and places the converted type (that
861/// might differ from ToType in its cv-qualifiers at some level) into
862/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000863///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000864/// This routine also supports conversions to and from block pointers
865/// and conversions with Objective-C's 'id', 'id<protocols...>', and
866/// pointers to interfaces. FIXME: Once we've determined the
867/// appropriate overloading rules for Objective-C, we may want to
868/// split the Objective-C checks into a different routine; however,
869/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000870/// conversions, so for now they live here. IncompatibleObjC will be
871/// set if the conversion is an allowed Objective-C conversion that
872/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000873bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000874 QualType& ConvertedType,
875 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000876{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000877 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000878 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
879 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000880
Douglas Gregorf1d75712008-12-22 20:51:52 +0000881 // Conversion from a null pointer constant to any Objective-C pointer type.
882 if (Context.isObjCObjectPointerType(ToType) &&
883 From->isNullPointerConstant(Context)) {
884 ConvertedType = ToType;
885 return true;
886 }
887
Douglas Gregor9036ef72008-11-27 00:15:41 +0000888 // Blocks: Block pointers can be converted to void*.
889 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
890 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
891 ConvertedType = ToType;
892 return true;
893 }
894 // Blocks: A null pointer constant can be converted to a block
895 // pointer type.
896 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
897 ConvertedType = ToType;
898 return true;
899 }
900
Douglas Gregord2baafd2008-10-21 16:13:35 +0000901 const PointerType* ToTypePtr = ToType->getAsPointerType();
902 if (!ToTypePtr)
903 return false;
904
905 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
906 if (From->isNullPointerConstant(Context)) {
907 ConvertedType = ToType;
908 return true;
909 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000910
Douglas Gregor24a90a52008-11-26 23:31:11 +0000911 // Beyond this point, both types need to be pointers.
912 const PointerType *FromTypePtr = FromType->getAsPointerType();
913 if (!FromTypePtr)
914 return false;
915
916 QualType FromPointeeType = FromTypePtr->getPointeeType();
917 QualType ToPointeeType = ToTypePtr->getPointeeType();
918
Douglas Gregord2baafd2008-10-21 16:13:35 +0000919 // An rvalue of type "pointer to cv T," where T is an object type,
920 // can be converted to an rvalue of type "pointer to cv void" (C++
921 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000922 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000923 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
924 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000925 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000926 return true;
927 }
928
Douglas Gregorfcb19192009-02-11 23:02:49 +0000929 // When we're overloading in C, we allow a special kind of pointer
930 // conversion for compatible-but-not-identical pointee types.
931 if (!getLangOptions().CPlusPlus &&
932 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
933 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
934 ToPointeeType,
935 ToType, Context);
936 return true;
937 }
938
Douglas Gregor14046502008-10-23 00:40:37 +0000939 // C++ [conv.ptr]p3:
940 //
941 // An rvalue of type "pointer to cv D," where D is a class type,
942 // can be converted to an rvalue of type "pointer to cv B," where
943 // B is a base class (clause 10) of D. If B is an inaccessible
944 // (clause 11) or ambiguous (10.2) base class of D, a program that
945 // necessitates this conversion is ill-formed. The result of the
946 // conversion is a pointer to the base class sub-object of the
947 // derived class object. The null pointer value is converted to
948 // the null pointer value of the destination type.
949 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000950 // Note that we do not check for ambiguity or inaccessibility
951 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000952 if (getLangOptions().CPlusPlus &&
953 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000954 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000955 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
956 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000957 ToType, Context);
958 return true;
959 }
Douglas Gregor14046502008-10-23 00:40:37 +0000960
Douglas Gregor932778b2008-12-19 19:13:09 +0000961 return false;
962}
963
964/// isObjCPointerConversion - Determines whether this is an
965/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
966/// with the same arguments and return values.
967bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
968 QualType& ConvertedType,
969 bool &IncompatibleObjC) {
970 if (!getLangOptions().ObjC1)
971 return false;
972
973 // Conversions with Objective-C's id<...>.
974 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
975 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
976 ConvertedType = ToType;
977 return true;
978 }
979
Douglas Gregor80402cf2008-12-23 00:53:59 +0000980 // Beyond this point, both types need to be pointers or block pointers.
981 QualType ToPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000982 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000983 if (ToTypePtr)
984 ToPointeeType = ToTypePtr->getPointeeType();
985 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
986 ToPointeeType = ToBlockPtr->getPointeeType();
987 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000988 return false;
989
Douglas Gregor80402cf2008-12-23 00:53:59 +0000990 QualType FromPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000991 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000992 if (FromTypePtr)
993 FromPointeeType = FromTypePtr->getPointeeType();
994 else if (const BlockPointerType *FromBlockPtr
995 = FromType->getAsBlockPointerType())
996 FromPointeeType = FromBlockPtr->getPointeeType();
997 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000998 return false;
999
Douglas Gregor24a90a52008-11-26 23:31:11 +00001000 // Objective C++: We're able to convert from a pointer to an
1001 // interface to a pointer to a different interface.
1002 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
1003 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1004 if (FromIface && ToIface &&
1005 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor80402cf2008-12-23 00:53:59 +00001006 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001007 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001008 ToType, Context);
1009 return true;
1010 }
1011
Douglas Gregor6fd35572008-12-19 17:40:08 +00001012 if (FromIface && ToIface &&
1013 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1014 // Okay: this is some kind of implicit downcast of Objective-C
1015 // interfaces, which is permitted. However, we're going to
1016 // complain about it.
1017 IncompatibleObjC = true;
Douglas Gregor80402cf2008-12-23 00:53:59 +00001018 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor6fd35572008-12-19 17:40:08 +00001019 ToPointeeType,
1020 ToType, Context);
1021 return true;
1022 }
1023
Douglas Gregor24a90a52008-11-26 23:31:11 +00001024 // Objective C++: We're able to convert between "id" and a pointer
1025 // to any interface (in both directions).
Steve Naroff17c03822009-02-12 17:52:19 +00001026 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1027 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001028 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1029 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001030 ToType, Context);
1031 return true;
1032 }
Douglas Gregor14046502008-10-23 00:40:37 +00001033
Douglas Gregord0c653a2008-12-18 23:43:31 +00001034 // Objective C++: Allow conversions between the Objective-C "id" and
1035 // "Class", in either direction.
Steve Naroff17c03822009-02-12 17:52:19 +00001036 if ((Context.isObjCIdStructType(FromPointeeType) &&
1037 Context.isObjCClassStructType(ToPointeeType)) ||
1038 (Context.isObjCClassStructType(FromPointeeType) &&
1039 Context.isObjCIdStructType(ToPointeeType))) {
Douglas Gregord0c653a2008-12-18 23:43:31 +00001040 ConvertedType = ToType;
1041 return true;
1042 }
1043
Douglas Gregor932778b2008-12-19 19:13:09 +00001044 // If we have pointers to pointers, recursively check whether this
1045 // is an Objective-C conversion.
1046 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1047 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1048 IncompatibleObjC)) {
1049 // We always complain about this conversion.
1050 IncompatibleObjC = true;
1051 ConvertedType = ToType;
1052 return true;
1053 }
1054
Douglas Gregor80402cf2008-12-23 00:53:59 +00001055 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001056 // differences in the argument and result types are in Objective-C
1057 // pointer conversions. If so, we permit the conversion (but
1058 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001059 const FunctionProtoType *FromFunctionType
1060 = FromPointeeType->getAsFunctionProtoType();
1061 const FunctionProtoType *ToFunctionType
1062 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001063 if (FromFunctionType && ToFunctionType) {
1064 // If the function types are exactly the same, this isn't an
1065 // Objective-C pointer conversion.
1066 if (Context.getCanonicalType(FromPointeeType)
1067 == Context.getCanonicalType(ToPointeeType))
1068 return false;
1069
1070 // Perform the quick checks that will tell us whether these
1071 // function types are obviously different.
1072 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1073 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1074 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1075 return false;
1076
1077 bool HasObjCConversion = false;
1078 if (Context.getCanonicalType(FromFunctionType->getResultType())
1079 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1080 // Okay, the types match exactly. Nothing to do.
1081 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1082 ToFunctionType->getResultType(),
1083 ConvertedType, IncompatibleObjC)) {
1084 // Okay, we have an Objective-C pointer conversion.
1085 HasObjCConversion = true;
1086 } else {
1087 // Function types are too different. Abort.
1088 return false;
1089 }
1090
1091 // Check argument types.
1092 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1093 ArgIdx != NumArgs; ++ArgIdx) {
1094 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1095 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1096 if (Context.getCanonicalType(FromArgType)
1097 == Context.getCanonicalType(ToArgType)) {
1098 // Okay, the types match exactly. Nothing to do.
1099 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1100 ConvertedType, IncompatibleObjC)) {
1101 // Okay, we have an Objective-C pointer conversion.
1102 HasObjCConversion = true;
1103 } else {
1104 // Argument types are too different. Abort.
1105 return false;
1106 }
1107 }
1108
1109 if (HasObjCConversion) {
1110 // We had an Objective-C conversion. Allow this pointer
1111 // conversion, but complain about it.
1112 ConvertedType = ToType;
1113 IncompatibleObjC = true;
1114 return true;
1115 }
1116 }
1117
Sebastian Redlba387562009-01-25 19:43:20 +00001118 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001119}
1120
Douglas Gregorbb461502008-10-24 04:54:22 +00001121/// CheckPointerConversion - Check the pointer conversion from the
1122/// expression From to the type ToType. This routine checks for
1123/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1124/// conversions for which IsPointerConversion has already returned
1125/// true. It returns true and produces a diagnostic if there was an
1126/// error, or returns false otherwise.
1127bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1128 QualType FromType = From->getType();
1129
1130 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1131 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001132 QualType FromPointeeType = FromPtrType->getPointeeType(),
1133 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001134
1135 // Objective-C++ conversions are always okay.
1136 // FIXME: We should have a different class of conversions for
1137 // the Objective-C++ implicit conversions.
Steve Naroff17c03822009-02-12 17:52:19 +00001138 if (Context.isObjCIdStructType(FromPointeeType) ||
1139 Context.isObjCIdStructType(ToPointeeType) ||
1140 Context.isObjCClassStructType(FromPointeeType) ||
1141 Context.isObjCClassStructType(ToPointeeType))
Douglas Gregord0c653a2008-12-18 23:43:31 +00001142 return false;
1143
Douglas Gregorbb461502008-10-24 04:54:22 +00001144 if (FromPointeeType->isRecordType() &&
1145 ToPointeeType->isRecordType()) {
1146 // We must have a derived-to-base conversion. Check an
1147 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001148 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1149 From->getExprLoc(),
1150 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001151 }
1152 }
1153
1154 return false;
1155}
1156
Sebastian Redlba387562009-01-25 19:43:20 +00001157/// IsMemberPointerConversion - Determines whether the conversion of the
1158/// expression From, which has the (possibly adjusted) type FromType, can be
1159/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1160/// If so, returns true and places the converted type (that might differ from
1161/// ToType in its cv-qualifiers at some level) into ConvertedType.
1162bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1163 QualType ToType, QualType &ConvertedType)
1164{
1165 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1166 if (!ToTypePtr)
1167 return false;
1168
1169 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1170 if (From->isNullPointerConstant(Context)) {
1171 ConvertedType = ToType;
1172 return true;
1173 }
1174
1175 // Otherwise, both types have to be member pointers.
1176 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1177 if (!FromTypePtr)
1178 return false;
1179
1180 // A pointer to member of B can be converted to a pointer to member of D,
1181 // where D is derived from B (C++ 4.11p2).
1182 QualType FromClass(FromTypePtr->getClass(), 0);
1183 QualType ToClass(ToTypePtr->getClass(), 0);
1184 // FIXME: What happens when these are dependent? Is this function even called?
1185
1186 if (IsDerivedFrom(ToClass, FromClass)) {
1187 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1188 ToClass.getTypePtr());
1189 return true;
1190 }
1191
1192 return false;
1193}
1194
1195/// CheckMemberPointerConversion - Check the member pointer conversion from the
1196/// expression From to the type ToType. This routine checks for ambiguous or
1197/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1198/// for which IsMemberPointerConversion has already returned true. It returns
1199/// true and produces a diagnostic if there was an error, or returns false
1200/// otherwise.
1201bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1202 QualType FromType = From->getType();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001203 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1204 if (!FromPtrType)
1205 return false;
Sebastian Redlba387562009-01-25 19:43:20 +00001206
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001207 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1208 assert(ToPtrType && "No member pointer cast has a target type "
1209 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001210
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001211 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1212 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001213
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001214 // FIXME: What about dependent types?
1215 assert(FromClass->isRecordType() && "Pointer into non-class.");
1216 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001217
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001218 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1219 /*DetectVirtual=*/true);
1220 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1221 assert(DerivationOkay &&
1222 "Should not have been called if derivation isn't OK.");
1223 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001224
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001225 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1226 getUnqualifiedType())) {
1227 // Derivation is ambiguous. Redo the check to find the exact paths.
1228 Paths.clear();
1229 Paths.setRecordingPaths(true);
1230 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1231 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1232 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001233
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001234 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1235 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1236 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1237 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001238 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001239
Douglas Gregor2e047592009-02-28 01:32:25 +00001240 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001241 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1242 << FromClass << ToClass << QualType(VBase, 0)
1243 << From->getSourceRange();
1244 return true;
1245 }
1246
Sebastian Redlba387562009-01-25 19:43:20 +00001247 return false;
1248}
1249
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001250/// IsQualificationConversion - Determines whether the conversion from
1251/// an rvalue of type FromType to ToType is a qualification conversion
1252/// (C++ 4.4).
1253bool
1254Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1255{
1256 FromType = Context.getCanonicalType(FromType);
1257 ToType = Context.getCanonicalType(ToType);
1258
1259 // If FromType and ToType are the same type, this is not a
1260 // qualification conversion.
1261 if (FromType == ToType)
1262 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001263
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001264 // (C++ 4.4p4):
1265 // A conversion can add cv-qualifiers at levels other than the first
1266 // in multi-level pointers, subject to the following rules: [...]
1267 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001268 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001269 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001270 // Within each iteration of the loop, we check the qualifiers to
1271 // determine if this still looks like a qualification
1272 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001273 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001274 // until there are no more pointers or pointers-to-members left to
1275 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001276 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001277
1278 // -- for every j > 0, if const is in cv 1,j then const is in cv
1279 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001280 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001281 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001282
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001283 // -- if the cv 1,j and cv 2,j are different, then const is in
1284 // every cv for 0 < k < j.
1285 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001286 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001287 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001288
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001289 // Keep track of whether all prior cv-qualifiers in the "to" type
1290 // include const.
1291 PreviousToQualsIncludeConst
1292 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001293 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001294
1295 // We are left with FromType and ToType being the pointee types
1296 // after unwrapping the original FromType and ToType the same number
1297 // of types. If we unwrapped any pointers, and if FromType and
1298 // ToType have the same unqualified type (since we checked
1299 // qualifiers above), then this is a qualification conversion.
1300 return UnwrappedAnyPointer &&
1301 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1302}
1303
Douglas Gregorb206cc42009-01-30 23:27:23 +00001304/// Determines whether there is a user-defined conversion sequence
1305/// (C++ [over.ics.user]) that converts expression From to the type
1306/// ToType. If such a conversion exists, User will contain the
1307/// user-defined conversion sequence that performs such a conversion
1308/// and this routine will return true. Otherwise, this routine returns
1309/// false and User is unspecified.
1310///
1311/// \param AllowConversionFunctions true if the conversion should
1312/// consider conversion functions at all. If false, only constructors
1313/// will be considered.
1314///
1315/// \param AllowExplicit true if the conversion should consider C++0x
1316/// "explicit" conversion functions as well as non-explicit conversion
1317/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001318///
1319/// \param ForceRValue true if the expression should be treated as an rvalue
1320/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001321bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001322 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001323 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001324 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001325{
1326 OverloadCandidateSet CandidateSet;
Douglas Gregor2e047592009-02-28 01:32:25 +00001327 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1328 if (CXXRecordDecl *ToRecordDecl
1329 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1330 // C++ [over.match.ctor]p1:
1331 // When objects of class type are direct-initialized (8.5), or
1332 // copy-initialized from an expression of the same or a
1333 // derived class type (8.5), overload resolution selects the
1334 // constructor. [...] For copy-initialization, the candidate
1335 // functions are all the converting constructors (12.3.1) of
1336 // that class. The argument list is the expression-list within
1337 // the parentheses of the initializer.
1338 DeclarationName ConstructorName
1339 = Context.DeclarationNames.getCXXConstructorName(
1340 Context.getCanonicalType(ToType).getUnqualifiedType());
1341 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001342 for (llvm::tie(Con, ConEnd)
1343 = ToRecordDecl->lookup(Context, ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001344 Con != ConEnd; ++Con) {
1345 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1346 if (Constructor->isConvertingConstructor())
1347 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00001348 /*SuppressUserConversions=*/true, ForceRValue);
Douglas Gregor2e047592009-02-28 01:32:25 +00001349 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001350 }
1351 }
1352
Douglas Gregorb206cc42009-01-30 23:27:23 +00001353 if (!AllowConversionFunctions) {
1354 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-02-28 01:32:25 +00001355 } else if (const RecordType *FromRecordType
1356 = From->getType()->getAsRecordType()) {
1357 if (CXXRecordDecl *FromRecordDecl
1358 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1359 // Add all of the conversion functions as candidates.
1360 // FIXME: Look for conversions in base classes!
1361 OverloadedFunctionDecl *Conversions
1362 = FromRecordDecl->getConversionFunctions();
1363 for (OverloadedFunctionDecl::function_iterator Func
1364 = Conversions->function_begin();
1365 Func != Conversions->function_end(); ++Func) {
1366 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1367 if (AllowExplicit || !Conv->isExplicit())
1368 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1369 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001370 }
1371 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001372
1373 OverloadCandidateSet::iterator Best;
1374 switch (BestViableFunction(CandidateSet, Best)) {
1375 case OR_Success:
1376 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001377 if (CXXConstructorDecl *Constructor
1378 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1379 // C++ [over.ics.user]p1:
1380 // If the user-defined conversion is specified by a
1381 // constructor (12.3.1), the initial standard conversion
1382 // sequence converts the source type to the type required by
1383 // the argument of the constructor.
1384 //
1385 // FIXME: What about ellipsis conversions?
1386 QualType ThisType = Constructor->getThisType(Context);
1387 User.Before = Best->Conversions[0].Standard;
1388 User.ConversionFunction = Constructor;
1389 User.After.setAsIdentityConversion();
1390 User.After.FromTypePtr
1391 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1392 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1393 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001394 } else if (CXXConversionDecl *Conversion
1395 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1396 // C++ [over.ics.user]p1:
1397 //
1398 // [...] If the user-defined conversion is specified by a
1399 // conversion function (12.3.2), the initial standard
1400 // conversion sequence converts the source type to the
1401 // implicit object parameter of the conversion function.
1402 User.Before = Best->Conversions[0].Standard;
1403 User.ConversionFunction = Conversion;
1404
1405 // C++ [over.ics.user]p2:
1406 // The second standard conversion sequence converts the
1407 // result of the user-defined conversion to the target type
1408 // for the sequence. Since an implicit conversion sequence
1409 // is an initialization, the special rules for
1410 // initialization by user-defined conversion apply when
1411 // selecting the best user-defined conversion for a
1412 // user-defined conversion sequence (see 13.3.3 and
1413 // 13.3.3.1).
1414 User.After = Best->FinalConversion;
1415 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001416 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001417 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001418 return false;
1419 }
1420
1421 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001422 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001423 // No conversion here! We're done.
1424 return false;
1425
1426 case OR_Ambiguous:
1427 // FIXME: See C++ [over.best.ics]p10 for the handling of
1428 // ambiguous conversion sequences.
1429 return false;
1430 }
1431
1432 return false;
1433}
1434
Douglas Gregord2baafd2008-10-21 16:13:35 +00001435/// CompareImplicitConversionSequences - Compare two implicit
1436/// conversion sequences to determine whether one is better than the
1437/// other or if they are indistinguishable (C++ 13.3.3.2).
1438ImplicitConversionSequence::CompareKind
1439Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1440 const ImplicitConversionSequence& ICS2)
1441{
1442 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1443 // conversion sequences (as defined in 13.3.3.1)
1444 // -- a standard conversion sequence (13.3.3.1.1) is a better
1445 // conversion sequence than a user-defined conversion sequence or
1446 // an ellipsis conversion sequence, and
1447 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1448 // conversion sequence than an ellipsis conversion sequence
1449 // (13.3.3.1.3).
1450 //
1451 if (ICS1.ConversionKind < ICS2.ConversionKind)
1452 return ImplicitConversionSequence::Better;
1453 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1454 return ImplicitConversionSequence::Worse;
1455
1456 // Two implicit conversion sequences of the same form are
1457 // indistinguishable conversion sequences unless one of the
1458 // following rules apply: (C++ 13.3.3.2p3):
1459 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1460 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1461 else if (ICS1.ConversionKind ==
1462 ImplicitConversionSequence::UserDefinedConversion) {
1463 // User-defined conversion sequence U1 is a better conversion
1464 // sequence than another user-defined conversion sequence U2 if
1465 // they contain the same user-defined conversion function or
1466 // constructor and if the second standard conversion sequence of
1467 // U1 is better than the second standard conversion sequence of
1468 // U2 (C++ 13.3.3.2p3).
1469 if (ICS1.UserDefined.ConversionFunction ==
1470 ICS2.UserDefined.ConversionFunction)
1471 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1472 ICS2.UserDefined.After);
1473 }
1474
1475 return ImplicitConversionSequence::Indistinguishable;
1476}
1477
1478/// CompareStandardConversionSequences - Compare two standard
1479/// conversion sequences to determine whether one is better than the
1480/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1481ImplicitConversionSequence::CompareKind
1482Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1483 const StandardConversionSequence& SCS2)
1484{
1485 // Standard conversion sequence S1 is a better conversion sequence
1486 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1487
1488 // -- S1 is a proper subsequence of S2 (comparing the conversion
1489 // sequences in the canonical form defined by 13.3.3.1.1,
1490 // excluding any Lvalue Transformation; the identity conversion
1491 // sequence is considered to be a subsequence of any
1492 // non-identity conversion sequence) or, if not that,
1493 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1494 // Neither is a proper subsequence of the other. Do nothing.
1495 ;
1496 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1497 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1498 (SCS1.Second == ICK_Identity &&
1499 SCS1.Third == ICK_Identity))
1500 // SCS1 is a proper subsequence of SCS2.
1501 return ImplicitConversionSequence::Better;
1502 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1503 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1504 (SCS2.Second == ICK_Identity &&
1505 SCS2.Third == ICK_Identity))
1506 // SCS2 is a proper subsequence of SCS1.
1507 return ImplicitConversionSequence::Worse;
1508
1509 // -- the rank of S1 is better than the rank of S2 (by the rules
1510 // defined below), or, if not that,
1511 ImplicitConversionRank Rank1 = SCS1.getRank();
1512 ImplicitConversionRank Rank2 = SCS2.getRank();
1513 if (Rank1 < Rank2)
1514 return ImplicitConversionSequence::Better;
1515 else if (Rank2 < Rank1)
1516 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001517
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001518 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1519 // are indistinguishable unless one of the following rules
1520 // applies:
1521
1522 // A conversion that is not a conversion of a pointer, or
1523 // pointer to member, to bool is better than another conversion
1524 // that is such a conversion.
1525 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1526 return SCS2.isPointerConversionToBool()
1527 ? ImplicitConversionSequence::Better
1528 : ImplicitConversionSequence::Worse;
1529
Douglas Gregor14046502008-10-23 00:40:37 +00001530 // C++ [over.ics.rank]p4b2:
1531 //
1532 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001533 // conversion of B* to A* is better than conversion of B* to
1534 // void*, and conversion of A* to void* is better than conversion
1535 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001536 bool SCS1ConvertsToVoid
1537 = SCS1.isPointerConversionToVoidPointer(Context);
1538 bool SCS2ConvertsToVoid
1539 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001540 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1541 // Exactly one of the conversion sequences is a conversion to
1542 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001543 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1544 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001545 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1546 // Neither conversion sequence converts to a void pointer; compare
1547 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001548 if (ImplicitConversionSequence::CompareKind DerivedCK
1549 = CompareDerivedToBaseConversions(SCS1, SCS2))
1550 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001551 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1552 // Both conversion sequences are conversions to void
1553 // pointers. Compare the source types to determine if there's an
1554 // inheritance relationship in their sources.
1555 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1556 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1557
1558 // Adjust the types we're converting from via the array-to-pointer
1559 // conversion, if we need to.
1560 if (SCS1.First == ICK_Array_To_Pointer)
1561 FromType1 = Context.getArrayDecayedType(FromType1);
1562 if (SCS2.First == ICK_Array_To_Pointer)
1563 FromType2 = Context.getArrayDecayedType(FromType2);
1564
1565 QualType FromPointee1
1566 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1567 QualType FromPointee2
1568 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1569
1570 if (IsDerivedFrom(FromPointee2, FromPointee1))
1571 return ImplicitConversionSequence::Better;
1572 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1573 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001574
1575 // Objective-C++: If one interface is more specific than the
1576 // other, it is the better one.
1577 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1578 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1579 if (FromIface1 && FromIface1) {
1580 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1581 return ImplicitConversionSequence::Better;
1582 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1583 return ImplicitConversionSequence::Worse;
1584 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001585 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001586
1587 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1588 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001589 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001590 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001591 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001592
Douglas Gregor0e343382008-10-29 14:50:44 +00001593 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001594 // C++0x [over.ics.rank]p3b4:
1595 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1596 // implicit object parameter of a non-static member function declared
1597 // without a ref-qualifier, and S1 binds an rvalue reference to an
1598 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001599 // FIXME: We don't know if we're dealing with the implicit object parameter,
1600 // or if the member function in this case has a ref qualifier.
1601 // (Of course, we don't have ref qualifiers yet.)
1602 if (SCS1.RRefBinding != SCS2.RRefBinding)
1603 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1604 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001605
1606 // C++ [over.ics.rank]p3b4:
1607 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1608 // which the references refer are the same type except for
1609 // top-level cv-qualifiers, and the type to which the reference
1610 // initialized by S2 refers is more cv-qualified than the type
1611 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001612 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1613 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001614 T1 = Context.getCanonicalType(T1);
1615 T2 = Context.getCanonicalType(T2);
1616 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1617 if (T2.isMoreQualifiedThan(T1))
1618 return ImplicitConversionSequence::Better;
1619 else if (T1.isMoreQualifiedThan(T2))
1620 return ImplicitConversionSequence::Worse;
1621 }
1622 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001623
1624 return ImplicitConversionSequence::Indistinguishable;
1625}
1626
1627/// CompareQualificationConversions - Compares two standard conversion
1628/// sequences to determine whether they can be ranked based on their
1629/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1630ImplicitConversionSequence::CompareKind
1631Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1632 const StandardConversionSequence& SCS2)
1633{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001634 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001635 // -- S1 and S2 differ only in their qualification conversion and
1636 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1637 // cv-qualification signature of type T1 is a proper subset of
1638 // the cv-qualification signature of type T2, and S1 is not the
1639 // deprecated string literal array-to-pointer conversion (4.2).
1640 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1641 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1642 return ImplicitConversionSequence::Indistinguishable;
1643
1644 // FIXME: the example in the standard doesn't use a qualification
1645 // conversion (!)
1646 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1647 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1648 T1 = Context.getCanonicalType(T1);
1649 T2 = Context.getCanonicalType(T2);
1650
1651 // If the types are the same, we won't learn anything by unwrapped
1652 // them.
1653 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1654 return ImplicitConversionSequence::Indistinguishable;
1655
1656 ImplicitConversionSequence::CompareKind Result
1657 = ImplicitConversionSequence::Indistinguishable;
1658 while (UnwrapSimilarPointerTypes(T1, T2)) {
1659 // Within each iteration of the loop, we check the qualifiers to
1660 // determine if this still looks like a qualification
1661 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001662 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001663 // until there are no more pointers or pointers-to-members left
1664 // to unwrap. This essentially mimics what
1665 // IsQualificationConversion does, but here we're checking for a
1666 // strict subset of qualifiers.
1667 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1668 // The qualifiers are the same, so this doesn't tell us anything
1669 // about how the sequences rank.
1670 ;
1671 else if (T2.isMoreQualifiedThan(T1)) {
1672 // T1 has fewer qualifiers, so it could be the better sequence.
1673 if (Result == ImplicitConversionSequence::Worse)
1674 // Neither has qualifiers that are a subset of the other's
1675 // qualifiers.
1676 return ImplicitConversionSequence::Indistinguishable;
1677
1678 Result = ImplicitConversionSequence::Better;
1679 } else if (T1.isMoreQualifiedThan(T2)) {
1680 // T2 has fewer qualifiers, so it could be the better sequence.
1681 if (Result == ImplicitConversionSequence::Better)
1682 // Neither has qualifiers that are a subset of the other's
1683 // qualifiers.
1684 return ImplicitConversionSequence::Indistinguishable;
1685
1686 Result = ImplicitConversionSequence::Worse;
1687 } else {
1688 // Qualifiers are disjoint.
1689 return ImplicitConversionSequence::Indistinguishable;
1690 }
1691
1692 // If the types after this point are equivalent, we're done.
1693 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1694 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001695 }
1696
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001697 // Check that the winning standard conversion sequence isn't using
1698 // the deprecated string literal array to pointer conversion.
1699 switch (Result) {
1700 case ImplicitConversionSequence::Better:
1701 if (SCS1.Deprecated)
1702 Result = ImplicitConversionSequence::Indistinguishable;
1703 break;
1704
1705 case ImplicitConversionSequence::Indistinguishable:
1706 break;
1707
1708 case ImplicitConversionSequence::Worse:
1709 if (SCS2.Deprecated)
1710 Result = ImplicitConversionSequence::Indistinguishable;
1711 break;
1712 }
1713
1714 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001715}
1716
Douglas Gregor14046502008-10-23 00:40:37 +00001717/// CompareDerivedToBaseConversions - Compares two standard conversion
1718/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001719/// various kinds of derived-to-base conversions (C++
1720/// [over.ics.rank]p4b3). As part of these checks, we also look at
1721/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001722ImplicitConversionSequence::CompareKind
1723Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1724 const StandardConversionSequence& SCS2) {
1725 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1726 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1727 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1728 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1729
1730 // Adjust the types we're converting from via the array-to-pointer
1731 // conversion, if we need to.
1732 if (SCS1.First == ICK_Array_To_Pointer)
1733 FromType1 = Context.getArrayDecayedType(FromType1);
1734 if (SCS2.First == ICK_Array_To_Pointer)
1735 FromType2 = Context.getArrayDecayedType(FromType2);
1736
1737 // Canonicalize all of the types.
1738 FromType1 = Context.getCanonicalType(FromType1);
1739 ToType1 = Context.getCanonicalType(ToType1);
1740 FromType2 = Context.getCanonicalType(FromType2);
1741 ToType2 = Context.getCanonicalType(ToType2);
1742
Douglas Gregor0e343382008-10-29 14:50:44 +00001743 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001744 //
1745 // If class B is derived directly or indirectly from class A and
1746 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001747 //
1748 // For Objective-C, we let A, B, and C also be Objective-C
1749 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001750
1751 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001752 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001753 SCS2.Second == ICK_Pointer_Conversion &&
1754 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1755 FromType1->isPointerType() && FromType2->isPointerType() &&
1756 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001757 QualType FromPointee1
1758 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1759 QualType ToPointee1
1760 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1761 QualType FromPointee2
1762 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1763 QualType ToPointee2
1764 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001765
1766 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1767 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1768 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1769 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1770
Douglas Gregor0e343382008-10-29 14:50:44 +00001771 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001772 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1773 if (IsDerivedFrom(ToPointee1, ToPointee2))
1774 return ImplicitConversionSequence::Better;
1775 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1776 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001777
1778 if (ToIface1 && ToIface2) {
1779 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1780 return ImplicitConversionSequence::Better;
1781 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1782 return ImplicitConversionSequence::Worse;
1783 }
Douglas Gregor14046502008-10-23 00:40:37 +00001784 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001785
1786 // -- conversion of B* to A* is better than conversion of C* to A*,
1787 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1788 if (IsDerivedFrom(FromPointee2, FromPointee1))
1789 return ImplicitConversionSequence::Better;
1790 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1791 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001792
1793 if (FromIface1 && FromIface2) {
1794 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1795 return ImplicitConversionSequence::Better;
1796 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1797 return ImplicitConversionSequence::Worse;
1798 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001799 }
Douglas Gregor14046502008-10-23 00:40:37 +00001800 }
1801
Douglas Gregor0e343382008-10-29 14:50:44 +00001802 // Compare based on reference bindings.
1803 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1804 SCS1.Second == ICK_Derived_To_Base) {
1805 // -- binding of an expression of type C to a reference of type
1806 // B& is better than binding an expression of type C to a
1807 // reference of type A&,
1808 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1809 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1810 if (IsDerivedFrom(ToType1, ToType2))
1811 return ImplicitConversionSequence::Better;
1812 else if (IsDerivedFrom(ToType2, ToType1))
1813 return ImplicitConversionSequence::Worse;
1814 }
1815
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001816 // -- binding of an expression of type B to a reference of type
1817 // A& is better than binding an expression of type C to a
1818 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001819 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1820 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1821 if (IsDerivedFrom(FromType2, FromType1))
1822 return ImplicitConversionSequence::Better;
1823 else if (IsDerivedFrom(FromType1, FromType2))
1824 return ImplicitConversionSequence::Worse;
1825 }
1826 }
1827
1828
1829 // FIXME: conversion of A::* to B::* is better than conversion of
1830 // A::* to C::*,
1831
1832 // FIXME: conversion of B::* to C::* is better than conversion of
1833 // A::* to C::*, and
1834
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001835 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1836 SCS1.Second == ICK_Derived_To_Base) {
1837 // -- conversion of C to B is better than conversion of C to A,
1838 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1839 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1840 if (IsDerivedFrom(ToType1, ToType2))
1841 return ImplicitConversionSequence::Better;
1842 else if (IsDerivedFrom(ToType2, ToType1))
1843 return ImplicitConversionSequence::Worse;
1844 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001845
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001846 // -- conversion of B to A is better than conversion of C to A.
1847 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1848 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1849 if (IsDerivedFrom(FromType2, FromType1))
1850 return ImplicitConversionSequence::Better;
1851 else if (IsDerivedFrom(FromType1, FromType2))
1852 return ImplicitConversionSequence::Worse;
1853 }
1854 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001855
Douglas Gregor14046502008-10-23 00:40:37 +00001856 return ImplicitConversionSequence::Indistinguishable;
1857}
1858
Douglas Gregor81c29152008-10-29 00:13:59 +00001859/// TryCopyInitialization - Try to copy-initialize a value of type
1860/// ToType from the expression From. Return the implicit conversion
1861/// sequence required to pass this argument, which may be a bad
1862/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001863/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001864/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1865/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001866ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001867Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001868 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001869 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001870 ImplicitConversionSequence ICS;
Sebastian Redla55834a2009-04-12 17:16:29 +00001871 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1872 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001873 return ICS;
1874 } else {
Sebastian Redla55834a2009-04-12 17:16:29 +00001875 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1876 ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001877 }
1878}
1879
Sebastian Redla55834a2009-04-12 17:16:29 +00001880/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1881/// the expression @p From. Returns true (and emits a diagnostic) if there was
1882/// an error, returns false if the initialization succeeded. Elidable should
1883/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1884/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001885bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001886 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001887 if (!getLangOptions().CPlusPlus) {
1888 // In C, argument passing is the same as performing an assignment.
1889 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001890
Douglas Gregor81c29152008-10-29 00:13:59 +00001891 AssignConvertType ConvTy =
1892 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001893 if (ConvTy != Compatible &&
1894 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1895 ConvTy = Compatible;
1896
Douglas Gregor81c29152008-10-29 00:13:59 +00001897 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1898 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001899 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001900
Chris Lattner271d4c22008-11-24 05:29:24 +00001901 if (ToType->isReferenceType())
1902 return CheckReferenceInit(From, ToType);
1903
Sebastian Redla55834a2009-04-12 17:16:29 +00001904 if (!PerformImplicitConversion(From, ToType, Flavor,
1905 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001906 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001907
Chris Lattner271d4c22008-11-24 05:29:24 +00001908 return Diag(From->getSourceRange().getBegin(),
1909 diag::err_typecheck_convert_incompatible)
1910 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001911}
1912
Douglas Gregor5ed15042008-11-18 23:14:02 +00001913/// TryObjectArgumentInitialization - Try to initialize the object
1914/// parameter of the given member function (@c Method) from the
1915/// expression @p From.
1916ImplicitConversionSequence
1917Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1918 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1919 unsigned MethodQuals = Method->getTypeQualifiers();
1920 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1921
1922 // Set up the conversion sequence as a "bad" conversion, to allow us
1923 // to exit early.
1924 ImplicitConversionSequence ICS;
1925 ICS.Standard.setAsIdentityConversion();
1926 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1927
1928 // We need to have an object of class type.
1929 QualType FromType = From->getType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001930 if (const PointerType *PT = FromType->getAsPointerType())
1931 FromType = PT->getPointeeType();
1932
1933 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00001934
1935 // The implicit object parmeter is has the type "reference to cv X",
1936 // where X is the class of which the function is a member
1937 // (C++ [over.match.funcs]p4). However, when finding an implicit
1938 // conversion sequence for the argument, we are not allowed to
1939 // create temporaries or perform user-defined conversions
1940 // (C++ [over.match.funcs]p5). We perform a simplified version of
1941 // reference binding here, that allows class rvalues to bind to
1942 // non-constant references.
1943
1944 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1945 // with the implicit object parameter (C++ [over.match.funcs]p5).
1946 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1947 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1948 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1949 return ICS;
1950
1951 // Check that we have either the same type or a derived type. It
1952 // affects the conversion rank.
1953 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1954 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1955 ICS.Standard.Second = ICK_Identity;
1956 else if (IsDerivedFrom(FromType, ClassType))
1957 ICS.Standard.Second = ICK_Derived_To_Base;
1958 else
1959 return ICS;
1960
1961 // Success. Mark this as a reference binding.
1962 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1963 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1964 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1965 ICS.Standard.ReferenceBinding = true;
1966 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00001967 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00001968 return ICS;
1969}
1970
1971/// PerformObjectArgumentInitialization - Perform initialization of
1972/// the implicit object parameter for the given Method with the given
1973/// expression.
1974bool
1975Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001976 QualType FromRecordType, DestType;
1977 QualType ImplicitParamRecordType =
1978 Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1979
1980 if (const PointerType *PT = From->getType()->getAsPointerType()) {
1981 FromRecordType = PT->getPointeeType();
1982 DestType = Method->getThisType(Context);
1983 } else {
1984 FromRecordType = From->getType();
1985 DestType = ImplicitParamRecordType;
1986 }
1987
Douglas Gregor5ed15042008-11-18 23:14:02 +00001988 ImplicitConversionSequence ICS
1989 = TryObjectArgumentInitialization(From, Method);
1990 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1991 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001992 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001993 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
1994
Douglas Gregor5ed15042008-11-18 23:14:02 +00001995 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001996 CheckDerivedToBaseConversion(FromRecordType,
1997 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00001998 From->getSourceRange().getBegin(),
1999 From->getSourceRange()))
2000 return true;
2001
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002002 ImpCastExprToType(From, DestType, /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002003 return false;
2004}
2005
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002006/// TryContextuallyConvertToBool - Attempt to contextually convert the
2007/// expression From to bool (C++0x [conv]p3).
2008ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2009 return TryImplicitConversion(From, Context.BoolTy, false, true);
2010}
2011
2012/// PerformContextuallyConvertToBool - Perform a contextual conversion
2013/// of the expression From to bool (C++0x [conv]p3).
2014bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2015 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2016 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2017 return false;
2018
2019 return Diag(From->getSourceRange().getBegin(),
2020 diag::err_typecheck_bool_condition)
2021 << From->getType() << From->getSourceRange();
2022}
2023
Douglas Gregord2baafd2008-10-21 16:13:35 +00002024/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002025/// candidate functions, using the given function call arguments. If
2026/// @p SuppressUserConversions, then don't allow user-defined
2027/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002028/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2029/// hacky way to implement the overloading rules for elidable copy
2030/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002031void
2032Sema::AddOverloadCandidate(FunctionDecl *Function,
2033 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002034 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002035 bool SuppressUserConversions,
2036 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002037{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002038 const FunctionProtoType* Proto
2039 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002040 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002041 assert(!isa<CXXConversionDecl>(Function) &&
2042 "Use AddConversionCandidate for conversion functions");
Douglas Gregord2baafd2008-10-21 16:13:35 +00002043
Douglas Gregor3257fb52008-12-22 05:46:06 +00002044 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002045 if (!isa<CXXConstructorDecl>(Method)) {
2046 // If we get here, it's because we're calling a member function
2047 // that is named without a member access expression (e.g.,
2048 // "this->f") that was either written explicitly or created
2049 // implicitly. This can happen with a qualified call to a member
2050 // function, e.g., X::f(). We use a NULL object as the implied
2051 // object argument (C++ [over.call.func]p3).
2052 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2053 SuppressUserConversions, ForceRValue);
2054 return;
2055 }
2056 // We treat a constructor like a non-member function, since its object
2057 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002058 }
2059
2060
Douglas Gregord2baafd2008-10-21 16:13:35 +00002061 // Add this candidate
2062 CandidateSet.push_back(OverloadCandidate());
2063 OverloadCandidate& Candidate = CandidateSet.back();
2064 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002065 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002066 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002067 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002068
2069 unsigned NumArgsInProto = Proto->getNumArgs();
2070
2071 // (C++ 13.3.2p2): A candidate function having fewer than m
2072 // parameters is viable only if it has an ellipsis in its parameter
2073 // list (8.3.5).
2074 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2075 Candidate.Viable = false;
2076 return;
2077 }
2078
2079 // (C++ 13.3.2p2): A candidate function having more than m parameters
2080 // is viable only if the (m+1)st parameter has a default argument
2081 // (8.3.6). For the purposes of overload resolution, the
2082 // parameter list is truncated on the right, so that there are
2083 // exactly m parameters.
2084 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2085 if (NumArgs < MinRequiredArgs) {
2086 // Not enough arguments.
2087 Candidate.Viable = false;
2088 return;
2089 }
2090
2091 // Determine the implicit conversion sequences for each of the
2092 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002093 Candidate.Conversions.resize(NumArgs);
2094 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2095 if (ArgIdx < NumArgsInProto) {
2096 // (C++ 13.3.2p3): for F to be a viable function, there shall
2097 // exist for each argument an implicit conversion sequence
2098 // (13.3.3.1) that converts that argument to the corresponding
2099 // parameter of F.
2100 QualType ParamType = Proto->getArgType(ArgIdx);
2101 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002102 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002103 SuppressUserConversions, ForceRValue);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002104 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002105 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002106 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002107 break;
2108 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002109 } else {
2110 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2111 // argument for which there is no corresponding parameter is
2112 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2113 Candidate.Conversions[ArgIdx].ConversionKind
2114 = ImplicitConversionSequence::EllipsisConversion;
2115 }
2116 }
2117}
2118
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002119/// \brief Add all of the function declarations in the given function set to
2120/// the overload canddiate set.
2121void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2122 Expr **Args, unsigned NumArgs,
2123 OverloadCandidateSet& CandidateSet,
2124 bool SuppressUserConversions) {
2125 for (FunctionSet::const_iterator F = Functions.begin(),
2126 FEnd = Functions.end();
2127 F != FEnd; ++F)
2128 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2129 SuppressUserConversions);
2130}
2131
Douglas Gregor5ed15042008-11-18 23:14:02 +00002132/// AddMethodCandidate - Adds the given C++ member function to the set
2133/// of candidate functions, using the given function call arguments
2134/// and the object argument (@c Object). For example, in a call
2135/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2136/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2137/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002138/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2139/// a slightly hacky way to implement the overloading rules for elidable copy
2140/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002141void
2142Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2143 Expr **Args, unsigned NumArgs,
2144 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002145 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002146{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002147 const FunctionProtoType* Proto
2148 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002149 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002150 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002151 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002152 assert(!isa<CXXConstructorDecl>(Method) &&
2153 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002154
2155 // Add this candidate
2156 CandidateSet.push_back(OverloadCandidate());
2157 OverloadCandidate& Candidate = CandidateSet.back();
2158 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002159 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002160 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002161
2162 unsigned NumArgsInProto = Proto->getNumArgs();
2163
2164 // (C++ 13.3.2p2): A candidate function having fewer than m
2165 // parameters is viable only if it has an ellipsis in its parameter
2166 // list (8.3.5).
2167 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2168 Candidate.Viable = false;
2169 return;
2170 }
2171
2172 // (C++ 13.3.2p2): A candidate function having more than m parameters
2173 // is viable only if the (m+1)st parameter has a default argument
2174 // (8.3.6). For the purposes of overload resolution, the
2175 // parameter list is truncated on the right, so that there are
2176 // exactly m parameters.
2177 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2178 if (NumArgs < MinRequiredArgs) {
2179 // Not enough arguments.
2180 Candidate.Viable = false;
2181 return;
2182 }
2183
2184 Candidate.Viable = true;
2185 Candidate.Conversions.resize(NumArgs + 1);
2186
Douglas Gregor3257fb52008-12-22 05:46:06 +00002187 if (Method->isStatic() || !Object)
2188 // The implicit object argument is ignored.
2189 Candidate.IgnoreObjectArgument = true;
2190 else {
2191 // Determine the implicit conversion sequence for the object
2192 // parameter.
2193 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2194 if (Candidate.Conversions[0].ConversionKind
2195 == ImplicitConversionSequence::BadConversion) {
2196 Candidate.Viable = false;
2197 return;
2198 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002199 }
2200
2201 // Determine the implicit conversion sequences for each of the
2202 // arguments.
2203 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2204 if (ArgIdx < NumArgsInProto) {
2205 // (C++ 13.3.2p3): for F to be a viable function, there shall
2206 // exist for each argument an implicit conversion sequence
2207 // (13.3.3.1) that converts that argument to the corresponding
2208 // parameter of F.
2209 QualType ParamType = Proto->getArgType(ArgIdx);
2210 Candidate.Conversions[ArgIdx + 1]
2211 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002212 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002213 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2214 == ImplicitConversionSequence::BadConversion) {
2215 Candidate.Viable = false;
2216 break;
2217 }
2218 } else {
2219 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2220 // argument for which there is no corresponding parameter is
2221 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2222 Candidate.Conversions[ArgIdx + 1].ConversionKind
2223 = ImplicitConversionSequence::EllipsisConversion;
2224 }
2225 }
2226}
2227
Douglas Gregor60714f92008-11-07 22:36:19 +00002228/// AddConversionCandidate - Add a C++ conversion function as a
2229/// candidate in the candidate set (C++ [over.match.conv],
2230/// C++ [over.match.copy]). From is the expression we're converting from,
2231/// and ToType is the type that we're eventually trying to convert to
2232/// (which may or may not be the same type as the type that the
2233/// conversion function produces).
2234void
2235Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2236 Expr *From, QualType ToType,
2237 OverloadCandidateSet& CandidateSet) {
2238 // Add this candidate
2239 CandidateSet.push_back(OverloadCandidate());
2240 OverloadCandidate& Candidate = CandidateSet.back();
2241 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002242 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002243 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002244 Candidate.FinalConversion.setAsIdentityConversion();
2245 Candidate.FinalConversion.FromTypePtr
2246 = Conversion->getConversionType().getAsOpaquePtr();
2247 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2248
Douglas Gregor5ed15042008-11-18 23:14:02 +00002249 // Determine the implicit conversion sequence for the implicit
2250 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002251 Candidate.Viable = true;
2252 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002253 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002254
Douglas Gregor60714f92008-11-07 22:36:19 +00002255 if (Candidate.Conversions[0].ConversionKind
2256 == ImplicitConversionSequence::BadConversion) {
2257 Candidate.Viable = false;
2258 return;
2259 }
2260
2261 // To determine what the conversion from the result of calling the
2262 // conversion function to the type we're eventually trying to
2263 // convert to (ToType), we need to synthesize a call to the
2264 // conversion function and attempt copy initialization from it. This
2265 // makes sure that we get the right semantics with respect to
2266 // lvalues/rvalues and the type. Fortunately, we can allocate this
2267 // call on the stack and we don't need its arguments to be
2268 // well-formed.
2269 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2270 SourceLocation());
2271 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregor70d26122008-11-12 17:17:38 +00002272 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002273
2274 // Note that it is safe to allocate CallExpr on the stack here because
2275 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2276 // allocator).
2277 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002278 Conversion->getConversionType().getNonReferenceType(),
2279 SourceLocation());
2280 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2281 switch (ICS.ConversionKind) {
2282 case ImplicitConversionSequence::StandardConversion:
2283 Candidate.FinalConversion = ICS.Standard;
2284 break;
2285
2286 case ImplicitConversionSequence::BadConversion:
2287 Candidate.Viable = false;
2288 break;
2289
2290 default:
2291 assert(false &&
2292 "Can only end up with a standard conversion sequence or failure");
2293 }
2294}
2295
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002296/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2297/// converts the given @c Object to a function pointer via the
2298/// conversion function @c Conversion, and then attempts to call it
2299/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2300/// the type of function that we'll eventually be calling.
2301void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002302 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002303 Expr *Object, Expr **Args, unsigned NumArgs,
2304 OverloadCandidateSet& CandidateSet) {
2305 CandidateSet.push_back(OverloadCandidate());
2306 OverloadCandidate& Candidate = CandidateSet.back();
2307 Candidate.Function = 0;
2308 Candidate.Surrogate = Conversion;
2309 Candidate.Viable = true;
2310 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002311 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002312 Candidate.Conversions.resize(NumArgs + 1);
2313
2314 // Determine the implicit conversion sequence for the implicit
2315 // object parameter.
2316 ImplicitConversionSequence ObjectInit
2317 = TryObjectArgumentInitialization(Object, Conversion);
2318 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2319 Candidate.Viable = false;
2320 return;
2321 }
2322
2323 // The first conversion is actually a user-defined conversion whose
2324 // first conversion is ObjectInit's standard conversion (which is
2325 // effectively a reference binding). Record it as such.
2326 Candidate.Conversions[0].ConversionKind
2327 = ImplicitConversionSequence::UserDefinedConversion;
2328 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2329 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2330 Candidate.Conversions[0].UserDefined.After
2331 = Candidate.Conversions[0].UserDefined.Before;
2332 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2333
2334 // Find the
2335 unsigned NumArgsInProto = Proto->getNumArgs();
2336
2337 // (C++ 13.3.2p2): A candidate function having fewer than m
2338 // parameters is viable only if it has an ellipsis in its parameter
2339 // list (8.3.5).
2340 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2341 Candidate.Viable = false;
2342 return;
2343 }
2344
2345 // Function types don't have any default arguments, so just check if
2346 // we have enough arguments.
2347 if (NumArgs < NumArgsInProto) {
2348 // Not enough arguments.
2349 Candidate.Viable = false;
2350 return;
2351 }
2352
2353 // Determine the implicit conversion sequences for each of the
2354 // arguments.
2355 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2356 if (ArgIdx < NumArgsInProto) {
2357 // (C++ 13.3.2p3): for F to be a viable function, there shall
2358 // exist for each argument an implicit conversion sequence
2359 // (13.3.3.1) that converts that argument to the corresponding
2360 // parameter of F.
2361 QualType ParamType = Proto->getArgType(ArgIdx);
2362 Candidate.Conversions[ArgIdx + 1]
2363 = TryCopyInitialization(Args[ArgIdx], ParamType,
2364 /*SuppressUserConversions=*/false);
2365 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2366 == ImplicitConversionSequence::BadConversion) {
2367 Candidate.Viable = false;
2368 break;
2369 }
2370 } else {
2371 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2372 // argument for which there is no corresponding parameter is
2373 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2374 Candidate.Conversions[ArgIdx + 1].ConversionKind
2375 = ImplicitConversionSequence::EllipsisConversion;
2376 }
2377 }
2378}
2379
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002380// FIXME: This will eventually be removed, once we've migrated all of
2381// the operator overloading logic over to the scheme used by binary
2382// operators, which works for template instantiation.
2383void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002384 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002385 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002386 OverloadCandidateSet& CandidateSet,
2387 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002388
2389 FunctionSet Functions;
2390
2391 QualType T1 = Args[0]->getType();
2392 QualType T2;
2393 if (NumArgs > 1)
2394 T2 = Args[1]->getType();
2395
2396 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2397 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2398 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2399 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2400 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2401 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2402}
2403
2404/// \brief Add overload candidates for overloaded operators that are
2405/// member functions.
2406///
2407/// Add the overloaded operator candidates that are member functions
2408/// for the operator Op that was used in an operator expression such
2409/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2410/// CandidateSet will store the added overload candidates. (C++
2411/// [over.match.oper]).
2412void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2413 SourceLocation OpLoc,
2414 Expr **Args, unsigned NumArgs,
2415 OverloadCandidateSet& CandidateSet,
2416 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002417 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2418
2419 // C++ [over.match.oper]p3:
2420 // For a unary operator @ with an operand of a type whose
2421 // cv-unqualified version is T1, and for a binary operator @ with
2422 // a left operand of a type whose cv-unqualified version is T1 and
2423 // a right operand of a type whose cv-unqualified version is T2,
2424 // three sets of candidate functions, designated member
2425 // candidates, non-member candidates and built-in candidates, are
2426 // constructed as follows:
2427 QualType T1 = Args[0]->getType();
2428 QualType T2;
2429 if (NumArgs > 1)
2430 T2 = Args[1]->getType();
2431
2432 // -- If T1 is a class type, the set of member candidates is the
2433 // result of the qualified lookup of T1::operator@
2434 // (13.3.1.1.1); otherwise, the set of member candidates is
2435 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002436 // FIXME: Lookup in base classes, too!
Douglas Gregor5ed15042008-11-18 23:14:02 +00002437 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002438 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002439 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002440 Oper != OperEnd; ++Oper)
2441 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2442 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002443 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002444 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002445}
2446
Douglas Gregor70d26122008-11-12 17:17:38 +00002447/// AddBuiltinCandidate - Add a candidate for a built-in
2448/// operator. ResultTy and ParamTys are the result and parameter types
2449/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002450/// arguments being passed to the candidate. IsAssignmentOperator
2451/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002452/// operator. NumContextualBoolArguments is the number of arguments
2453/// (at the beginning of the argument list) that will be contextually
2454/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002455void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2456 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002457 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002458 bool IsAssignmentOperator,
2459 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002460 // Add this candidate
2461 CandidateSet.push_back(OverloadCandidate());
2462 OverloadCandidate& Candidate = CandidateSet.back();
2463 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002464 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002465 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002466 Candidate.BuiltinTypes.ResultTy = ResultTy;
2467 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2468 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2469
2470 // Determine the implicit conversion sequences for each of the
2471 // arguments.
2472 Candidate.Viable = true;
2473 Candidate.Conversions.resize(NumArgs);
2474 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002475 // C++ [over.match.oper]p4:
2476 // For the built-in assignment operators, conversions of the
2477 // left operand are restricted as follows:
2478 // -- no temporaries are introduced to hold the left operand, and
2479 // -- no user-defined conversions are applied to the left
2480 // operand to achieve a type match with the left-most
2481 // parameter of a built-in candidate.
2482 //
2483 // We block these conversions by turning off user-defined
2484 // conversions, since that is the only way that initialization of
2485 // a reference to a non-class type can occur from something that
2486 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002487 if (ArgIdx < NumContextualBoolArguments) {
2488 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2489 "Contextual conversion to bool requires bool type");
2490 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2491 } else {
2492 Candidate.Conversions[ArgIdx]
2493 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2494 ArgIdx == 0 && IsAssignmentOperator);
2495 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002496 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002497 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002498 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002499 break;
2500 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002501 }
2502}
2503
2504/// BuiltinCandidateTypeSet - A set of types that will be used for the
2505/// candidate operator functions for built-in operators (C++
2506/// [over.built]). The types are separated into pointer types and
2507/// enumeration types.
2508class BuiltinCandidateTypeSet {
2509 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002510 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002511
2512 /// PointerTypes - The set of pointer types that will be used in the
2513 /// built-in candidates.
2514 TypeSet PointerTypes;
2515
Sebastian Redl674d1b72009-04-19 21:53:20 +00002516 /// MemberPointerTypes - The set of member pointer types that will be
2517 /// used in the built-in candidates.
2518 TypeSet MemberPointerTypes;
2519
Douglas Gregor70d26122008-11-12 17:17:38 +00002520 /// EnumerationTypes - The set of enumeration types that will be
2521 /// used in the built-in candidates.
2522 TypeSet EnumerationTypes;
2523
2524 /// Context - The AST context in which we will build the type sets.
2525 ASTContext &Context;
2526
Sebastian Redl674d1b72009-04-19 21:53:20 +00002527 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2528 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002529
2530public:
2531 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002532 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002533
2534 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2535
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002536 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2537 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002538
2539 /// pointer_begin - First pointer type found;
2540 iterator pointer_begin() { return PointerTypes.begin(); }
2541
Sebastian Redl674d1b72009-04-19 21:53:20 +00002542 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002543 iterator pointer_end() { return PointerTypes.end(); }
2544
Sebastian Redl674d1b72009-04-19 21:53:20 +00002545 /// member_pointer_begin - First member pointer type found;
2546 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2547
2548 /// member_pointer_end - Past the last member pointer type found;
2549 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2550
Douglas Gregor70d26122008-11-12 17:17:38 +00002551 /// enumeration_begin - First enumeration type found;
2552 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2553
Sebastian Redl674d1b72009-04-19 21:53:20 +00002554 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002555 iterator enumeration_end() { return EnumerationTypes.end(); }
2556};
2557
Sebastian Redl674d1b72009-04-19 21:53:20 +00002558/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002559/// the set of pointer types along with any more-qualified variants of
2560/// that type. For example, if @p Ty is "int const *", this routine
2561/// will add "int const *", "int const volatile *", "int const
2562/// restrict *", and "int const volatile restrict *" to the set of
2563/// pointer types. Returns true if the add of @p Ty itself succeeded,
2564/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002565bool
2566BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002567 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002568 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002569 return false;
2570
2571 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2572 QualType PointeeTy = PointerTy->getPointeeType();
2573 // FIXME: Optimize this so that we don't keep trying to add the same types.
2574
2575 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2576 // with all pointer conversions that don't cast away constness?
2577 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002578 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002579 (Context.getPointerType(PointeeTy.withConst()));
2580 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002581 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002582 (Context.getPointerType(PointeeTy.withVolatile()));
2583 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002584 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002585 (Context.getPointerType(PointeeTy.withRestrict()));
2586 }
2587
2588 return true;
2589}
2590
Sebastian Redl674d1b72009-04-19 21:53:20 +00002591/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2592/// to the set of pointer types along with any more-qualified variants of
2593/// that type. For example, if @p Ty is "int const *", this routine
2594/// will add "int const *", "int const volatile *", "int const
2595/// restrict *", and "int const volatile restrict *" to the set of
2596/// pointer types. Returns true if the add of @p Ty itself succeeded,
2597/// false otherwise.
2598bool
2599BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2600 QualType Ty) {
2601 // Insert this type.
2602 if (!MemberPointerTypes.insert(Ty))
2603 return false;
2604
2605 if (const MemberPointerType *PointerTy = Ty->getAsMemberPointerType()) {
2606 QualType PointeeTy = PointerTy->getPointeeType();
2607 const Type *ClassTy = PointerTy->getClass();
2608 // FIXME: Optimize this so that we don't keep trying to add the same types.
2609
2610 if (!PointeeTy.isConstQualified())
2611 AddMemberPointerWithMoreQualifiedTypeVariants
2612 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2613 if (!PointeeTy.isVolatileQualified())
2614 AddMemberPointerWithMoreQualifiedTypeVariants
2615 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2616 if (!PointeeTy.isRestrictQualified())
2617 AddMemberPointerWithMoreQualifiedTypeVariants
2618 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2619 }
2620
2621 return true;
2622}
2623
Douglas Gregor70d26122008-11-12 17:17:38 +00002624/// AddTypesConvertedFrom - Add each of the types to which the type @p
2625/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002626/// primarily interested in pointer types and enumeration types. We also
2627/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002628/// AllowUserConversions is true if we should look at the conversion
2629/// functions of a class type, and AllowExplicitConversions if we
2630/// should also include the explicit conversion functions of a class
2631/// type.
2632void
2633BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2634 bool AllowUserConversions,
2635 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002636 // Only deal with canonical types.
2637 Ty = Context.getCanonicalType(Ty);
2638
2639 // Look through reference types; they aren't part of the type of an
2640 // expression for the purposes of conversions.
2641 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2642 Ty = RefTy->getPointeeType();
2643
2644 // We don't care about qualifiers on the type.
2645 Ty = Ty.getUnqualifiedType();
2646
2647 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2648 QualType PointeeTy = PointerTy->getPointeeType();
2649
2650 // Insert our type, and its more-qualified variants, into the set
2651 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002652 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002653 return;
2654
2655 // Add 'cv void*' to our set of types.
2656 if (!Ty->isVoidType()) {
2657 QualType QualVoid
2658 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002659 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002660 }
2661
2662 // If this is a pointer to a class type, add pointers to its bases
2663 // (with the same level of cv-qualification as the original
2664 // derived class, of course).
2665 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2666 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2667 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2668 Base != ClassDecl->bases_end(); ++Base) {
2669 QualType BaseTy = Context.getCanonicalType(Base->getType());
2670 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2671
2672 // Add the pointer type, recursively, so that we get all of
2673 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002674 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002675 }
2676 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002677 } else if (Ty->isMemberPointerType()) {
2678 // Member pointers are far easier, since the pointee can't be converted.
2679 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2680 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002681 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002682 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002683 } else if (AllowUserConversions) {
2684 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2685 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2686 // FIXME: Visit conversion functions in the base classes, too.
2687 OverloadedFunctionDecl *Conversions
2688 = ClassDecl->getConversionFunctions();
2689 for (OverloadedFunctionDecl::function_iterator Func
2690 = Conversions->function_begin();
2691 Func != Conversions->function_end(); ++Func) {
2692 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002693 if (AllowExplicitConversions || !Conv->isExplicit())
2694 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002695 }
2696 }
2697 }
2698}
2699
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002700/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2701/// operator overloads to the candidate set (C++ [over.built]), based
2702/// on the operator @p Op and the arguments given. For example, if the
2703/// operator is a binary '+', this routine might add "int
2704/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002705void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002706Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2707 Expr **Args, unsigned NumArgs,
2708 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002709 // The set of "promoted arithmetic types", which are the arithmetic
2710 // types are that preserved by promotion (C++ [over.built]p2). Note
2711 // that the first few of these types are the promoted integral
2712 // types; these types need to be first.
2713 // FIXME: What about complex?
2714 const unsigned FirstIntegralType = 0;
2715 const unsigned LastIntegralType = 13;
2716 const unsigned FirstPromotedIntegralType = 7,
2717 LastPromotedIntegralType = 13;
2718 const unsigned FirstPromotedArithmeticType = 7,
2719 LastPromotedArithmeticType = 16;
2720 const unsigned NumArithmeticTypes = 16;
2721 QualType ArithmeticTypes[NumArithmeticTypes] = {
2722 Context.BoolTy, Context.CharTy, Context.WCharTy,
2723 Context.SignedCharTy, Context.ShortTy,
2724 Context.UnsignedCharTy, Context.UnsignedShortTy,
2725 Context.IntTy, Context.LongTy, Context.LongLongTy,
2726 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2727 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2728 };
2729
2730 // Find all of the types that the arguments can convert to, but only
2731 // if the operator we're looking at has built-in operator candidates
2732 // that make use of these types.
2733 BuiltinCandidateTypeSet CandidateTypes(Context);
2734 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2735 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002736 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002737 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002738 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00002739 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002740 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002741 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2742 true,
2743 (Op == OO_Exclaim ||
2744 Op == OO_AmpAmp ||
2745 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002746 }
2747
2748 bool isComparison = false;
2749 switch (Op) {
2750 case OO_None:
2751 case NUM_OVERLOADED_OPERATORS:
2752 assert(false && "Expected an overloaded operator");
2753 break;
2754
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002755 case OO_Star: // '*' is either unary or binary
2756 if (NumArgs == 1)
2757 goto UnaryStar;
2758 else
2759 goto BinaryStar;
2760 break;
2761
2762 case OO_Plus: // '+' is either unary or binary
2763 if (NumArgs == 1)
2764 goto UnaryPlus;
2765 else
2766 goto BinaryPlus;
2767 break;
2768
2769 case OO_Minus: // '-' is either unary or binary
2770 if (NumArgs == 1)
2771 goto UnaryMinus;
2772 else
2773 goto BinaryMinus;
2774 break;
2775
2776 case OO_Amp: // '&' is either unary or binary
2777 if (NumArgs == 1)
2778 goto UnaryAmp;
2779 else
2780 goto BinaryAmp;
2781
2782 case OO_PlusPlus:
2783 case OO_MinusMinus:
2784 // C++ [over.built]p3:
2785 //
2786 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2787 // is either volatile or empty, there exist candidate operator
2788 // functions of the form
2789 //
2790 // VQ T& operator++(VQ T&);
2791 // T operator++(VQ T&, int);
2792 //
2793 // C++ [over.built]p4:
2794 //
2795 // For every pair (T, VQ), where T is an arithmetic type other
2796 // than bool, and VQ is either volatile or empty, there exist
2797 // candidate operator functions of the form
2798 //
2799 // VQ T& operator--(VQ T&);
2800 // T operator--(VQ T&, int);
2801 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2802 Arith < NumArithmeticTypes; ++Arith) {
2803 QualType ArithTy = ArithmeticTypes[Arith];
2804 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00002805 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002806
2807 // Non-volatile version.
2808 if (NumArgs == 1)
2809 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2810 else
2811 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2812
2813 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00002814 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002815 if (NumArgs == 1)
2816 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2817 else
2818 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2819 }
2820
2821 // C++ [over.built]p5:
2822 //
2823 // For every pair (T, VQ), where T is a cv-qualified or
2824 // cv-unqualified object type, and VQ is either volatile or
2825 // empty, there exist candidate operator functions of the form
2826 //
2827 // T*VQ& operator++(T*VQ&);
2828 // T*VQ& operator--(T*VQ&);
2829 // T* operator++(T*VQ&, int);
2830 // T* operator--(T*VQ&, int);
2831 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2832 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2833 // Skip pointer types that aren't pointers to object types.
Douglas Gregor26ea1222009-03-24 20:32:41 +00002834 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002835 continue;
2836
2837 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002838 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002839 };
2840
2841 // Without volatile
2842 if (NumArgs == 1)
2843 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2844 else
2845 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2846
2847 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2848 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00002849 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002850 if (NumArgs == 1)
2851 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2852 else
2853 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2854 }
2855 }
2856 break;
2857
2858 UnaryStar:
2859 // C++ [over.built]p6:
2860 // For every cv-qualified or cv-unqualified object type T, there
2861 // exist candidate operator functions of the form
2862 //
2863 // T& operator*(T*);
2864 //
2865 // C++ [over.built]p7:
2866 // For every function type T, there exist candidate operator
2867 // functions of the form
2868 // T& operator*(T*);
2869 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2870 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2871 QualType ParamTy = *Ptr;
2872 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00002873 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002874 &ParamTy, Args, 1, CandidateSet);
2875 }
2876 break;
2877
2878 UnaryPlus:
2879 // C++ [over.built]p8:
2880 // For every type T, there exist candidate operator functions of
2881 // the form
2882 //
2883 // T* operator+(T*);
2884 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2885 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2886 QualType ParamTy = *Ptr;
2887 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2888 }
2889
2890 // Fall through
2891
2892 UnaryMinus:
2893 // C++ [over.built]p9:
2894 // For every promoted arithmetic type T, there exist candidate
2895 // operator functions of the form
2896 //
2897 // T operator+(T);
2898 // T operator-(T);
2899 for (unsigned Arith = FirstPromotedArithmeticType;
2900 Arith < LastPromotedArithmeticType; ++Arith) {
2901 QualType ArithTy = ArithmeticTypes[Arith];
2902 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2903 }
2904 break;
2905
2906 case OO_Tilde:
2907 // C++ [over.built]p10:
2908 // For every promoted integral type T, there exist candidate
2909 // operator functions of the form
2910 //
2911 // T operator~(T);
2912 for (unsigned Int = FirstPromotedIntegralType;
2913 Int < LastPromotedIntegralType; ++Int) {
2914 QualType IntTy = ArithmeticTypes[Int];
2915 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2916 }
2917 break;
2918
Douglas Gregor70d26122008-11-12 17:17:38 +00002919 case OO_New:
2920 case OO_Delete:
2921 case OO_Array_New:
2922 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00002923 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002924 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00002925 break;
2926
2927 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002928 UnaryAmp:
2929 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00002930 // C++ [over.match.oper]p3:
2931 // -- For the operator ',', the unary operator '&', or the
2932 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00002933 break;
2934
2935 case OO_Less:
2936 case OO_Greater:
2937 case OO_LessEqual:
2938 case OO_GreaterEqual:
2939 case OO_EqualEqual:
2940 case OO_ExclaimEqual:
2941 // C++ [over.built]p15:
2942 //
2943 // For every pointer or enumeration type T, there exist
2944 // candidate operator functions of the form
2945 //
2946 // bool operator<(T, T);
2947 // bool operator>(T, T);
2948 // bool operator<=(T, T);
2949 // bool operator>=(T, T);
2950 // bool operator==(T, T);
2951 // bool operator!=(T, T);
2952 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2953 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2954 QualType ParamTypes[2] = { *Ptr, *Ptr };
2955 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2956 }
2957 for (BuiltinCandidateTypeSet::iterator Enum
2958 = CandidateTypes.enumeration_begin();
2959 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2960 QualType ParamTypes[2] = { *Enum, *Enum };
2961 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2962 }
2963
2964 // Fall through.
2965 isComparison = true;
2966
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002967 BinaryPlus:
2968 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00002969 if (!isComparison) {
2970 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2971
2972 // C++ [over.built]p13:
2973 //
2974 // For every cv-qualified or cv-unqualified object type T
2975 // there exist candidate operator functions of the form
2976 //
2977 // T* operator+(T*, ptrdiff_t);
2978 // T& operator[](T*, ptrdiff_t); [BELOW]
2979 // T* operator-(T*, ptrdiff_t);
2980 // T* operator+(ptrdiff_t, T*);
2981 // T& operator[](ptrdiff_t, T*); [BELOW]
2982 //
2983 // C++ [over.built]p14:
2984 //
2985 // For every T, where T is a pointer to object type, there
2986 // exist candidate operator functions of the form
2987 //
2988 // ptrdiff_t operator-(T, T);
2989 for (BuiltinCandidateTypeSet::iterator Ptr
2990 = CandidateTypes.pointer_begin();
2991 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2992 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2993
2994 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2995 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2996
2997 if (Op == OO_Plus) {
2998 // T* operator+(ptrdiff_t, T*);
2999 ParamTypes[0] = ParamTypes[1];
3000 ParamTypes[1] = *Ptr;
3001 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3002 } else {
3003 // ptrdiff_t operator-(T, T);
3004 ParamTypes[1] = *Ptr;
3005 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3006 Args, 2, CandidateSet);
3007 }
3008 }
3009 }
3010 // Fall through
3011
Douglas Gregor70d26122008-11-12 17:17:38 +00003012 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003013 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003014 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003015 // C++ [over.built]p12:
3016 //
3017 // For every pair of promoted arithmetic types L and R, there
3018 // exist candidate operator functions of the form
3019 //
3020 // LR operator*(L, R);
3021 // LR operator/(L, R);
3022 // LR operator+(L, R);
3023 // LR operator-(L, R);
3024 // bool operator<(L, R);
3025 // bool operator>(L, R);
3026 // bool operator<=(L, R);
3027 // bool operator>=(L, R);
3028 // bool operator==(L, R);
3029 // bool operator!=(L, R);
3030 //
3031 // where LR is the result of the usual arithmetic conversions
3032 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003033 //
3034 // C++ [over.built]p24:
3035 //
3036 // For every pair of promoted arithmetic types L and R, there exist
3037 // candidate operator functions of the form
3038 //
3039 // LR operator?(bool, L, R);
3040 //
3041 // where LR is the result of the usual arithmetic conversions
3042 // between types L and R.
3043 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003044 for (unsigned Left = FirstPromotedArithmeticType;
3045 Left < LastPromotedArithmeticType; ++Left) {
3046 for (unsigned Right = FirstPromotedArithmeticType;
3047 Right < LastPromotedArithmeticType; ++Right) {
3048 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3049 QualType Result
3050 = isComparison? Context.BoolTy
3051 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3052 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3053 }
3054 }
3055 break;
3056
3057 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003058 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003059 case OO_Caret:
3060 case OO_Pipe:
3061 case OO_LessLess:
3062 case OO_GreaterGreater:
3063 // C++ [over.built]p17:
3064 //
3065 // For every pair of promoted integral types L and R, there
3066 // exist candidate operator functions of the form
3067 //
3068 // LR operator%(L, R);
3069 // LR operator&(L, R);
3070 // LR operator^(L, R);
3071 // LR operator|(L, R);
3072 // L operator<<(L, R);
3073 // L operator>>(L, R);
3074 //
3075 // where LR is the result of the usual arithmetic conversions
3076 // between types L and R.
3077 for (unsigned Left = FirstPromotedIntegralType;
3078 Left < LastPromotedIntegralType; ++Left) {
3079 for (unsigned Right = FirstPromotedIntegralType;
3080 Right < LastPromotedIntegralType; ++Right) {
3081 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3082 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3083 ? LandR[0]
3084 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3085 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3086 }
3087 }
3088 break;
3089
3090 case OO_Equal:
3091 // C++ [over.built]p20:
3092 //
3093 // For every pair (T, VQ), where T is an enumeration or
3094 // (FIXME:) pointer to member type and VQ is either volatile or
3095 // empty, there exist candidate operator functions of the form
3096 //
3097 // VQ T& operator=(VQ T&, T);
3098 for (BuiltinCandidateTypeSet::iterator Enum
3099 = CandidateTypes.enumeration_begin();
3100 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3101 QualType ParamTypes[2];
3102
3103 // T& operator=(T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003104 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregor70d26122008-11-12 17:17:38 +00003105 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003106 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003107 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003108
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003109 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3110 // volatile T& operator=(volatile T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003111 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003112 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003113 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003114 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003115 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003116 }
3117 // Fall through.
3118
3119 case OO_PlusEqual:
3120 case OO_MinusEqual:
3121 // C++ [over.built]p19:
3122 //
3123 // For every pair (T, VQ), where T is any type and VQ is either
3124 // volatile or empty, there exist candidate operator functions
3125 // of the form
3126 //
3127 // T*VQ& operator=(T*VQ&, T*);
3128 //
3129 // C++ [over.built]p21:
3130 //
3131 // For every pair (T, VQ), where T is a cv-qualified or
3132 // cv-unqualified object type and VQ is either volatile or
3133 // empty, there exist candidate operator functions of the form
3134 //
3135 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3136 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3137 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3138 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3139 QualType ParamTypes[2];
3140 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3141
3142 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003143 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003144 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3145 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003146
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003147 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3148 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003149 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003150 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3151 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003152 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003153 }
3154 // Fall through.
3155
3156 case OO_StarEqual:
3157 case OO_SlashEqual:
3158 // C++ [over.built]p18:
3159 //
3160 // For every triple (L, VQ, R), where L is an arithmetic type,
3161 // VQ is either volatile or empty, and R is a promoted
3162 // arithmetic type, there exist candidate operator functions of
3163 // the form
3164 //
3165 // VQ L& operator=(VQ L&, R);
3166 // VQ L& operator*=(VQ L&, R);
3167 // VQ L& operator/=(VQ L&, R);
3168 // VQ L& operator+=(VQ L&, R);
3169 // VQ L& operator-=(VQ L&, R);
3170 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3171 for (unsigned Right = FirstPromotedArithmeticType;
3172 Right < LastPromotedArithmeticType; ++Right) {
3173 QualType ParamTypes[2];
3174 ParamTypes[1] = ArithmeticTypes[Right];
3175
3176 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003177 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003178 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3179 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003180
3181 // Add this built-in operator as a candidate (VQ is 'volatile').
3182 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003183 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003184 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3185 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003186 }
3187 }
3188 break;
3189
3190 case OO_PercentEqual:
3191 case OO_LessLessEqual:
3192 case OO_GreaterGreaterEqual:
3193 case OO_AmpEqual:
3194 case OO_CaretEqual:
3195 case OO_PipeEqual:
3196 // C++ [over.built]p22:
3197 //
3198 // For every triple (L, VQ, R), where L is an integral type, VQ
3199 // is either volatile or empty, and R is a promoted integral
3200 // type, there exist candidate operator functions of the form
3201 //
3202 // VQ L& operator%=(VQ L&, R);
3203 // VQ L& operator<<=(VQ L&, R);
3204 // VQ L& operator>>=(VQ L&, R);
3205 // VQ L& operator&=(VQ L&, R);
3206 // VQ L& operator^=(VQ L&, R);
3207 // VQ L& operator|=(VQ L&, R);
3208 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3209 for (unsigned Right = FirstPromotedIntegralType;
3210 Right < LastPromotedIntegralType; ++Right) {
3211 QualType ParamTypes[2];
3212 ParamTypes[1] = ArithmeticTypes[Right];
3213
3214 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003215 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003216 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3217
3218 // Add this built-in operator as a candidate (VQ is 'volatile').
3219 ParamTypes[0] = ArithmeticTypes[Left];
3220 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003221 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003222 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3223 }
3224 }
3225 break;
3226
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003227 case OO_Exclaim: {
3228 // C++ [over.operator]p23:
3229 //
3230 // There also exist candidate operator functions of the form
3231 //
3232 // bool operator!(bool);
3233 // bool operator&&(bool, bool); [BELOW]
3234 // bool operator||(bool, bool); [BELOW]
3235 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003236 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3237 /*IsAssignmentOperator=*/false,
3238 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003239 break;
3240 }
3241
Douglas Gregor70d26122008-11-12 17:17:38 +00003242 case OO_AmpAmp:
3243 case OO_PipePipe: {
3244 // C++ [over.operator]p23:
3245 //
3246 // There also exist candidate operator functions of the form
3247 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003248 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003249 // bool operator&&(bool, bool);
3250 // bool operator||(bool, bool);
3251 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003252 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3253 /*IsAssignmentOperator=*/false,
3254 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003255 break;
3256 }
3257
3258 case OO_Subscript:
3259 // C++ [over.built]p13:
3260 //
3261 // For every cv-qualified or cv-unqualified object type T there
3262 // exist candidate operator functions of the form
3263 //
3264 // T* operator+(T*, ptrdiff_t); [ABOVE]
3265 // T& operator[](T*, ptrdiff_t);
3266 // T* operator-(T*, ptrdiff_t); [ABOVE]
3267 // T* operator+(ptrdiff_t, T*); [ABOVE]
3268 // T& operator[](ptrdiff_t, T*);
3269 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3270 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3271 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3272 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003273 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003274
3275 // T& operator[](T*, ptrdiff_t)
3276 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3277
3278 // T& operator[](ptrdiff_t, T*);
3279 ParamTypes[0] = ParamTypes[1];
3280 ParamTypes[1] = *Ptr;
3281 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3282 }
3283 break;
3284
3285 case OO_ArrowStar:
3286 // FIXME: No support for pointer-to-members yet.
3287 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003288
3289 case OO_Conditional:
3290 // Note that we don't consider the first argument, since it has been
3291 // contextually converted to bool long ago. The candidates below are
3292 // therefore added as binary.
3293 //
3294 // C++ [over.built]p24:
3295 // For every type T, where T is a pointer or pointer-to-member type,
3296 // there exist candidate operator functions of the form
3297 //
3298 // T operator?(bool, T, T);
3299 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003300 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3301 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3302 QualType ParamTypes[2] = { *Ptr, *Ptr };
3303 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3304 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003305 for (BuiltinCandidateTypeSet::iterator Ptr =
3306 CandidateTypes.member_pointer_begin(),
3307 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3308 QualType ParamTypes[2] = { *Ptr, *Ptr };
3309 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3310 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003311 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003312 }
3313}
3314
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003315/// \brief Add function candidates found via argument-dependent lookup
3316/// to the set of overloading candidates.
3317///
3318/// This routine performs argument-dependent name lookup based on the
3319/// given function name (which may also be an operator name) and adds
3320/// all of the overload candidates found by ADL to the overload
3321/// candidate set (C++ [basic.lookup.argdep]).
3322void
3323Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3324 Expr **Args, unsigned NumArgs,
3325 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003326 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003327
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003328 // Record all of the function candidates that we've already
3329 // added to the overload set, so that we don't add those same
3330 // candidates a second time.
3331 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3332 CandEnd = CandidateSet.end();
3333 Cand != CandEnd; ++Cand)
3334 if (Cand->Function)
3335 Functions.insert(Cand->Function);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003336
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003337 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003338
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003339 // Erase all of the candidates we already knew about.
3340 // FIXME: This is suboptimal. Is there a better way?
3341 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3342 CandEnd = CandidateSet.end();
3343 Cand != CandEnd; ++Cand)
3344 if (Cand->Function)
3345 Functions.erase(Cand->Function);
3346
3347 // For each of the ADL candidates we found, add it to the overload
3348 // set.
3349 for (FunctionSet::iterator Func = Functions.begin(),
3350 FuncEnd = Functions.end();
3351 Func != FuncEnd; ++Func)
3352 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003353}
3354
Douglas Gregord2baafd2008-10-21 16:13:35 +00003355/// isBetterOverloadCandidate - Determines whether the first overload
3356/// candidate is a better candidate than the second (C++ 13.3.3p1).
3357bool
3358Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3359 const OverloadCandidate& Cand2)
3360{
3361 // Define viable functions to be better candidates than non-viable
3362 // functions.
3363 if (!Cand2.Viable)
3364 return Cand1.Viable;
3365 else if (!Cand1.Viable)
3366 return false;
3367
Douglas Gregor3257fb52008-12-22 05:46:06 +00003368 // C++ [over.match.best]p1:
3369 //
3370 // -- if F is a static member function, ICS1(F) is defined such
3371 // that ICS1(F) is neither better nor worse than ICS1(G) for
3372 // any function G, and, symmetrically, ICS1(G) is neither
3373 // better nor worse than ICS1(F).
3374 unsigned StartArg = 0;
3375 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3376 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003377
3378 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3379 // function than another viable function F2 if for all arguments i,
3380 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3381 // then...
3382 unsigned NumArgs = Cand1.Conversions.size();
3383 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3384 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003385 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003386 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3387 Cand2.Conversions[ArgIdx])) {
3388 case ImplicitConversionSequence::Better:
3389 // Cand1 has a better conversion sequence.
3390 HasBetterConversion = true;
3391 break;
3392
3393 case ImplicitConversionSequence::Worse:
3394 // Cand1 can't be better than Cand2.
3395 return false;
3396
3397 case ImplicitConversionSequence::Indistinguishable:
3398 // Do nothing.
3399 break;
3400 }
3401 }
3402
3403 if (HasBetterConversion)
3404 return true;
3405
Douglas Gregor70d26122008-11-12 17:17:38 +00003406 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3407 // implemented, but they require template support.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003408
Douglas Gregor60714f92008-11-07 22:36:19 +00003409 // C++ [over.match.best]p1b4:
3410 //
3411 // -- the context is an initialization by user-defined conversion
3412 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3413 // from the return type of F1 to the destination type (i.e.,
3414 // the type of the entity being initialized) is a better
3415 // conversion sequence than the standard conversion sequence
3416 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003417 if (Cand1.Function && Cand2.Function &&
3418 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003419 isa<CXXConversionDecl>(Cand2.Function)) {
3420 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3421 Cand2.FinalConversion)) {
3422 case ImplicitConversionSequence::Better:
3423 // Cand1 has a better conversion sequence.
3424 return true;
3425
3426 case ImplicitConversionSequence::Worse:
3427 // Cand1 can't be better than Cand2.
3428 return false;
3429
3430 case ImplicitConversionSequence::Indistinguishable:
3431 // Do nothing
3432 break;
3433 }
3434 }
3435
Douglas Gregord2baafd2008-10-21 16:13:35 +00003436 return false;
3437}
3438
3439/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3440/// within an overload candidate set. If overloading is successful,
3441/// the result will be OR_Success and Best will be set to point to the
3442/// best viable function within the candidate set. Otherwise, one of
3443/// several kinds of errors will be returned; see
3444/// Sema::OverloadingResult.
3445Sema::OverloadingResult
3446Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3447 OverloadCandidateSet::iterator& Best)
3448{
3449 // Find the best viable function.
3450 Best = CandidateSet.end();
3451 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3452 Cand != CandidateSet.end(); ++Cand) {
3453 if (Cand->Viable) {
3454 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3455 Best = Cand;
3456 }
3457 }
3458
3459 // If we didn't find any viable functions, abort.
3460 if (Best == CandidateSet.end())
3461 return OR_No_Viable_Function;
3462
3463 // Make sure that this function is better than every other viable
3464 // function. If not, we have an ambiguity.
3465 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3466 Cand != CandidateSet.end(); ++Cand) {
3467 if (Cand->Viable &&
3468 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003469 !isBetterOverloadCandidate(*Best, *Cand)) {
3470 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003471 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003472 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003473 }
3474
3475 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003476 if (Best->Function &&
3477 (Best->Function->isDeleted() ||
3478 Best->Function->getAttr<UnavailableAttr>()))
3479 return OR_Deleted;
3480
3481 // If Best refers to a function that is either deleted (C++0x) or
3482 // unavailable (Clang extension) report an error.
3483
Douglas Gregord2baafd2008-10-21 16:13:35 +00003484 return OR_Success;
3485}
3486
3487/// PrintOverloadCandidates - When overload resolution fails, prints
3488/// diagnostic messages containing the candidates in the candidate
3489/// set. If OnlyViable is true, only viable candidates will be printed.
3490void
3491Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3492 bool OnlyViable)
3493{
3494 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3495 LastCand = CandidateSet.end();
3496 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003497 if (Cand->Viable || !OnlyViable) {
3498 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003499 if (Cand->Function->isDeleted() ||
3500 Cand->Function->getAttr<UnavailableAttr>()) {
3501 // Deleted or "unavailable" function.
3502 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3503 << Cand->Function->isDeleted();
3504 } else {
3505 // Normal function
3506 // FIXME: Give a better reason!
3507 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3508 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003509 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003510 // Desugar the type of the surrogate down to a function type,
3511 // retaining as many typedefs as possible while still showing
3512 // the function type (and, therefore, its parameter types).
3513 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003514 bool isLValueReference = false;
3515 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003516 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003517 if (const LValueReferenceType *FnTypeRef =
3518 FnType->getAsLValueReferenceType()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003519 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003520 isLValueReference = true;
3521 } else if (const RValueReferenceType *FnTypeRef =
3522 FnType->getAsRValueReferenceType()) {
3523 FnType = FnTypeRef->getPointeeType();
3524 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003525 }
3526 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3527 FnType = FnTypePtr->getPointeeType();
3528 isPointer = true;
3529 }
3530 // Desugar down to a function type.
3531 FnType = QualType(FnType->getAsFunctionType(), 0);
3532 // Reconstruct the pointer/reference as appropriate.
3533 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003534 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3535 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003536
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003537 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003538 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003539 } else {
3540 // FIXME: We need to get the identifier in here
3541 // FIXME: Do we want the error message to point at the
3542 // operator? (built-ins won't have a location)
3543 QualType FnType
3544 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3545 Cand->BuiltinTypes.ParamTypes,
3546 Cand->Conversions.size(),
3547 false, 0);
3548
Chris Lattner4bfd2232008-11-24 06:25:27 +00003549 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003550 }
3551 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003552 }
3553}
3554
Douglas Gregor45014fd2008-11-10 20:40:00 +00003555/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3556/// an overloaded function (C++ [over.over]), where @p From is an
3557/// expression with overloaded function type and @p ToType is the type
3558/// we're trying to resolve to. For example:
3559///
3560/// @code
3561/// int f(double);
3562/// int f(int);
3563///
3564/// int (*pfd)(double) = f; // selects f(double)
3565/// @endcode
3566///
3567/// This routine returns the resulting FunctionDecl if it could be
3568/// resolved, and NULL otherwise. When @p Complain is true, this
3569/// routine will emit diagnostics if there is an error.
3570FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003571Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003572 bool Complain) {
3573 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003574 bool IsMember = false;
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003575 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003576 FunctionType = ToTypePtr->getPointeeType();
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003577 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3578 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003579 else if (const MemberPointerType *MemTypePtr =
3580 ToType->getAsMemberPointerType()) {
3581 FunctionType = MemTypePtr->getPointeeType();
3582 IsMember = true;
3583 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003584
3585 // We only look at pointers or references to functions.
3586 if (!FunctionType->isFunctionType())
3587 return 0;
3588
3589 // Find the actual overloaded function declaration.
3590 OverloadedFunctionDecl *Ovl = 0;
3591
3592 // C++ [over.over]p1:
3593 // [...] [Note: any redundant set of parentheses surrounding the
3594 // overloaded function name is ignored (5.1). ]
3595 Expr *OvlExpr = From->IgnoreParens();
3596
3597 // C++ [over.over]p1:
3598 // [...] The overloaded function name can be preceded by the &
3599 // operator.
3600 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3601 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3602 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3603 }
3604
3605 // Try to dig out the overloaded function.
3606 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3607 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3608
3609 // If there's no overloaded function declaration, we're done.
3610 if (!Ovl)
3611 return 0;
3612
3613 // Look through all of the overloaded functions, searching for one
3614 // whose type matches exactly.
3615 // FIXME: When templates or using declarations come along, we'll actually
3616 // have to deal with duplicates, partial ordering, etc. For now, we
3617 // can just do a simple search.
3618 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3619 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3620 Fun != Ovl->function_end(); ++Fun) {
3621 // C++ [over.over]p3:
3622 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003623 // targets of type "pointer-to-function" or "reference-to-function."
3624 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003625 // type "pointer-to-member-function."
3626 // Note that according to DR 247, the containing class does not matter.
3627 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3628 // Skip non-static functions when converting to pointer, and static
3629 // when converting to member pointer.
3630 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003631 continue;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003632 } else if (IsMember)
3633 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003634
3635 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3636 return *Fun;
3637 }
3638
3639 return 0;
3640}
3641
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003642/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003643/// (which eventually refers to the declaration Func) and the call
3644/// arguments Args/NumArgs, attempt to resolve the function call down
3645/// to a specific function. If overload resolution succeeds, returns
3646/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003647/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003648/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003649FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003650 DeclarationName UnqualifiedName,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003651 SourceLocation LParenLoc,
3652 Expr **Args, unsigned NumArgs,
3653 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003654 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003655 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003656 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003657
3658 // Add the functions denoted by Callee to the set of candidate
3659 // functions. While we're doing so, track whether argument-dependent
3660 // lookup still applies, per:
3661 //
3662 // C++0x [basic.lookup.argdep]p3:
3663 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3664 // and let Y be the lookup set produced by argument dependent
3665 // lookup (defined as follows). If X contains
3666 //
3667 // -- a declaration of a class member, or
3668 //
3669 // -- a block-scope function declaration that is not a
3670 // using-declaration, or
3671 //
3672 // -- a declaration that is neither a function or a function
3673 // template
3674 //
3675 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003676 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003677 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3678 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3679 FuncEnd = Ovl->function_end();
3680 Func != FuncEnd; ++Func) {
3681 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3682
3683 if ((*Func)->getDeclContext()->isRecord() ||
3684 (*Func)->getDeclContext()->isFunctionOrMethod())
3685 ArgumentDependentLookup = false;
3686 }
3687 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3688 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3689
3690 if (Func->getDeclContext()->isRecord() ||
3691 Func->getDeclContext()->isFunctionOrMethod())
3692 ArgumentDependentLookup = false;
3693 }
3694
3695 if (Callee)
3696 UnqualifiedName = Callee->getDeclName();
3697
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003698 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003699 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003700 CandidateSet);
3701
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003702 OverloadCandidateSet::iterator Best;
3703 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003704 case OR_Success:
3705 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003706
3707 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00003708 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003709 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00003710 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003711 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3712 break;
3713
3714 case OR_Ambiguous:
3715 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003716 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003717 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3718 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00003719
3720 case OR_Deleted:
3721 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3722 << Best->Function->isDeleted()
3723 << UnqualifiedName
3724 << Fn->getSourceRange();
3725 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3726 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003727 }
3728
3729 // Overload resolution failed. Destroy all of the subexpressions and
3730 // return NULL.
3731 Fn->Destroy(Context);
3732 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3733 Args[Arg]->Destroy(Context);
3734 return 0;
3735}
3736
Douglas Gregorc78182d2009-03-13 23:49:33 +00003737/// \brief Create a unary operation that may resolve to an overloaded
3738/// operator.
3739///
3740/// \param OpLoc The location of the operator itself (e.g., '*').
3741///
3742/// \param OpcIn The UnaryOperator::Opcode that describes this
3743/// operator.
3744///
3745/// \param Functions The set of non-member functions that will be
3746/// considered by overload resolution. The caller needs to build this
3747/// set based on the context using, e.g.,
3748/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3749/// set should not contain any member functions; those will be added
3750/// by CreateOverloadedUnaryOp().
3751///
3752/// \param input The input argument.
3753Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3754 unsigned OpcIn,
3755 FunctionSet &Functions,
3756 ExprArg input) {
3757 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3758 Expr *Input = (Expr *)input.get();
3759
3760 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3761 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3762 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3763
3764 Expr *Args[2] = { Input, 0 };
3765 unsigned NumArgs = 1;
3766
3767 // For post-increment and post-decrement, add the implicit '0' as
3768 // the second argument, so that we know this is a post-increment or
3769 // post-decrement.
3770 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3771 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3772 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3773 SourceLocation());
3774 NumArgs = 2;
3775 }
3776
3777 if (Input->isTypeDependent()) {
3778 OverloadedFunctionDecl *Overloads
3779 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3780 for (FunctionSet::iterator Func = Functions.begin(),
3781 FuncEnd = Functions.end();
3782 Func != FuncEnd; ++Func)
3783 Overloads->addOverload(*Func);
3784
3785 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3786 OpLoc, false, false);
3787
3788 input.release();
3789 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3790 &Args[0], NumArgs,
3791 Context.DependentTy,
3792 OpLoc));
3793 }
3794
3795 // Build an empty overload set.
3796 OverloadCandidateSet CandidateSet;
3797
3798 // Add the candidates from the given function set.
3799 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3800
3801 // Add operator candidates that are member functions.
3802 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3803
3804 // Add builtin operator candidates.
3805 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3806
3807 // Perform overload resolution.
3808 OverloadCandidateSet::iterator Best;
3809 switch (BestViableFunction(CandidateSet, Best)) {
3810 case OR_Success: {
3811 // We found a built-in operator or an overloaded operator.
3812 FunctionDecl *FnDecl = Best->Function;
3813
3814 if (FnDecl) {
3815 // We matched an overloaded operator. Build a call to that
3816 // operator.
3817
3818 // Convert the arguments.
3819 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3820 if (PerformObjectArgumentInitialization(Input, Method))
3821 return ExprError();
3822 } else {
3823 // Convert the arguments.
3824 if (PerformCopyInitialization(Input,
3825 FnDecl->getParamDecl(0)->getType(),
3826 "passing"))
3827 return ExprError();
3828 }
3829
3830 // Determine the result type
3831 QualType ResultTy
3832 = FnDecl->getType()->getAsFunctionType()->getResultType();
3833 ResultTy = ResultTy.getNonReferenceType();
3834
3835 // Build the actual expression node.
3836 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3837 SourceLocation());
3838 UsualUnaryConversions(FnExpr);
3839
3840 input.release();
3841 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3842 &Input, 1, ResultTy,
3843 OpLoc));
3844 } else {
3845 // We matched a built-in operator. Convert the arguments, then
3846 // break out so that we will build the appropriate built-in
3847 // operator node.
3848 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3849 Best->Conversions[0], "passing"))
3850 return ExprError();
3851
3852 break;
3853 }
3854 }
3855
3856 case OR_No_Viable_Function:
3857 // No viable function; fall through to handling this as a
3858 // built-in operator, which will produce an error message for us.
3859 break;
3860
3861 case OR_Ambiguous:
3862 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3863 << UnaryOperator::getOpcodeStr(Opc)
3864 << Input->getSourceRange();
3865 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3866 return ExprError();
3867
3868 case OR_Deleted:
3869 Diag(OpLoc, diag::err_ovl_deleted_oper)
3870 << Best->Function->isDeleted()
3871 << UnaryOperator::getOpcodeStr(Opc)
3872 << Input->getSourceRange();
3873 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3874 return ExprError();
3875 }
3876
3877 // Either we found no viable overloaded operator or we matched a
3878 // built-in operator. In either case, fall through to trying to
3879 // build a built-in operation.
3880 input.release();
3881 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
3882}
3883
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003884/// \brief Create a binary operation that may resolve to an overloaded
3885/// operator.
3886///
3887/// \param OpLoc The location of the operator itself (e.g., '+').
3888///
3889/// \param OpcIn The BinaryOperator::Opcode that describes this
3890/// operator.
3891///
3892/// \param Functions The set of non-member functions that will be
3893/// considered by overload resolution. The caller needs to build this
3894/// set based on the context using, e.g.,
3895/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3896/// set should not contain any member functions; those will be added
3897/// by CreateOverloadedBinOp().
3898///
3899/// \param LHS Left-hand argument.
3900/// \param RHS Right-hand argument.
3901Sema::OwningExprResult
3902Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
3903 unsigned OpcIn,
3904 FunctionSet &Functions,
3905 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003906 Expr *Args[2] = { LHS, RHS };
3907
3908 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
3909 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
3910 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3911
3912 // If either side is type-dependent, create an appropriate dependent
3913 // expression.
3914 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
3915 // .* cannot be overloaded.
3916 if (Opc == BinaryOperator::PtrMemD)
3917 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
3918 Context.DependentTy, OpLoc));
3919
3920 OverloadedFunctionDecl *Overloads
3921 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3922 for (FunctionSet::iterator Func = Functions.begin(),
3923 FuncEnd = Functions.end();
3924 Func != FuncEnd; ++Func)
3925 Overloads->addOverload(*Func);
3926
3927 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3928 OpLoc, false, false);
3929
3930 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3931 Args, 2,
3932 Context.DependentTy,
3933 OpLoc));
3934 }
3935
3936 // If this is the .* operator, which is not overloadable, just
3937 // create a built-in binary operator.
3938 if (Opc == BinaryOperator::PtrMemD)
3939 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3940
3941 // If this is one of the assignment operators, we only perform
3942 // overload resolution if the left-hand side is a class or
3943 // enumeration type (C++ [expr.ass]p3).
3944 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3945 !LHS->getType()->isOverloadableType())
3946 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3947
Douglas Gregorc78182d2009-03-13 23:49:33 +00003948 // Build an empty overload set.
3949 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003950
3951 // Add the candidates from the given function set.
3952 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
3953
3954 // Add operator candidates that are member functions.
3955 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
3956
3957 // Add builtin operator candidates.
3958 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
3959
3960 // Perform overload resolution.
3961 OverloadCandidateSet::iterator Best;
3962 switch (BestViableFunction(CandidateSet, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003963 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003964 // We found a built-in operator or an overloaded operator.
3965 FunctionDecl *FnDecl = Best->Function;
3966
3967 if (FnDecl) {
3968 // We matched an overloaded operator. Build a call to that
3969 // operator.
3970
3971 // Convert the arguments.
3972 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3973 if (PerformObjectArgumentInitialization(LHS, Method) ||
3974 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
3975 "passing"))
3976 return ExprError();
3977 } else {
3978 // Convert the arguments.
3979 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
3980 "passing") ||
3981 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
3982 "passing"))
3983 return ExprError();
3984 }
3985
3986 // Determine the result type
3987 QualType ResultTy
3988 = FnDecl->getType()->getAsFunctionType()->getResultType();
3989 ResultTy = ResultTy.getNonReferenceType();
3990
3991 // Build the actual expression node.
3992 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3993 SourceLocation());
3994 UsualUnaryConversions(FnExpr);
3995
3996 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3997 Args, 2, ResultTy,
3998 OpLoc));
3999 } else {
4000 // We matched a built-in operator. Convert the arguments, then
4001 // break out so that we will build the appropriate built-in
4002 // operator node.
4003 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4004 Best->Conversions[0], "passing") ||
4005 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4006 Best->Conversions[1], "passing"))
4007 return ExprError();
4008
4009 break;
4010 }
4011 }
4012
4013 case OR_No_Viable_Function:
4014 // No viable function; fall through to handling this as a
4015 // built-in operator, which will produce an error message for us.
4016 break;
4017
4018 case OR_Ambiguous:
4019 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4020 << BinaryOperator::getOpcodeStr(Opc)
4021 << LHS->getSourceRange() << RHS->getSourceRange();
4022 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4023 return ExprError();
4024
4025 case OR_Deleted:
4026 Diag(OpLoc, diag::err_ovl_deleted_oper)
4027 << Best->Function->isDeleted()
4028 << BinaryOperator::getOpcodeStr(Opc)
4029 << LHS->getSourceRange() << RHS->getSourceRange();
4030 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4031 return ExprError();
4032 }
4033
4034 // Either we found no viable overloaded operator or we matched a
4035 // built-in operator. In either case, try to build a built-in
4036 // operation.
4037 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4038}
4039
Douglas Gregor3257fb52008-12-22 05:46:06 +00004040/// BuildCallToMemberFunction - Build a call to a member
4041/// function. MemExpr is the expression that refers to the member
4042/// function (and includes the object parameter), Args/NumArgs are the
4043/// arguments to the function call (not including the object
4044/// parameter). The caller needs to validate that the member
4045/// expression refers to a member function or an overloaded member
4046/// function.
4047Sema::ExprResult
4048Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4049 SourceLocation LParenLoc, Expr **Args,
4050 unsigned NumArgs, SourceLocation *CommaLocs,
4051 SourceLocation RParenLoc) {
4052 // Dig out the member expression. This holds both the object
4053 // argument and the member function we're referring to.
4054 MemberExpr *MemExpr = 0;
4055 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4056 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4057 else
4058 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4059 assert(MemExpr && "Building member call without member expression");
4060
4061 // Extract the object argument.
4062 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004063
Douglas Gregor3257fb52008-12-22 05:46:06 +00004064 CXXMethodDecl *Method = 0;
4065 if (OverloadedFunctionDecl *Ovl
4066 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
4067 // Add overload candidates
4068 OverloadCandidateSet CandidateSet;
4069 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4070 FuncEnd = Ovl->function_end();
4071 Func != FuncEnd; ++Func) {
4072 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
4073 Method = cast<CXXMethodDecl>(*Func);
4074 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4075 /*SuppressUserConversions=*/false);
4076 }
4077
4078 OverloadCandidateSet::iterator Best;
4079 switch (BestViableFunction(CandidateSet, Best)) {
4080 case OR_Success:
4081 Method = cast<CXXMethodDecl>(Best->Function);
4082 break;
4083
4084 case OR_No_Viable_Function:
4085 Diag(MemExpr->getSourceRange().getBegin(),
4086 diag::err_ovl_no_viable_member_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004087 << Ovl->getDeclName() << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004088 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4089 // FIXME: Leaking incoming expressions!
4090 return true;
4091
4092 case OR_Ambiguous:
4093 Diag(MemExpr->getSourceRange().getBegin(),
4094 diag::err_ovl_ambiguous_member_call)
4095 << Ovl->getDeclName() << MemExprE->getSourceRange();
4096 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4097 // FIXME: Leaking incoming expressions!
4098 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004099
4100 case OR_Deleted:
4101 Diag(MemExpr->getSourceRange().getBegin(),
4102 diag::err_ovl_deleted_member_call)
4103 << Best->Function->isDeleted()
4104 << Ovl->getDeclName() << MemExprE->getSourceRange();
4105 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4106 // FIXME: Leaking incoming expressions!
4107 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004108 }
4109
4110 FixOverloadedFunctionReference(MemExpr, Method);
4111 } else {
4112 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4113 }
4114
4115 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004116 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004117 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4118 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004119 Method->getResultType().getNonReferenceType(),
4120 RParenLoc));
4121
4122 // Convert the object argument (for a non-static member function call).
4123 if (!Method->isStatic() &&
4124 PerformObjectArgumentInitialization(ObjectArg, Method))
4125 return true;
4126 MemExpr->setBase(ObjectArg);
4127
4128 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004129 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004130 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4131 RParenLoc))
4132 return true;
4133
Sebastian Redl8b769972009-01-19 00:08:26 +00004134 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004135}
4136
Douglas Gregor10f3c502008-11-19 21:05:33 +00004137/// BuildCallToObjectOfClassType - Build a call to an object of class
4138/// type (C++ [over.call.object]), which can end up invoking an
4139/// overloaded function call operator (@c operator()) or performing a
4140/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004141Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004142Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4143 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004144 Expr **Args, unsigned NumArgs,
4145 SourceLocation *CommaLocs,
4146 SourceLocation RParenLoc) {
4147 assert(Object->getType()->isRecordType() && "Requires object type argument");
4148 const RecordType *Record = Object->getType()->getAsRecordType();
4149
4150 // C++ [over.call.object]p1:
4151 // If the primary-expression E in the function call syntax
4152 // evaluates to a class object of type “cv T”, then the set of
4153 // candidate functions includes at least the function call
4154 // operators of T. The function call operators of T are obtained by
4155 // ordinary lookup of the name operator() in the context of
4156 // (E).operator().
4157 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004158 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004159 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004160 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004161 Oper != OperEnd; ++Oper)
4162 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4163 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004164
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004165 // C++ [over.call.object]p2:
4166 // In addition, for each conversion function declared in T of the
4167 // form
4168 //
4169 // operator conversion-type-id () cv-qualifier;
4170 //
4171 // where cv-qualifier is the same cv-qualification as, or a
4172 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004173 // denotes the type "pointer to function of (P1,...,Pn) returning
4174 // R", or the type "reference to pointer to function of
4175 // (P1,...,Pn) returning R", or the type "reference to function
4176 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004177 // is also considered as a candidate function. Similarly,
4178 // surrogate call functions are added to the set of candidate
4179 // functions for each conversion function declared in an
4180 // accessible base class provided the function is not hidden
4181 // within T by another intervening declaration.
4182 //
4183 // FIXME: Look in base classes for more conversion operators!
4184 OverloadedFunctionDecl *Conversions
4185 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004186 for (OverloadedFunctionDecl::function_iterator
4187 Func = Conversions->function_begin(),
4188 FuncEnd = Conversions->function_end();
4189 Func != FuncEnd; ++Func) {
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004190 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4191
4192 // Strip the reference type (if any) and then the pointer type (if
4193 // any) to get down to what might be a function type.
4194 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4195 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4196 ConvType = ConvPtrType->getPointeeType();
4197
Douglas Gregor4fa58902009-02-26 23:50:07 +00004198 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004199 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4200 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004201
4202 // Perform overload resolution.
4203 OverloadCandidateSet::iterator Best;
4204 switch (BestViableFunction(CandidateSet, Best)) {
4205 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004206 // Overload resolution succeeded; we'll build the appropriate call
4207 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004208 break;
4209
4210 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004211 Diag(Object->getSourceRange().getBegin(),
4212 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004213 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004214 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004215 break;
4216
4217 case OR_Ambiguous:
4218 Diag(Object->getSourceRange().getBegin(),
4219 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004220 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004221 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4222 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004223
4224 case OR_Deleted:
4225 Diag(Object->getSourceRange().getBegin(),
4226 diag::err_ovl_deleted_object_call)
4227 << Best->Function->isDeleted()
4228 << Object->getType() << Object->getSourceRange();
4229 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4230 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004231 }
4232
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004233 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004234 // We had an error; delete all of the subexpressions and return
4235 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004236 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004237 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004238 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004239 return true;
4240 }
4241
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004242 if (Best->Function == 0) {
4243 // Since there is no function declaration, this is one of the
4244 // surrogate candidates. Dig out the conversion function.
4245 CXXConversionDecl *Conv
4246 = cast<CXXConversionDecl>(
4247 Best->Conversions[0].UserDefined.ConversionFunction);
4248
4249 // We selected one of the surrogate functions that converts the
4250 // object parameter to a function pointer. Perform the conversion
4251 // on the object argument, then let ActOnCallExpr finish the job.
4252 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004253 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004254 Conv->getConversionType().getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +00004255 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004256 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4257 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4258 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004259 }
4260
4261 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4262 // that calls this method, using Object for the implicit object
4263 // parameter and passing along the remaining arguments.
4264 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004265 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004266
4267 unsigned NumArgsInProto = Proto->getNumArgs();
4268 unsigned NumArgsToCheck = NumArgs;
4269
4270 // Build the full argument list for the method call (the
4271 // implicit object parameter is placed at the beginning of the
4272 // list).
4273 Expr **MethodArgs;
4274 if (NumArgs < NumArgsInProto) {
4275 NumArgsToCheck = NumArgsInProto;
4276 MethodArgs = new Expr*[NumArgsInProto + 1];
4277 } else {
4278 MethodArgs = new Expr*[NumArgs + 1];
4279 }
4280 MethodArgs[0] = Object;
4281 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4282 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4283
Ted Kremenek0c97e042009-02-07 01:47:29 +00004284 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4285 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004286 UsualUnaryConversions(NewFn);
4287
4288 // Once we've built TheCall, all of the expressions are properly
4289 // owned.
4290 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004291 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004292 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4293 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004294 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004295 delete [] MethodArgs;
4296
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004297 // We may have default arguments. If so, we need to allocate more
4298 // slots in the call for them.
4299 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004300 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004301 else if (NumArgs > NumArgsInProto)
4302 NumArgsToCheck = NumArgsInProto;
4303
Chris Lattner81f00ed2009-04-12 08:11:20 +00004304 bool IsError = false;
4305
Douglas Gregor10f3c502008-11-19 21:05:33 +00004306 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004307 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004308 TheCall->setArg(0, Object);
4309
Chris Lattner81f00ed2009-04-12 08:11:20 +00004310
Douglas Gregor10f3c502008-11-19 21:05:33 +00004311 // Check the argument types.
4312 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004313 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004314 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004315 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004316
4317 // Pass the argument.
4318 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004319 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004320 } else {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004321 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004322 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004323
4324 TheCall->setArg(i + 1, Arg);
4325 }
4326
4327 // If this is a variadic call, handle args passed through "...".
4328 if (Proto->isVariadic()) {
4329 // Promote the arguments (C99 6.5.2.2p7).
4330 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4331 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004332 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004333 TheCall->setArg(i + 1, Arg);
4334 }
4335 }
4336
Chris Lattner81f00ed2009-04-12 08:11:20 +00004337 if (IsError) return true;
4338
Sebastian Redl8b769972009-01-19 00:08:26 +00004339 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004340}
4341
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004342/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4343/// (if one exists), where @c Base is an expression of class type and
4344/// @c Member is the name of the member we're trying to find.
4345Action::ExprResult
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004346Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004347 SourceLocation MemberLoc,
4348 IdentifierInfo &Member) {
4349 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4350
4351 // C++ [over.ref]p1:
4352 //
4353 // [...] An expression x->m is interpreted as (x.operator->())->m
4354 // for a class object x of type T if T::operator->() exists and if
4355 // the operator is selected as the best match function by the
4356 // overload resolution mechanism (13.3).
4357 // FIXME: look in base classes.
4358 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4359 OverloadCandidateSet CandidateSet;
4360 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004361
4362 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004363 for (llvm::tie(Oper, OperEnd)
4364 = BaseRecord->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004365 Oper != OperEnd; ++Oper)
4366 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004367 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004368
Ted Kremenek0c97e042009-02-07 01:47:29 +00004369 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004370
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004371 // Perform overload resolution.
4372 OverloadCandidateSet::iterator Best;
4373 switch (BestViableFunction(CandidateSet, Best)) {
4374 case OR_Success:
4375 // Overload resolution succeeded; we'll build the call below.
4376 break;
4377
4378 case OR_No_Viable_Function:
4379 if (CandidateSet.empty())
4380 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004381 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004382 else
4383 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Chris Lattner4a526112009-02-17 07:29:20 +00004384 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004385 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004386 return true;
4387
4388 case OR_Ambiguous:
4389 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004390 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004391 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004392 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004393
4394 case OR_Deleted:
4395 Diag(OpLoc, diag::err_ovl_deleted_oper)
4396 << Best->Function->isDeleted()
4397 << "operator->" << BasePtr->getSourceRange();
4398 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4399 return true;
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004400 }
4401
4402 // Convert the object parameter.
4403 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004404 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004405 return true;
Douglas Gregor9c690e92008-11-21 03:04:22 +00004406
4407 // No concerns about early exits now.
4408 BasePtr.take();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004409
4410 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004411 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4412 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004413 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004414 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004415 Method->getResultType().getNonReferenceType(),
4416 OpLoc);
Sebastian Redl8b769972009-01-19 00:08:26 +00004417 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
Chris Lattner5261d0c2009-03-28 19:18:32 +00004418 MemberLoc, Member, DeclPtrTy()).release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004419}
4420
Douglas Gregor45014fd2008-11-10 20:40:00 +00004421/// FixOverloadedFunctionReference - E is an expression that refers to
4422/// a C++ overloaded function (possibly with some parentheses and
4423/// perhaps a '&' around it). We have resolved the overloaded function
4424/// to the function declaration Fn, so patch up the expression E to
4425/// refer (possibly indirectly) to Fn.
4426void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4427 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4428 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4429 E->setType(PE->getSubExpr()->getType());
4430 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4431 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4432 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004433 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4434 if (Method->isStatic()) {
4435 // Do nothing: static member functions aren't any different
4436 // from non-member functions.
4437 }
4438 else if (QualifiedDeclRefExpr *DRE
4439 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4440 // We have taken the address of a pointer to member
4441 // function. Perform the computation here so that we get the
4442 // appropriate pointer to member type.
4443 DRE->setDecl(Fn);
4444 DRE->setType(Fn->getType());
4445 QualType ClassType
4446 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4447 E->setType(Context.getMemberPointerType(Fn->getType(),
4448 ClassType.getTypePtr()));
4449 return;
4450 }
4451 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004452 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004453 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004454 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4455 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4456 "Expected overloaded function");
4457 DR->setDecl(Fn);
4458 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004459 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4460 MemExpr->setMemberDecl(Fn);
4461 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004462 } else {
4463 assert(false && "Invalid reference to overloaded function");
4464 }
4465}
4466
Douglas Gregord2baafd2008-10-21 16:13:35 +00004467} // end namespace clang