blob: 5321935cfc7bfd88f3c72e4f0e1912d2743b814c [file] [log] [blame]
Douglas Gregord2baafd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor10f3c502008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000042 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000045 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000050 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000051 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000052 ICC_Conversion
53 };
54 return Category[(int)Kind];
55}
56
57/// GetConversionRank - Retrieve the implicit conversion rank
58/// corresponding to the given implicit conversion kind.
59ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
60 static const ImplicitConversionRank
61 Rank[(int)ICK_Num_Conversion_Kinds] = {
62 ICR_Exact_Match,
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Promotion,
68 ICR_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000069 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000072 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000077 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000078 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000079 ICR_Conversion
80 };
81 return Rank[(int)Kind];
82}
83
84/// GetImplicitConversionName - Return the name of this kind of
85/// implicit conversion.
86const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
87 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
88 "No conversion",
89 "Lvalue-to-rvalue",
90 "Array-to-pointer",
91 "Function-to-pointer",
92 "Qualification",
93 "Integral promotion",
94 "Floating point promotion",
Douglas Gregore819caf2009-02-12 00:15:05 +000095 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000096 "Integral conversion",
97 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +000098 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000099 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000100 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000101 "Pointer conversion",
102 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000103 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000104 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000105 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000106 };
107 return Name[Kind];
108}
109
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113 First = ICK_Identity;
114 Second = ICK_Identity;
115 Third = ICK_Identity;
116 Deprecated = false;
117 ReferenceBinding = false;
118 DirectBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000119 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000120}
121
Douglas Gregord2baafd2008-10-21 16:13:35 +0000122/// getRank - Retrieve the rank of this standard conversion sequence
123/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
124/// implicit conversions.
125ImplicitConversionRank StandardConversionSequence::getRank() const {
126 ImplicitConversionRank Rank = ICR_Exact_Match;
127 if (GetConversionRank(First) > Rank)
128 Rank = GetConversionRank(First);
129 if (GetConversionRank(Second) > Rank)
130 Rank = GetConversionRank(Second);
131 if (GetConversionRank(Third) > Rank)
132 Rank = GetConversionRank(Third);
133 return Rank;
134}
135
136/// isPointerConversionToBool - Determines whether this conversion is
137/// a conversion of a pointer or pointer-to-member to bool. This is
138/// used as part of the ranking of standard conversion sequences
139/// (C++ 13.3.3.2p4).
140bool StandardConversionSequence::isPointerConversionToBool() const
141{
142 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
143 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
144
145 // Note that FromType has not necessarily been transformed by the
146 // array-to-pointer or function-to-pointer implicit conversions, so
147 // check for their presence as well as checking whether FromType is
148 // a pointer.
149 if (ToType->isBooleanType() &&
Douglas Gregor80402cf2008-12-23 00:53:59 +0000150 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000151 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
152 return true;
153
154 return false;
155}
156
Douglas Gregor14046502008-10-23 00:40:37 +0000157/// isPointerConversionToVoidPointer - Determines whether this
158/// conversion is a conversion of a pointer to a void pointer. This is
159/// used as part of the ranking of standard conversion sequences (C++
160/// 13.3.3.2p4).
161bool
162StandardConversionSequence::
163isPointerConversionToVoidPointer(ASTContext& Context) const
164{
165 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
166 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
167
168 // Note that FromType has not necessarily been transformed by the
169 // array-to-pointer implicit conversion, so check for its presence
170 // and redo the conversion to get a pointer.
171 if (First == ICK_Array_To_Pointer)
172 FromType = Context.getArrayDecayedType(FromType);
173
174 if (Second == ICK_Pointer_Conversion)
175 if (const PointerType* ToPtrType = ToType->getAsPointerType())
176 return ToPtrType->getPointeeType()->isVoidType();
177
178 return false;
179}
180
Douglas Gregord2baafd2008-10-21 16:13:35 +0000181/// DebugPrint - Print this standard conversion sequence to standard
182/// error. Useful for debugging overloading issues.
183void StandardConversionSequence::DebugPrint() const {
184 bool PrintedSomething = false;
185 if (First != ICK_Identity) {
186 fprintf(stderr, "%s", GetImplicitConversionName(First));
187 PrintedSomething = true;
188 }
189
190 if (Second != ICK_Identity) {
191 if (PrintedSomething) {
192 fprintf(stderr, " -> ");
193 }
194 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000195
196 if (CopyConstructor) {
197 fprintf(stderr, " (by copy constructor)");
198 } else if (DirectBinding) {
199 fprintf(stderr, " (direct reference binding)");
200 } else if (ReferenceBinding) {
201 fprintf(stderr, " (reference binding)");
202 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000203 PrintedSomething = true;
204 }
205
206 if (Third != ICK_Identity) {
207 if (PrintedSomething) {
208 fprintf(stderr, " -> ");
209 }
210 fprintf(stderr, "%s", GetImplicitConversionName(Third));
211 PrintedSomething = true;
212 }
213
214 if (!PrintedSomething) {
215 fprintf(stderr, "No conversions required");
216 }
217}
218
219/// DebugPrint - Print this user-defined conversion sequence to standard
220/// error. Useful for debugging overloading issues.
221void UserDefinedConversionSequence::DebugPrint() const {
222 if (Before.First || Before.Second || Before.Third) {
223 Before.DebugPrint();
224 fprintf(stderr, " -> ");
225 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000226 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000227 if (After.First || After.Second || After.Third) {
228 fprintf(stderr, " -> ");
229 After.DebugPrint();
230 }
231}
232
233/// DebugPrint - Print this implicit conversion sequence to standard
234/// error. Useful for debugging overloading issues.
235void ImplicitConversionSequence::DebugPrint() const {
236 switch (ConversionKind) {
237 case StandardConversion:
238 fprintf(stderr, "Standard conversion: ");
239 Standard.DebugPrint();
240 break;
241 case UserDefinedConversion:
242 fprintf(stderr, "User-defined conversion: ");
243 UserDefined.DebugPrint();
244 break;
245 case EllipsisConversion:
246 fprintf(stderr, "Ellipsis conversion");
247 break;
248 case BadConversion:
249 fprintf(stderr, "Bad conversion");
250 break;
251 }
252
253 fprintf(stderr, "\n");
254}
255
256// IsOverload - Determine whether the given New declaration is an
257// overload of the Old declaration. This routine returns false if New
258// and Old cannot be overloaded, e.g., if they are functions with the
259// same signature (C++ 1.3.10) or if the Old declaration isn't a
260// function (or overload set). When it does return false and Old is an
261// OverloadedFunctionDecl, MatchedDecl will be set to point to the
262// FunctionDecl that New cannot be overloaded with.
263//
264// Example: Given the following input:
265//
266// void f(int, float); // #1
267// void f(int, int); // #2
268// int f(int, int); // #3
269//
270// When we process #1, there is no previous declaration of "f",
271// so IsOverload will not be used.
272//
273// When we process #2, Old is a FunctionDecl for #1. By comparing the
274// parameter types, we see that #1 and #2 are overloaded (since they
275// have different signatures), so this routine returns false;
276// MatchedDecl is unchanged.
277//
278// When we process #3, Old is an OverloadedFunctionDecl containing #1
279// and #2. We compare the signatures of #3 to #1 (they're overloaded,
280// so we do nothing) and then #3 to #2. Since the signatures of #3 and
281// #2 are identical (return types of functions are not part of the
282// signature), IsOverload returns false and MatchedDecl will be set to
283// point to the FunctionDecl for #2.
284bool
285Sema::IsOverload(FunctionDecl *New, Decl* OldD,
286 OverloadedFunctionDecl::function_iterator& MatchedDecl)
287{
288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
290 // overload set?
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
295 MatchedDecl = Func;
296 return false;
297 }
298 }
299
300 // This function overloads every function in the overload set.
301 return true;
302 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
303 // Is the function New an overload of the function Old?
304 QualType OldQType = Context.getCanonicalType(Old->getType());
305 QualType NewQType = Context.getCanonicalType(New->getType());
306
307 // Compare the signatures (C++ 1.3.10) of the two functions to
308 // determine whether they are overloads. If we find any mismatch
309 // in the signature, they are overloads.
310
311 // If either of these functions is a K&R-style function (no
312 // prototype), then we consider them to have matching signatures.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000313 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
314 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000315 return false;
316
Douglas Gregor4fa58902009-02-26 23:50:07 +0000317 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType.getTypePtr());
318 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType.getTypePtr());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000319
320 // The signature of a function includes the types of its
321 // parameters (C++ 1.3.10), which includes the presence or absence
322 // of the ellipsis; see C++ DR 357).
323 if (OldQType != NewQType &&
324 (OldType->getNumArgs() != NewType->getNumArgs() ||
325 OldType->isVariadic() != NewType->isVariadic() ||
326 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
327 NewType->arg_type_begin())))
328 return true;
329
330 // If the function is a class member, its signature includes the
331 // cv-qualifiers (if any) on the function itself.
332 //
333 // As part of this, also check whether one of the member functions
334 // is static, in which case they are not overloads (C++
335 // 13.1p2). While not part of the definition of the signature,
336 // this check is important to determine whether these functions
337 // can be overloaded.
338 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
339 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
340 if (OldMethod && NewMethod &&
341 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000342 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000343 return true;
344
345 // The signatures match; this is not an overload.
346 return false;
347 } else {
348 // (C++ 13p1):
349 // Only function declarations can be overloaded; object and type
350 // declarations cannot be overloaded.
351 return false;
352 }
353}
354
Douglas Gregor81c29152008-10-29 00:13:59 +0000355/// TryImplicitConversion - Attempt to perform an implicit conversion
356/// from the given expression (Expr) to the given type (ToType). This
357/// function returns an implicit conversion sequence that can be used
358/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000359///
360/// void f(float f);
361/// void g(int i) { f(i); }
362///
363/// this routine would produce an implicit conversion sequence to
364/// describe the initialization of f from i, which will be a standard
365/// conversion sequence containing an lvalue-to-rvalue conversion (C++
366/// 4.1) followed by a floating-integral conversion (C++ 4.9).
367//
368/// Note that this routine only determines how the conversion can be
369/// performed; it does not actually perform the conversion. As such,
370/// it will not produce any diagnostics if no conversion is available,
371/// but will instead return an implicit conversion sequence of kind
372/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000373///
374/// If @p SuppressUserConversions, then user-defined conversions are
375/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000376/// If @p AllowExplicit, then explicit user-defined conversions are
377/// permitted.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000378ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000379Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000380 bool SuppressUserConversions,
Douglas Gregorb206cc42009-01-30 23:27:23 +0000381 bool AllowExplicit)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000382{
383 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000384 if (IsStandardConversion(From, ToType, ICS.Standard))
385 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000386 else if (getLangOptions().CPlusPlus &&
387 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregorb206cc42009-01-30 23:27:23 +0000388 !SuppressUserConversions, AllowExplicit)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000389 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000390 // C++ [over.ics.user]p4:
391 // A conversion of an expression of class type to the same class
392 // type is given Exact Match rank, and a conversion of an
393 // expression of class type to a base class of that type is
394 // given Conversion rank, in spite of the fact that a copy
395 // constructor (i.e., a user-defined conversion function) is
396 // called for those cases.
397 if (CXXConstructorDecl *Constructor
398 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregord9176392009-02-02 22:11:10 +0000399 QualType FromCanon
400 = Context.getCanonicalType(From->getType().getUnqualifiedType());
401 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
402 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000403 // Turn this into a "standard" conversion sequence, so that it
404 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000405 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
406 ICS.Standard.setAsIdentityConversion();
407 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
408 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000409 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000410 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000411 ICS.Standard.Second = ICK_Derived_To_Base;
412 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000413 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000414
415 // C++ [over.best.ics]p4:
416 // However, when considering the argument of a user-defined
417 // conversion function that is a candidate by 13.3.1.3 when
418 // invoked for the copying of the temporary in the second step
419 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
420 // 13.3.1.6 in all cases, only standard conversion sequences and
421 // ellipsis conversion sequences are allowed.
422 if (SuppressUserConversions &&
423 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
424 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000425 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000426 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000427
428 return ICS;
429}
430
431/// IsStandardConversion - Determines whether there is a standard
432/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
433/// expression From to the type ToType. Standard conversion sequences
434/// only consider non-class types; for conversions that involve class
435/// types, use TryImplicitConversion. If a conversion exists, SCS will
436/// contain the standard conversion sequence required to perform this
437/// conversion and this routine will return true. Otherwise, this
438/// routine will return false and the value of SCS is unspecified.
439bool
440Sema::IsStandardConversion(Expr* From, QualType ToType,
441 StandardConversionSequence &SCS)
442{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000443 QualType FromType = From->getType();
444
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000445 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000446 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000447 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000448 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000449 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000450 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000451
Douglas Gregorfcb19192009-02-11 23:02:49 +0000452 // There are no standard conversions for class types in C++, so
453 // abort early. When overloading in C, however, we do permit
454 if (FromType->isRecordType() || ToType->isRecordType()) {
455 if (getLangOptions().CPlusPlus)
456 return false;
457
458 // When we're overloading in C, we allow, as standard conversions,
459 }
460
Douglas Gregord2baafd2008-10-21 16:13:35 +0000461 // The first conversion can be an lvalue-to-rvalue conversion,
462 // array-to-pointer conversion, or function-to-pointer conversion
463 // (C++ 4p1).
464
465 // Lvalue-to-rvalue conversion (C++ 4.1):
466 // An lvalue (3.10) of a non-function, non-array type T can be
467 // converted to an rvalue.
468 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
469 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000470 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000471 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000472 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000473
474 // If T is a non-class type, the type of the rvalue is the
475 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000476 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
477 // just strip the qualifiers because they don't matter.
478
479 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000480 FromType = FromType.getUnqualifiedType();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000481 }
482 // Array-to-pointer conversion (C++ 4.2)
483 else if (FromType->isArrayType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000484 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000485
486 // An lvalue or rvalue of type "array of N T" or "array of unknown
487 // bound of T" can be converted to an rvalue of type "pointer to
488 // T" (C++ 4.2p1).
489 FromType = Context.getArrayDecayedType(FromType);
490
491 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
492 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000493 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000494
495 // For the purpose of ranking in overload resolution
496 // (13.3.3.1.1), this conversion is considered an
497 // array-to-pointer conversion followed by a qualification
498 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000499 SCS.Second = ICK_Identity;
500 SCS.Third = ICK_Qualification;
501 SCS.ToTypePtr = ToType.getAsOpaquePtr();
502 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000503 }
504 }
505 // Function-to-pointer conversion (C++ 4.3).
506 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000507 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000508
509 // An lvalue of function type T can be converted to an rvalue of
510 // type "pointer to T." The result is a pointer to the
511 // function. (C++ 4.3p1).
512 FromType = Context.getPointerType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000513 }
Douglas Gregor45014fd2008-11-10 20:40:00 +0000514 // Address of overloaded function (C++ [over.over]).
515 else if (FunctionDecl *Fn
516 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
517 SCS.First = ICK_Function_To_Pointer;
518
519 // We were able to resolve the address of the overloaded function,
520 // so we can convert to the type of that function.
521 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000522 if (ToType->isLValueReferenceType())
523 FromType = Context.getLValueReferenceType(FromType);
524 else if (ToType->isRValueReferenceType())
525 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000526 else if (ToType->isMemberPointerType()) {
527 // Resolve address only succeeds if both sides are member pointers,
528 // but it doesn't have to be the same class. See DR 247.
529 // Note that this means that the type of &Derived::fn can be
530 // Ret (Base::*)(Args) if the fn overload actually found is from the
531 // base class, even if it was brought into the derived class via a
532 // using declaration. The standard isn't clear on this issue at all.
533 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
534 FromType = Context.getMemberPointerType(FromType,
535 Context.getTypeDeclType(M->getParent()).getTypePtr());
536 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000537 FromType = Context.getPointerType(FromType);
538 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000539 // We don't require any conversions for the first step.
540 else {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000541 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000542 }
543
544 // The second conversion can be an integral promotion, floating
545 // point promotion, integral conversion, floating point conversion,
546 // floating-integral conversion, pointer conversion,
547 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000548 // For overloading in C, this can also be a "compatible-type"
549 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000550 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000551 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000552 // The unqualified versions of the types are the same: there's no
553 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000554 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000555 }
556 // Integral promotion (C++ 4.5).
557 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000558 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000559 FromType = ToType.getUnqualifiedType();
560 }
561 // Floating point promotion (C++ 4.6).
562 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000563 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000564 FromType = ToType.getUnqualifiedType();
565 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000566 // Complex promotion (Clang extension)
567 else if (IsComplexPromotion(FromType, ToType)) {
568 SCS.Second = ICK_Complex_Promotion;
569 FromType = ToType.getUnqualifiedType();
570 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000571 // Integral conversions (C++ 4.7).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000572 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000573 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000574 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000575 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000576 FromType = ToType.getUnqualifiedType();
577 }
578 // Floating point conversions (C++ 4.8).
579 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000580 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000581 FromType = ToType.getUnqualifiedType();
582 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000583 // Complex conversions (C99 6.3.1.6)
584 else if (FromType->isComplexType() && ToType->isComplexType()) {
585 SCS.Second = ICK_Complex_Conversion;
586 FromType = ToType.getUnqualifiedType();
587 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000588 // Floating-integral conversions (C++ 4.9).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000589 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000590 else if ((FromType->isFloatingType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000591 ToType->isIntegralType() && !ToType->isBooleanType() &&
592 !ToType->isEnumeralType()) ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000593 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
594 ToType->isFloatingType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000595 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000596 FromType = ToType.getUnqualifiedType();
597 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000598 // Complex-real conversions (C99 6.3.1.7)
599 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
600 (ToType->isComplexType() && FromType->isArithmeticType())) {
601 SCS.Second = ICK_Complex_Real;
602 FromType = ToType.getUnqualifiedType();
603 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000604 // Pointer conversions (C++ 4.10).
Douglas Gregor6fd35572008-12-19 17:40:08 +0000605 else if (IsPointerConversion(From, FromType, ToType, FromType,
606 IncompatibleObjC)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000607 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000608 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000609 }
Sebastian Redlba387562009-01-25 19:43:20 +0000610 // Pointer to member conversions (4.11).
611 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
612 SCS.Second = ICK_Pointer_Member;
613 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000614 // Boolean conversions (C++ 4.12).
Douglas Gregord2baafd2008-10-21 16:13:35 +0000615 else if (ToType->isBooleanType() &&
616 (FromType->isArithmeticType() ||
617 FromType->isEnumeralType() ||
Douglas Gregor80402cf2008-12-23 00:53:59 +0000618 FromType->isPointerType() ||
Sebastian Redlba387562009-01-25 19:43:20 +0000619 FromType->isBlockPointerType() ||
620 FromType->isMemberPointerType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000621 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000622 FromType = Context.BoolTy;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000623 }
624 // Compatible conversions (Clang extension for C function overloading)
625 else if (!getLangOptions().CPlusPlus &&
626 Context.typesAreCompatible(ToType, FromType)) {
627 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000628 } else {
629 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000630 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000631 }
632
Douglas Gregor81c29152008-10-29 00:13:59 +0000633 QualType CanonFrom;
634 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000635 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000636 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000637 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000638 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000639 CanonFrom = Context.getCanonicalType(FromType);
640 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000641 } else {
642 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000643 SCS.Third = ICK_Identity;
644
645 // C++ [over.best.ics]p6:
646 // [...] Any difference in top-level cv-qualification is
647 // subsumed by the initialization itself and does not constitute
648 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000649 CanonFrom = Context.getCanonicalType(FromType);
650 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000651 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000652 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
653 FromType = ToType;
654 CanonFrom = CanonTo;
655 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000656 }
657
658 // If we have not converted the argument type to the parameter type,
659 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000660 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000661 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000662
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000663 SCS.ToTypePtr = FromType.getAsOpaquePtr();
664 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000665}
666
667/// IsIntegralPromotion - Determines whether the conversion from the
668/// expression From (whose potentially-adjusted type is FromType) to
669/// ToType is an integral promotion (C++ 4.5). If so, returns true and
670/// sets PromotedType to the promoted type.
671bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
672{
673 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000674 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000675 if (!To) {
676 return false;
677 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000678
679 // An rvalue of type char, signed char, unsigned char, short int, or
680 // unsigned short int can be converted to an rvalue of type int if
681 // int can represent all the values of the source type; otherwise,
682 // the source rvalue can be converted to an rvalue of type unsigned
683 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000684 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000685 if (// We can promote any signed, promotable integer type to an int
686 (FromType->isSignedIntegerType() ||
687 // We can promote any unsigned integer type whose size is
688 // less than int to an int.
689 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000690 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000691 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000692 }
693
Douglas Gregord2baafd2008-10-21 16:13:35 +0000694 return To->getKind() == BuiltinType::UInt;
695 }
696
697 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
698 // can be converted to an rvalue of the first of the following types
699 // that can represent all the values of its underlying type: int,
700 // unsigned int, long, or unsigned long (C++ 4.5p2).
701 if ((FromType->isEnumeralType() || FromType->isWideCharType())
702 && ToType->isIntegerType()) {
703 // Determine whether the type we're converting from is signed or
704 // unsigned.
705 bool FromIsSigned;
706 uint64_t FromSize = Context.getTypeSize(FromType);
707 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
708 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
709 FromIsSigned = UnderlyingType->isSignedIntegerType();
710 } else {
711 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
712 FromIsSigned = true;
713 }
714
715 // The types we'll try to promote to, in the appropriate
716 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000717 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000718 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000719 Context.LongTy, Context.UnsignedLongTy ,
720 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000721 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000722 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000723 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
724 if (FromSize < ToSize ||
725 (FromSize == ToSize &&
726 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
727 // We found the type that we can promote to. If this is the
728 // type we wanted, we have a promotion. Otherwise, no
729 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000730 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000731 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
732 }
733 }
734 }
735
736 // An rvalue for an integral bit-field (9.6) can be converted to an
737 // rvalue of type int if int can represent all the values of the
738 // bit-field; otherwise, it can be converted to unsigned int if
739 // unsigned int can represent all the values of the bit-field. If
740 // the bit-field is larger yet, no integral promotion applies to
741 // it. If the bit-field has an enumerated type, it is treated as any
742 // other value of that type for promotion purposes (C++ 4.5p3).
Douglas Gregor4ff48512009-02-12 00:26:06 +0000743 // FIXME: We should delay checking of bit-fields until we actually
744 // perform the conversion.
745 if (MemberExpr *MemRef = dyn_cast_or_null<MemberExpr>(From)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000746 using llvm::APSInt;
Douglas Gregor82d44772008-12-20 23:49:58 +0000747 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
748 APSInt BitWidth;
749 if (MemberDecl->isBitField() &&
750 FromType->isIntegralType() && !FromType->isEnumeralType() &&
751 From->isIntegerConstantExpr(BitWidth, Context)) {
752 APSInt ToSize(Context.getTypeSize(ToType));
753
754 // Are we promoting to an int from a bitfield that fits in an int?
755 if (BitWidth < ToSize ||
756 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
757 return To->getKind() == BuiltinType::Int;
758 }
759
760 // Are we promoting to an unsigned int from an unsigned bitfield
761 // that fits into an unsigned int?
762 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
763 return To->getKind() == BuiltinType::UInt;
764 }
765
766 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000767 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000768 }
769 }
770
771 // An rvalue of type bool can be converted to an rvalue of type int,
772 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000773 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000774 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000775 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000776
777 return false;
778}
779
780/// IsFloatingPointPromotion - Determines whether the conversion from
781/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
782/// returns true and sets PromotedType to the promoted type.
783bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
784{
785 /// An rvalue of type float can be converted to an rvalue of type
786 /// double. (C++ 4.6p1).
787 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000788 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000789 if (FromBuiltin->getKind() == BuiltinType::Float &&
790 ToBuiltin->getKind() == BuiltinType::Double)
791 return true;
792
Douglas Gregore819caf2009-02-12 00:15:05 +0000793 // C99 6.3.1.5p1:
794 // When a float is promoted to double or long double, or a
795 // double is promoted to long double [...].
796 if (!getLangOptions().CPlusPlus &&
797 (FromBuiltin->getKind() == BuiltinType::Float ||
798 FromBuiltin->getKind() == BuiltinType::Double) &&
799 (ToBuiltin->getKind() == BuiltinType::LongDouble))
800 return true;
801 }
802
Douglas Gregord2baafd2008-10-21 16:13:35 +0000803 return false;
804}
805
Douglas Gregore819caf2009-02-12 00:15:05 +0000806/// \brief Determine if a conversion is a complex promotion.
807///
808/// A complex promotion is defined as a complex -> complex conversion
809/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000810/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000811bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
812 const ComplexType *FromComplex = FromType->getAsComplexType();
813 if (!FromComplex)
814 return false;
815
816 const ComplexType *ToComplex = ToType->getAsComplexType();
817 if (!ToComplex)
818 return false;
819
820 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000821 ToComplex->getElementType()) ||
822 IsIntegralPromotion(0, FromComplex->getElementType(),
823 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000824}
825
Douglas Gregor24a90a52008-11-26 23:31:11 +0000826/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
827/// the pointer type FromPtr to a pointer to type ToPointee, with the
828/// same type qualifiers as FromPtr has on its pointee type. ToType,
829/// if non-empty, will be a pointer to ToType that may or may not have
830/// the right set of qualifiers on its pointee.
831static QualType
832BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
833 QualType ToPointee, QualType ToType,
834 ASTContext &Context) {
835 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
836 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
837 unsigned Quals = CanonFromPointee.getCVRQualifiers();
838
839 // Exact qualifier match -> return the pointer type we're converting to.
840 if (CanonToPointee.getCVRQualifiers() == Quals) {
841 // ToType is exactly what we need. Return it.
842 if (ToType.getTypePtr())
843 return ToType;
844
845 // Build a pointer to ToPointee. It has the right qualifiers
846 // already.
847 return Context.getPointerType(ToPointee);
848 }
849
850 // Just build a canonical type that has the right qualifiers.
851 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
852}
853
Douglas Gregord2baafd2008-10-21 16:13:35 +0000854/// IsPointerConversion - Determines whether the conversion of the
855/// expression From, which has the (possibly adjusted) type FromType,
856/// can be converted to the type ToType via a pointer conversion (C++
857/// 4.10). If so, returns true and places the converted type (that
858/// might differ from ToType in its cv-qualifiers at some level) into
859/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000860///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000861/// This routine also supports conversions to and from block pointers
862/// and conversions with Objective-C's 'id', 'id<protocols...>', and
863/// pointers to interfaces. FIXME: Once we've determined the
864/// appropriate overloading rules for Objective-C, we may want to
865/// split the Objective-C checks into a different routine; however,
866/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000867/// conversions, so for now they live here. IncompatibleObjC will be
868/// set if the conversion is an allowed Objective-C conversion that
869/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000870bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000871 QualType& ConvertedType,
872 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000873{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000874 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000875 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
876 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000877
Douglas Gregorf1d75712008-12-22 20:51:52 +0000878 // Conversion from a null pointer constant to any Objective-C pointer type.
879 if (Context.isObjCObjectPointerType(ToType) &&
880 From->isNullPointerConstant(Context)) {
881 ConvertedType = ToType;
882 return true;
883 }
884
Douglas Gregor9036ef72008-11-27 00:15:41 +0000885 // Blocks: Block pointers can be converted to void*.
886 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
887 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
888 ConvertedType = ToType;
889 return true;
890 }
891 // Blocks: A null pointer constant can be converted to a block
892 // pointer type.
893 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
894 ConvertedType = ToType;
895 return true;
896 }
897
Douglas Gregord2baafd2008-10-21 16:13:35 +0000898 const PointerType* ToTypePtr = ToType->getAsPointerType();
899 if (!ToTypePtr)
900 return false;
901
902 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
903 if (From->isNullPointerConstant(Context)) {
904 ConvertedType = ToType;
905 return true;
906 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000907
Douglas Gregor24a90a52008-11-26 23:31:11 +0000908 // Beyond this point, both types need to be pointers.
909 const PointerType *FromTypePtr = FromType->getAsPointerType();
910 if (!FromTypePtr)
911 return false;
912
913 QualType FromPointeeType = FromTypePtr->getPointeeType();
914 QualType ToPointeeType = ToTypePtr->getPointeeType();
915
Douglas Gregord2baafd2008-10-21 16:13:35 +0000916 // An rvalue of type "pointer to cv T," where T is an object type,
917 // can be converted to an rvalue of type "pointer to cv void" (C++
918 // 4.10p2).
Douglas Gregor932778b2008-12-19 19:13:09 +0000919 if (FromPointeeType->isIncompleteOrObjectType() &&
920 ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000921 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
922 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000923 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000924 return true;
925 }
926
Douglas Gregorfcb19192009-02-11 23:02:49 +0000927 // When we're overloading in C, we allow a special kind of pointer
928 // conversion for compatible-but-not-identical pointee types.
929 if (!getLangOptions().CPlusPlus &&
930 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
931 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
932 ToPointeeType,
933 ToType, Context);
934 return true;
935 }
936
Douglas Gregor14046502008-10-23 00:40:37 +0000937 // C++ [conv.ptr]p3:
938 //
939 // An rvalue of type "pointer to cv D," where D is a class type,
940 // can be converted to an rvalue of type "pointer to cv B," where
941 // B is a base class (clause 10) of D. If B is an inaccessible
942 // (clause 11) or ambiguous (10.2) base class of D, a program that
943 // necessitates this conversion is ill-formed. The result of the
944 // conversion is a pointer to the base class sub-object of the
945 // derived class object. The null pointer value is converted to
946 // the null pointer value of the destination type.
947 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000948 // Note that we do not check for ambiguity or inaccessibility
949 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000950 if (getLangOptions().CPlusPlus &&
951 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000952 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
954 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000955 ToType, Context);
956 return true;
957 }
Douglas Gregor14046502008-10-23 00:40:37 +0000958
Douglas Gregor932778b2008-12-19 19:13:09 +0000959 return false;
960}
961
962/// isObjCPointerConversion - Determines whether this is an
963/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
964/// with the same arguments and return values.
965bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
966 QualType& ConvertedType,
967 bool &IncompatibleObjC) {
968 if (!getLangOptions().ObjC1)
969 return false;
970
971 // Conversions with Objective-C's id<...>.
972 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
973 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
974 ConvertedType = ToType;
975 return true;
976 }
977
Douglas Gregor80402cf2008-12-23 00:53:59 +0000978 // Beyond this point, both types need to be pointers or block pointers.
979 QualType ToPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000980 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000981 if (ToTypePtr)
982 ToPointeeType = ToTypePtr->getPointeeType();
983 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
984 ToPointeeType = ToBlockPtr->getPointeeType();
985 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000986 return false;
987
Douglas Gregor80402cf2008-12-23 00:53:59 +0000988 QualType FromPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000989 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000990 if (FromTypePtr)
991 FromPointeeType = FromTypePtr->getPointeeType();
992 else if (const BlockPointerType *FromBlockPtr
993 = FromType->getAsBlockPointerType())
994 FromPointeeType = FromBlockPtr->getPointeeType();
995 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000996 return false;
997
Douglas Gregor24a90a52008-11-26 23:31:11 +0000998 // Objective C++: We're able to convert from a pointer to an
999 // interface to a pointer to a different interface.
1000 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
1001 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1002 if (FromIface && ToIface &&
1003 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor80402cf2008-12-23 00:53:59 +00001004 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001005 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001006 ToType, Context);
1007 return true;
1008 }
1009
Douglas Gregor6fd35572008-12-19 17:40:08 +00001010 if (FromIface && ToIface &&
1011 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1012 // Okay: this is some kind of implicit downcast of Objective-C
1013 // interfaces, which is permitted. However, we're going to
1014 // complain about it.
1015 IncompatibleObjC = true;
Douglas Gregor80402cf2008-12-23 00:53:59 +00001016 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor6fd35572008-12-19 17:40:08 +00001017 ToPointeeType,
1018 ToType, Context);
1019 return true;
1020 }
1021
Douglas Gregor24a90a52008-11-26 23:31:11 +00001022 // Objective C++: We're able to convert between "id" and a pointer
1023 // to any interface (in both directions).
Steve Naroff17c03822009-02-12 17:52:19 +00001024 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1025 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001026 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1027 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001028 ToType, Context);
1029 return true;
1030 }
Douglas Gregor14046502008-10-23 00:40:37 +00001031
Douglas Gregord0c653a2008-12-18 23:43:31 +00001032 // Objective C++: Allow conversions between the Objective-C "id" and
1033 // "Class", in either direction.
Steve Naroff17c03822009-02-12 17:52:19 +00001034 if ((Context.isObjCIdStructType(FromPointeeType) &&
1035 Context.isObjCClassStructType(ToPointeeType)) ||
1036 (Context.isObjCClassStructType(FromPointeeType) &&
1037 Context.isObjCIdStructType(ToPointeeType))) {
Douglas Gregord0c653a2008-12-18 23:43:31 +00001038 ConvertedType = ToType;
1039 return true;
1040 }
1041
Douglas Gregor932778b2008-12-19 19:13:09 +00001042 // If we have pointers to pointers, recursively check whether this
1043 // is an Objective-C conversion.
1044 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1045 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1046 IncompatibleObjC)) {
1047 // We always complain about this conversion.
1048 IncompatibleObjC = true;
1049 ConvertedType = ToType;
1050 return true;
1051 }
1052
Douglas Gregor80402cf2008-12-23 00:53:59 +00001053 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001054 // differences in the argument and result types are in Objective-C
1055 // pointer conversions. If so, we permit the conversion (but
1056 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001057 const FunctionProtoType *FromFunctionType
1058 = FromPointeeType->getAsFunctionProtoType();
1059 const FunctionProtoType *ToFunctionType
1060 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001061 if (FromFunctionType && ToFunctionType) {
1062 // If the function types are exactly the same, this isn't an
1063 // Objective-C pointer conversion.
1064 if (Context.getCanonicalType(FromPointeeType)
1065 == Context.getCanonicalType(ToPointeeType))
1066 return false;
1067
1068 // Perform the quick checks that will tell us whether these
1069 // function types are obviously different.
1070 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1071 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1072 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1073 return false;
1074
1075 bool HasObjCConversion = false;
1076 if (Context.getCanonicalType(FromFunctionType->getResultType())
1077 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1078 // Okay, the types match exactly. Nothing to do.
1079 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1080 ToFunctionType->getResultType(),
1081 ConvertedType, IncompatibleObjC)) {
1082 // Okay, we have an Objective-C pointer conversion.
1083 HasObjCConversion = true;
1084 } else {
1085 // Function types are too different. Abort.
1086 return false;
1087 }
1088
1089 // Check argument types.
1090 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1091 ArgIdx != NumArgs; ++ArgIdx) {
1092 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1093 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1094 if (Context.getCanonicalType(FromArgType)
1095 == Context.getCanonicalType(ToArgType)) {
1096 // Okay, the types match exactly. Nothing to do.
1097 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1098 ConvertedType, IncompatibleObjC)) {
1099 // Okay, we have an Objective-C pointer conversion.
1100 HasObjCConversion = true;
1101 } else {
1102 // Argument types are too different. Abort.
1103 return false;
1104 }
1105 }
1106
1107 if (HasObjCConversion) {
1108 // We had an Objective-C conversion. Allow this pointer
1109 // conversion, but complain about it.
1110 ConvertedType = ToType;
1111 IncompatibleObjC = true;
1112 return true;
1113 }
1114 }
1115
Sebastian Redlba387562009-01-25 19:43:20 +00001116 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001117}
1118
Douglas Gregorbb461502008-10-24 04:54:22 +00001119/// CheckPointerConversion - Check the pointer conversion from the
1120/// expression From to the type ToType. This routine checks for
1121/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1122/// conversions for which IsPointerConversion has already returned
1123/// true. It returns true and produces a diagnostic if there was an
1124/// error, or returns false otherwise.
1125bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1126 QualType FromType = From->getType();
1127
1128 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1129 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001130 QualType FromPointeeType = FromPtrType->getPointeeType(),
1131 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001132
1133 // Objective-C++ conversions are always okay.
1134 // FIXME: We should have a different class of conversions for
1135 // the Objective-C++ implicit conversions.
Steve Naroff17c03822009-02-12 17:52:19 +00001136 if (Context.isObjCIdStructType(FromPointeeType) ||
1137 Context.isObjCIdStructType(ToPointeeType) ||
1138 Context.isObjCClassStructType(FromPointeeType) ||
1139 Context.isObjCClassStructType(ToPointeeType))
Douglas Gregord0c653a2008-12-18 23:43:31 +00001140 return false;
1141
Douglas Gregorbb461502008-10-24 04:54:22 +00001142 if (FromPointeeType->isRecordType() &&
1143 ToPointeeType->isRecordType()) {
1144 // We must have a derived-to-base conversion. Check an
1145 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001146 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1147 From->getExprLoc(),
1148 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001149 }
1150 }
1151
1152 return false;
1153}
1154
Sebastian Redlba387562009-01-25 19:43:20 +00001155/// IsMemberPointerConversion - Determines whether the conversion of the
1156/// expression From, which has the (possibly adjusted) type FromType, can be
1157/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1158/// If so, returns true and places the converted type (that might differ from
1159/// ToType in its cv-qualifiers at some level) into ConvertedType.
1160bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1161 QualType ToType, QualType &ConvertedType)
1162{
1163 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1164 if (!ToTypePtr)
1165 return false;
1166
1167 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1168 if (From->isNullPointerConstant(Context)) {
1169 ConvertedType = ToType;
1170 return true;
1171 }
1172
1173 // Otherwise, both types have to be member pointers.
1174 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1175 if (!FromTypePtr)
1176 return false;
1177
1178 // A pointer to member of B can be converted to a pointer to member of D,
1179 // where D is derived from B (C++ 4.11p2).
1180 QualType FromClass(FromTypePtr->getClass(), 0);
1181 QualType ToClass(ToTypePtr->getClass(), 0);
1182 // FIXME: What happens when these are dependent? Is this function even called?
1183
1184 if (IsDerivedFrom(ToClass, FromClass)) {
1185 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1186 ToClass.getTypePtr());
1187 return true;
1188 }
1189
1190 return false;
1191}
1192
1193/// CheckMemberPointerConversion - Check the member pointer conversion from the
1194/// expression From to the type ToType. This routine checks for ambiguous or
1195/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1196/// for which IsMemberPointerConversion has already returned true. It returns
1197/// true and produces a diagnostic if there was an error, or returns false
1198/// otherwise.
1199bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1200 QualType FromType = From->getType();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001201 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1202 if (!FromPtrType)
1203 return false;
Sebastian Redlba387562009-01-25 19:43:20 +00001204
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001205 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1206 assert(ToPtrType && "No member pointer cast has a target type "
1207 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001208
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001209 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1210 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001211
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001212 // FIXME: What about dependent types?
1213 assert(FromClass->isRecordType() && "Pointer into non-class.");
1214 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001215
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001216 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1217 /*DetectVirtual=*/true);
1218 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1219 assert(DerivationOkay &&
1220 "Should not have been called if derivation isn't OK.");
1221 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001222
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001223 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1224 getUnqualifiedType())) {
1225 // Derivation is ambiguous. Redo the check to find the exact paths.
1226 Paths.clear();
1227 Paths.setRecordingPaths(true);
1228 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1229 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1230 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001231
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001232 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1233 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1234 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1235 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001236 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001237
Douglas Gregor2e047592009-02-28 01:32:25 +00001238 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001239 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1240 << FromClass << ToClass << QualType(VBase, 0)
1241 << From->getSourceRange();
1242 return true;
1243 }
1244
Sebastian Redlba387562009-01-25 19:43:20 +00001245 return false;
1246}
1247
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001248/// IsQualificationConversion - Determines whether the conversion from
1249/// an rvalue of type FromType to ToType is a qualification conversion
1250/// (C++ 4.4).
1251bool
1252Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1253{
1254 FromType = Context.getCanonicalType(FromType);
1255 ToType = Context.getCanonicalType(ToType);
1256
1257 // If FromType and ToType are the same type, this is not a
1258 // qualification conversion.
1259 if (FromType == ToType)
1260 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001261
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001262 // (C++ 4.4p4):
1263 // A conversion can add cv-qualifiers at levels other than the first
1264 // in multi-level pointers, subject to the following rules: [...]
1265 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001266 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001267 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001268 // Within each iteration of the loop, we check the qualifiers to
1269 // determine if this still looks like a qualification
1270 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001271 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001272 // until there are no more pointers or pointers-to-members left to
1273 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001274 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001275
1276 // -- for every j > 0, if const is in cv 1,j then const is in cv
1277 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001278 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001279 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001280
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001281 // -- if the cv 1,j and cv 2,j are different, then const is in
1282 // every cv for 0 < k < j.
1283 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001284 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001285 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001286
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001287 // Keep track of whether all prior cv-qualifiers in the "to" type
1288 // include const.
1289 PreviousToQualsIncludeConst
1290 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001291 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001292
1293 // We are left with FromType and ToType being the pointee types
1294 // after unwrapping the original FromType and ToType the same number
1295 // of types. If we unwrapped any pointers, and if FromType and
1296 // ToType have the same unqualified type (since we checked
1297 // qualifiers above), then this is a qualification conversion.
1298 return UnwrappedAnyPointer &&
1299 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1300}
1301
Douglas Gregorb206cc42009-01-30 23:27:23 +00001302/// Determines whether there is a user-defined conversion sequence
1303/// (C++ [over.ics.user]) that converts expression From to the type
1304/// ToType. If such a conversion exists, User will contain the
1305/// user-defined conversion sequence that performs such a conversion
1306/// and this routine will return true. Otherwise, this routine returns
1307/// false and User is unspecified.
1308///
1309/// \param AllowConversionFunctions true if the conversion should
1310/// consider conversion functions at all. If false, only constructors
1311/// will be considered.
1312///
1313/// \param AllowExplicit true if the conversion should consider C++0x
1314/// "explicit" conversion functions as well as non-explicit conversion
1315/// functions (C++0x [class.conv.fct]p2).
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001316bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001317 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001318 bool AllowConversionFunctions,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001319 bool AllowExplicit)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001320{
1321 OverloadCandidateSet CandidateSet;
Douglas Gregor2e047592009-02-28 01:32:25 +00001322 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1323 if (CXXRecordDecl *ToRecordDecl
1324 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1325 // C++ [over.match.ctor]p1:
1326 // When objects of class type are direct-initialized (8.5), or
1327 // copy-initialized from an expression of the same or a
1328 // derived class type (8.5), overload resolution selects the
1329 // constructor. [...] For copy-initialization, the candidate
1330 // functions are all the converting constructors (12.3.1) of
1331 // that class. The argument list is the expression-list within
1332 // the parentheses of the initializer.
1333 DeclarationName ConstructorName
1334 = Context.DeclarationNames.getCXXConstructorName(
1335 Context.getCanonicalType(ToType).getUnqualifiedType());
1336 DeclContext::lookup_iterator Con, ConEnd;
1337 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName);
1338 Con != ConEnd; ++Con) {
1339 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1340 if (Constructor->isConvertingConstructor())
1341 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1342 /*SuppressUserConversions=*/true);
1343 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001344 }
1345 }
1346
Douglas Gregorb206cc42009-01-30 23:27:23 +00001347 if (!AllowConversionFunctions) {
1348 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-02-28 01:32:25 +00001349 } else if (const RecordType *FromRecordType
1350 = From->getType()->getAsRecordType()) {
1351 if (CXXRecordDecl *FromRecordDecl
1352 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1353 // Add all of the conversion functions as candidates.
1354 // FIXME: Look for conversions in base classes!
1355 OverloadedFunctionDecl *Conversions
1356 = FromRecordDecl->getConversionFunctions();
1357 for (OverloadedFunctionDecl::function_iterator Func
1358 = Conversions->function_begin();
1359 Func != Conversions->function_end(); ++Func) {
1360 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1361 if (AllowExplicit || !Conv->isExplicit())
1362 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1363 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001364 }
1365 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001366
1367 OverloadCandidateSet::iterator Best;
1368 switch (BestViableFunction(CandidateSet, Best)) {
1369 case OR_Success:
1370 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001371 if (CXXConstructorDecl *Constructor
1372 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1373 // C++ [over.ics.user]p1:
1374 // If the user-defined conversion is specified by a
1375 // constructor (12.3.1), the initial standard conversion
1376 // sequence converts the source type to the type required by
1377 // the argument of the constructor.
1378 //
1379 // FIXME: What about ellipsis conversions?
1380 QualType ThisType = Constructor->getThisType(Context);
1381 User.Before = Best->Conversions[0].Standard;
1382 User.ConversionFunction = Constructor;
1383 User.After.setAsIdentityConversion();
1384 User.After.FromTypePtr
1385 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1386 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1387 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001388 } else if (CXXConversionDecl *Conversion
1389 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1390 // C++ [over.ics.user]p1:
1391 //
1392 // [...] If the user-defined conversion is specified by a
1393 // conversion function (12.3.2), the initial standard
1394 // conversion sequence converts the source type to the
1395 // implicit object parameter of the conversion function.
1396 User.Before = Best->Conversions[0].Standard;
1397 User.ConversionFunction = Conversion;
1398
1399 // C++ [over.ics.user]p2:
1400 // The second standard conversion sequence converts the
1401 // result of the user-defined conversion to the target type
1402 // for the sequence. Since an implicit conversion sequence
1403 // is an initialization, the special rules for
1404 // initialization by user-defined conversion apply when
1405 // selecting the best user-defined conversion for a
1406 // user-defined conversion sequence (see 13.3.3 and
1407 // 13.3.3.1).
1408 User.After = Best->FinalConversion;
1409 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001410 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001411 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001412 return false;
1413 }
1414
1415 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001416 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001417 // No conversion here! We're done.
1418 return false;
1419
1420 case OR_Ambiguous:
1421 // FIXME: See C++ [over.best.ics]p10 for the handling of
1422 // ambiguous conversion sequences.
1423 return false;
1424 }
1425
1426 return false;
1427}
1428
Douglas Gregord2baafd2008-10-21 16:13:35 +00001429/// CompareImplicitConversionSequences - Compare two implicit
1430/// conversion sequences to determine whether one is better than the
1431/// other or if they are indistinguishable (C++ 13.3.3.2).
1432ImplicitConversionSequence::CompareKind
1433Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1434 const ImplicitConversionSequence& ICS2)
1435{
1436 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1437 // conversion sequences (as defined in 13.3.3.1)
1438 // -- a standard conversion sequence (13.3.3.1.1) is a better
1439 // conversion sequence than a user-defined conversion sequence or
1440 // an ellipsis conversion sequence, and
1441 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1442 // conversion sequence than an ellipsis conversion sequence
1443 // (13.3.3.1.3).
1444 //
1445 if (ICS1.ConversionKind < ICS2.ConversionKind)
1446 return ImplicitConversionSequence::Better;
1447 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1448 return ImplicitConversionSequence::Worse;
1449
1450 // Two implicit conversion sequences of the same form are
1451 // indistinguishable conversion sequences unless one of the
1452 // following rules apply: (C++ 13.3.3.2p3):
1453 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1454 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1455 else if (ICS1.ConversionKind ==
1456 ImplicitConversionSequence::UserDefinedConversion) {
1457 // User-defined conversion sequence U1 is a better conversion
1458 // sequence than another user-defined conversion sequence U2 if
1459 // they contain the same user-defined conversion function or
1460 // constructor and if the second standard conversion sequence of
1461 // U1 is better than the second standard conversion sequence of
1462 // U2 (C++ 13.3.3.2p3).
1463 if (ICS1.UserDefined.ConversionFunction ==
1464 ICS2.UserDefined.ConversionFunction)
1465 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1466 ICS2.UserDefined.After);
1467 }
1468
1469 return ImplicitConversionSequence::Indistinguishable;
1470}
1471
1472/// CompareStandardConversionSequences - Compare two standard
1473/// conversion sequences to determine whether one is better than the
1474/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1475ImplicitConversionSequence::CompareKind
1476Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1477 const StandardConversionSequence& SCS2)
1478{
1479 // Standard conversion sequence S1 is a better conversion sequence
1480 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1481
1482 // -- S1 is a proper subsequence of S2 (comparing the conversion
1483 // sequences in the canonical form defined by 13.3.3.1.1,
1484 // excluding any Lvalue Transformation; the identity conversion
1485 // sequence is considered to be a subsequence of any
1486 // non-identity conversion sequence) or, if not that,
1487 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1488 // Neither is a proper subsequence of the other. Do nothing.
1489 ;
1490 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1491 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1492 (SCS1.Second == ICK_Identity &&
1493 SCS1.Third == ICK_Identity))
1494 // SCS1 is a proper subsequence of SCS2.
1495 return ImplicitConversionSequence::Better;
1496 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1497 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1498 (SCS2.Second == ICK_Identity &&
1499 SCS2.Third == ICK_Identity))
1500 // SCS2 is a proper subsequence of SCS1.
1501 return ImplicitConversionSequence::Worse;
1502
1503 // -- the rank of S1 is better than the rank of S2 (by the rules
1504 // defined below), or, if not that,
1505 ImplicitConversionRank Rank1 = SCS1.getRank();
1506 ImplicitConversionRank Rank2 = SCS2.getRank();
1507 if (Rank1 < Rank2)
1508 return ImplicitConversionSequence::Better;
1509 else if (Rank2 < Rank1)
1510 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001511
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001512 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1513 // are indistinguishable unless one of the following rules
1514 // applies:
1515
1516 // A conversion that is not a conversion of a pointer, or
1517 // pointer to member, to bool is better than another conversion
1518 // that is such a conversion.
1519 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1520 return SCS2.isPointerConversionToBool()
1521 ? ImplicitConversionSequence::Better
1522 : ImplicitConversionSequence::Worse;
1523
Douglas Gregor14046502008-10-23 00:40:37 +00001524 // C++ [over.ics.rank]p4b2:
1525 //
1526 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001527 // conversion of B* to A* is better than conversion of B* to
1528 // void*, and conversion of A* to void* is better than conversion
1529 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001530 bool SCS1ConvertsToVoid
1531 = SCS1.isPointerConversionToVoidPointer(Context);
1532 bool SCS2ConvertsToVoid
1533 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001534 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1535 // Exactly one of the conversion sequences is a conversion to
1536 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001537 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1538 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001539 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1540 // Neither conversion sequence converts to a void pointer; compare
1541 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001542 if (ImplicitConversionSequence::CompareKind DerivedCK
1543 = CompareDerivedToBaseConversions(SCS1, SCS2))
1544 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001545 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1546 // Both conversion sequences are conversions to void
1547 // pointers. Compare the source types to determine if there's an
1548 // inheritance relationship in their sources.
1549 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1550 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1551
1552 // Adjust the types we're converting from via the array-to-pointer
1553 // conversion, if we need to.
1554 if (SCS1.First == ICK_Array_To_Pointer)
1555 FromType1 = Context.getArrayDecayedType(FromType1);
1556 if (SCS2.First == ICK_Array_To_Pointer)
1557 FromType2 = Context.getArrayDecayedType(FromType2);
1558
1559 QualType FromPointee1
1560 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1561 QualType FromPointee2
1562 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1563
1564 if (IsDerivedFrom(FromPointee2, FromPointee1))
1565 return ImplicitConversionSequence::Better;
1566 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1567 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001568
1569 // Objective-C++: If one interface is more specific than the
1570 // other, it is the better one.
1571 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1572 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1573 if (FromIface1 && FromIface1) {
1574 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1575 return ImplicitConversionSequence::Better;
1576 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1577 return ImplicitConversionSequence::Worse;
1578 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001579 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001580
1581 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1582 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001583 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001584 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001585 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001586
Douglas Gregor0e343382008-10-29 14:50:44 +00001587 // C++ [over.ics.rank]p3b4:
1588 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1589 // which the references refer are the same type except for
1590 // top-level cv-qualifiers, and the type to which the reference
1591 // initialized by S2 refers is more cv-qualified than the type
1592 // to which the reference initialized by S1 refers.
1593 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1594 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1595 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1596 T1 = Context.getCanonicalType(T1);
1597 T2 = Context.getCanonicalType(T2);
1598 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1599 if (T2.isMoreQualifiedThan(T1))
1600 return ImplicitConversionSequence::Better;
1601 else if (T1.isMoreQualifiedThan(T2))
1602 return ImplicitConversionSequence::Worse;
1603 }
1604 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001605
1606 return ImplicitConversionSequence::Indistinguishable;
1607}
1608
1609/// CompareQualificationConversions - Compares two standard conversion
1610/// sequences to determine whether they can be ranked based on their
1611/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1612ImplicitConversionSequence::CompareKind
1613Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1614 const StandardConversionSequence& SCS2)
1615{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001616 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001617 // -- S1 and S2 differ only in their qualification conversion and
1618 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1619 // cv-qualification signature of type T1 is a proper subset of
1620 // the cv-qualification signature of type T2, and S1 is not the
1621 // deprecated string literal array-to-pointer conversion (4.2).
1622 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1623 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1624 return ImplicitConversionSequence::Indistinguishable;
1625
1626 // FIXME: the example in the standard doesn't use a qualification
1627 // conversion (!)
1628 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1629 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1630 T1 = Context.getCanonicalType(T1);
1631 T2 = Context.getCanonicalType(T2);
1632
1633 // If the types are the same, we won't learn anything by unwrapped
1634 // them.
1635 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1636 return ImplicitConversionSequence::Indistinguishable;
1637
1638 ImplicitConversionSequence::CompareKind Result
1639 = ImplicitConversionSequence::Indistinguishable;
1640 while (UnwrapSimilarPointerTypes(T1, T2)) {
1641 // Within each iteration of the loop, we check the qualifiers to
1642 // determine if this still looks like a qualification
1643 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001644 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001645 // until there are no more pointers or pointers-to-members left
1646 // to unwrap. This essentially mimics what
1647 // IsQualificationConversion does, but here we're checking for a
1648 // strict subset of qualifiers.
1649 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1650 // The qualifiers are the same, so this doesn't tell us anything
1651 // about how the sequences rank.
1652 ;
1653 else if (T2.isMoreQualifiedThan(T1)) {
1654 // T1 has fewer qualifiers, so it could be the better sequence.
1655 if (Result == ImplicitConversionSequence::Worse)
1656 // Neither has qualifiers that are a subset of the other's
1657 // qualifiers.
1658 return ImplicitConversionSequence::Indistinguishable;
1659
1660 Result = ImplicitConversionSequence::Better;
1661 } else if (T1.isMoreQualifiedThan(T2)) {
1662 // T2 has fewer qualifiers, so it could be the better sequence.
1663 if (Result == ImplicitConversionSequence::Better)
1664 // Neither has qualifiers that are a subset of the other's
1665 // qualifiers.
1666 return ImplicitConversionSequence::Indistinguishable;
1667
1668 Result = ImplicitConversionSequence::Worse;
1669 } else {
1670 // Qualifiers are disjoint.
1671 return ImplicitConversionSequence::Indistinguishable;
1672 }
1673
1674 // If the types after this point are equivalent, we're done.
1675 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1676 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001677 }
1678
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001679 // Check that the winning standard conversion sequence isn't using
1680 // the deprecated string literal array to pointer conversion.
1681 switch (Result) {
1682 case ImplicitConversionSequence::Better:
1683 if (SCS1.Deprecated)
1684 Result = ImplicitConversionSequence::Indistinguishable;
1685 break;
1686
1687 case ImplicitConversionSequence::Indistinguishable:
1688 break;
1689
1690 case ImplicitConversionSequence::Worse:
1691 if (SCS2.Deprecated)
1692 Result = ImplicitConversionSequence::Indistinguishable;
1693 break;
1694 }
1695
1696 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001697}
1698
Douglas Gregor14046502008-10-23 00:40:37 +00001699/// CompareDerivedToBaseConversions - Compares two standard conversion
1700/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001701/// various kinds of derived-to-base conversions (C++
1702/// [over.ics.rank]p4b3). As part of these checks, we also look at
1703/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001704ImplicitConversionSequence::CompareKind
1705Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1706 const StandardConversionSequence& SCS2) {
1707 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1708 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1709 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1710 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1711
1712 // Adjust the types we're converting from via the array-to-pointer
1713 // conversion, if we need to.
1714 if (SCS1.First == ICK_Array_To_Pointer)
1715 FromType1 = Context.getArrayDecayedType(FromType1);
1716 if (SCS2.First == ICK_Array_To_Pointer)
1717 FromType2 = Context.getArrayDecayedType(FromType2);
1718
1719 // Canonicalize all of the types.
1720 FromType1 = Context.getCanonicalType(FromType1);
1721 ToType1 = Context.getCanonicalType(ToType1);
1722 FromType2 = Context.getCanonicalType(FromType2);
1723 ToType2 = Context.getCanonicalType(ToType2);
1724
Douglas Gregor0e343382008-10-29 14:50:44 +00001725 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001726 //
1727 // If class B is derived directly or indirectly from class A and
1728 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001729 //
1730 // For Objective-C, we let A, B, and C also be Objective-C
1731 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001732
1733 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001734 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001735 SCS2.Second == ICK_Pointer_Conversion &&
1736 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1737 FromType1->isPointerType() && FromType2->isPointerType() &&
1738 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001739 QualType FromPointee1
1740 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1741 QualType ToPointee1
1742 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1743 QualType FromPointee2
1744 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1745 QualType ToPointee2
1746 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001747
1748 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1749 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1750 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1751 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1752
Douglas Gregor0e343382008-10-29 14:50:44 +00001753 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001754 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1755 if (IsDerivedFrom(ToPointee1, ToPointee2))
1756 return ImplicitConversionSequence::Better;
1757 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1758 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001759
1760 if (ToIface1 && ToIface2) {
1761 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1762 return ImplicitConversionSequence::Better;
1763 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1764 return ImplicitConversionSequence::Worse;
1765 }
Douglas Gregor14046502008-10-23 00:40:37 +00001766 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001767
1768 // -- conversion of B* to A* is better than conversion of C* to A*,
1769 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1770 if (IsDerivedFrom(FromPointee2, FromPointee1))
1771 return ImplicitConversionSequence::Better;
1772 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1773 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001774
1775 if (FromIface1 && FromIface2) {
1776 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1777 return ImplicitConversionSequence::Better;
1778 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1779 return ImplicitConversionSequence::Worse;
1780 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001781 }
Douglas Gregor14046502008-10-23 00:40:37 +00001782 }
1783
Douglas Gregor0e343382008-10-29 14:50:44 +00001784 // Compare based on reference bindings.
1785 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1786 SCS1.Second == ICK_Derived_To_Base) {
1787 // -- binding of an expression of type C to a reference of type
1788 // B& is better than binding an expression of type C to a
1789 // reference of type A&,
1790 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1791 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1792 if (IsDerivedFrom(ToType1, ToType2))
1793 return ImplicitConversionSequence::Better;
1794 else if (IsDerivedFrom(ToType2, ToType1))
1795 return ImplicitConversionSequence::Worse;
1796 }
1797
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001798 // -- binding of an expression of type B to a reference of type
1799 // A& is better than binding an expression of type C to a
1800 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001801 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1802 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1803 if (IsDerivedFrom(FromType2, FromType1))
1804 return ImplicitConversionSequence::Better;
1805 else if (IsDerivedFrom(FromType1, FromType2))
1806 return ImplicitConversionSequence::Worse;
1807 }
1808 }
1809
1810
1811 // FIXME: conversion of A::* to B::* is better than conversion of
1812 // A::* to C::*,
1813
1814 // FIXME: conversion of B::* to C::* is better than conversion of
1815 // A::* to C::*, and
1816
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001817 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1818 SCS1.Second == ICK_Derived_To_Base) {
1819 // -- conversion of C to B is better than conversion of C to A,
1820 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1821 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1822 if (IsDerivedFrom(ToType1, ToType2))
1823 return ImplicitConversionSequence::Better;
1824 else if (IsDerivedFrom(ToType2, ToType1))
1825 return ImplicitConversionSequence::Worse;
1826 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001827
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001828 // -- conversion of B to A is better than conversion of C to A.
1829 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1830 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1831 if (IsDerivedFrom(FromType2, FromType1))
1832 return ImplicitConversionSequence::Better;
1833 else if (IsDerivedFrom(FromType1, FromType2))
1834 return ImplicitConversionSequence::Worse;
1835 }
1836 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001837
Douglas Gregor14046502008-10-23 00:40:37 +00001838 return ImplicitConversionSequence::Indistinguishable;
1839}
1840
Douglas Gregor81c29152008-10-29 00:13:59 +00001841/// TryCopyInitialization - Try to copy-initialize a value of type
1842/// ToType from the expression From. Return the implicit conversion
1843/// sequence required to pass this argument, which may be a bad
1844/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001845/// a parameter of this type). If @p SuppressUserConversions, then we
1846/// do not permit any user-defined conversion sequences.
Douglas Gregor81c29152008-10-29 00:13:59 +00001847ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001848Sema::TryCopyInitialization(Expr *From, QualType ToType,
1849 bool SuppressUserConversions) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001850 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001851 ImplicitConversionSequence ICS;
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001852 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001853 return ICS;
1854 } else {
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001855 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001856 }
1857}
1858
1859/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1860/// type ToType. Returns true (and emits a diagnostic) if there was
1861/// an error, returns false if the initialization succeeded.
1862bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1863 const char* Flavor) {
1864 if (!getLangOptions().CPlusPlus) {
1865 // In C, argument passing is the same as performing an assignment.
1866 QualType FromType = From->getType();
1867 AssignConvertType ConvTy =
1868 CheckSingleAssignmentConstraints(ToType, From);
1869
1870 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1871 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001872 }
Chris Lattner271d4c22008-11-24 05:29:24 +00001873
1874 if (ToType->isReferenceType())
1875 return CheckReferenceInit(From, ToType);
1876
Douglas Gregor6fd35572008-12-19 17:40:08 +00001877 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattner271d4c22008-11-24 05:29:24 +00001878 return false;
1879
1880 return Diag(From->getSourceRange().getBegin(),
1881 diag::err_typecheck_convert_incompatible)
1882 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001883}
1884
Douglas Gregor5ed15042008-11-18 23:14:02 +00001885/// TryObjectArgumentInitialization - Try to initialize the object
1886/// parameter of the given member function (@c Method) from the
1887/// expression @p From.
1888ImplicitConversionSequence
1889Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1890 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1891 unsigned MethodQuals = Method->getTypeQualifiers();
1892 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1893
1894 // Set up the conversion sequence as a "bad" conversion, to allow us
1895 // to exit early.
1896 ImplicitConversionSequence ICS;
1897 ICS.Standard.setAsIdentityConversion();
1898 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1899
1900 // We need to have an object of class type.
1901 QualType FromType = From->getType();
1902 if (!FromType->isRecordType())
1903 return ICS;
1904
1905 // The implicit object parmeter is has the type "reference to cv X",
1906 // where X is the class of which the function is a member
1907 // (C++ [over.match.funcs]p4). However, when finding an implicit
1908 // conversion sequence for the argument, we are not allowed to
1909 // create temporaries or perform user-defined conversions
1910 // (C++ [over.match.funcs]p5). We perform a simplified version of
1911 // reference binding here, that allows class rvalues to bind to
1912 // non-constant references.
1913
1914 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1915 // with the implicit object parameter (C++ [over.match.funcs]p5).
1916 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1917 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1918 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1919 return ICS;
1920
1921 // Check that we have either the same type or a derived type. It
1922 // affects the conversion rank.
1923 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1924 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1925 ICS.Standard.Second = ICK_Identity;
1926 else if (IsDerivedFrom(FromType, ClassType))
1927 ICS.Standard.Second = ICK_Derived_To_Base;
1928 else
1929 return ICS;
1930
1931 // Success. Mark this as a reference binding.
1932 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1933 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1934 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1935 ICS.Standard.ReferenceBinding = true;
1936 ICS.Standard.DirectBinding = true;
1937 return ICS;
1938}
1939
1940/// PerformObjectArgumentInitialization - Perform initialization of
1941/// the implicit object parameter for the given Method with the given
1942/// expression.
1943bool
1944Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1945 QualType ImplicitParamType
1946 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1947 ImplicitConversionSequence ICS
1948 = TryObjectArgumentInitialization(From, Method);
1949 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1950 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001951 diag::err_implicit_object_parameter_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001952 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor5ed15042008-11-18 23:14:02 +00001953
1954 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1955 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1956 From->getSourceRange().getBegin(),
1957 From->getSourceRange()))
1958 return true;
1959
1960 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1961 return false;
1962}
1963
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001964/// TryContextuallyConvertToBool - Attempt to contextually convert the
1965/// expression From to bool (C++0x [conv]p3).
1966ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1967 return TryImplicitConversion(From, Context.BoolTy, false, true);
1968}
1969
1970/// PerformContextuallyConvertToBool - Perform a contextual conversion
1971/// of the expression From to bool (C++0x [conv]p3).
1972bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1973 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1974 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1975 return false;
1976
1977 return Diag(From->getSourceRange().getBegin(),
1978 diag::err_typecheck_bool_condition)
1979 << From->getType() << From->getSourceRange();
1980}
1981
Douglas Gregord2baafd2008-10-21 16:13:35 +00001982/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001983/// candidate functions, using the given function call arguments. If
1984/// @p SuppressUserConversions, then don't allow user-defined
1985/// conversions via constructors or conversion operators.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001986void
1987Sema::AddOverloadCandidate(FunctionDecl *Function,
1988 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001989 OverloadCandidateSet& CandidateSet,
1990 bool SuppressUserConversions)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001991{
Douglas Gregor4fa58902009-02-26 23:50:07 +00001992 const FunctionProtoType* Proto
1993 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001994 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00001995 assert(!isa<CXXConversionDecl>(Function) &&
1996 "Use AddConversionCandidate for conversion functions");
Douglas Gregord2baafd2008-10-21 16:13:35 +00001997
Douglas Gregor3257fb52008-12-22 05:46:06 +00001998 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
1999 // If we get here, it's because we're calling a member function
2000 // that is named without a member access expression (e.g.,
2001 // "this->f") that was either written explicitly or created
2002 // implicitly. This can happen with a qualified call to a member
2003 // function, e.g., X::f(). We use a NULL object as the implied
2004 // object argument (C++ [over.call.func]p3).
2005 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2006 SuppressUserConversions);
2007 return;
2008 }
2009
2010
Douglas Gregord2baafd2008-10-21 16:13:35 +00002011 // Add this candidate
2012 CandidateSet.push_back(OverloadCandidate());
2013 OverloadCandidate& Candidate = CandidateSet.back();
2014 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002015 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002016 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002017 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002018
2019 unsigned NumArgsInProto = Proto->getNumArgs();
2020
2021 // (C++ 13.3.2p2): A candidate function having fewer than m
2022 // parameters is viable only if it has an ellipsis in its parameter
2023 // list (8.3.5).
2024 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2025 Candidate.Viable = false;
2026 return;
2027 }
2028
2029 // (C++ 13.3.2p2): A candidate function having more than m parameters
2030 // is viable only if the (m+1)st parameter has a default argument
2031 // (8.3.6). For the purposes of overload resolution, the
2032 // parameter list is truncated on the right, so that there are
2033 // exactly m parameters.
2034 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2035 if (NumArgs < MinRequiredArgs) {
2036 // Not enough arguments.
2037 Candidate.Viable = false;
2038 return;
2039 }
2040
2041 // Determine the implicit conversion sequences for each of the
2042 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002043 Candidate.Conversions.resize(NumArgs);
2044 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2045 if (ArgIdx < NumArgsInProto) {
2046 // (C++ 13.3.2p3): for F to be a viable function, there shall
2047 // exist for each argument an implicit conversion sequence
2048 // (13.3.3.1) that converts that argument to the corresponding
2049 // parameter of F.
2050 QualType ParamType = Proto->getArgType(ArgIdx);
2051 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002052 = TryCopyInitialization(Args[ArgIdx], ParamType,
2053 SuppressUserConversions);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002054 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002055 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002056 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002057 break;
2058 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002059 } else {
2060 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2061 // argument for which there is no corresponding parameter is
2062 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2063 Candidate.Conversions[ArgIdx].ConversionKind
2064 = ImplicitConversionSequence::EllipsisConversion;
2065 }
2066 }
2067}
2068
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002069/// \brief Add all of the function declarations in the given function set to
2070/// the overload canddiate set.
2071void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2072 Expr **Args, unsigned NumArgs,
2073 OverloadCandidateSet& CandidateSet,
2074 bool SuppressUserConversions) {
2075 for (FunctionSet::const_iterator F = Functions.begin(),
2076 FEnd = Functions.end();
2077 F != FEnd; ++F)
2078 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2079 SuppressUserConversions);
2080}
2081
Douglas Gregor5ed15042008-11-18 23:14:02 +00002082/// AddMethodCandidate - Adds the given C++ member function to the set
2083/// of candidate functions, using the given function call arguments
2084/// and the object argument (@c Object). For example, in a call
2085/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2086/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2087/// allow user-defined conversions via constructors or conversion
2088/// operators.
2089void
2090Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2091 Expr **Args, unsigned NumArgs,
2092 OverloadCandidateSet& CandidateSet,
2093 bool SuppressUserConversions)
2094{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002095 const FunctionProtoType* Proto
2096 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002097 assert(Proto && "Methods without a prototype cannot be overloaded");
2098 assert(!isa<CXXConversionDecl>(Method) &&
2099 "Use AddConversionCandidate for conversion functions");
2100
2101 // Add this candidate
2102 CandidateSet.push_back(OverloadCandidate());
2103 OverloadCandidate& Candidate = CandidateSet.back();
2104 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002105 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002106 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002107
2108 unsigned NumArgsInProto = Proto->getNumArgs();
2109
2110 // (C++ 13.3.2p2): A candidate function having fewer than m
2111 // parameters is viable only if it has an ellipsis in its parameter
2112 // list (8.3.5).
2113 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2114 Candidate.Viable = false;
2115 return;
2116 }
2117
2118 // (C++ 13.3.2p2): A candidate function having more than m parameters
2119 // is viable only if the (m+1)st parameter has a default argument
2120 // (8.3.6). For the purposes of overload resolution, the
2121 // parameter list is truncated on the right, so that there are
2122 // exactly m parameters.
2123 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2124 if (NumArgs < MinRequiredArgs) {
2125 // Not enough arguments.
2126 Candidate.Viable = false;
2127 return;
2128 }
2129
2130 Candidate.Viable = true;
2131 Candidate.Conversions.resize(NumArgs + 1);
2132
Douglas Gregor3257fb52008-12-22 05:46:06 +00002133 if (Method->isStatic() || !Object)
2134 // The implicit object argument is ignored.
2135 Candidate.IgnoreObjectArgument = true;
2136 else {
2137 // Determine the implicit conversion sequence for the object
2138 // parameter.
2139 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2140 if (Candidate.Conversions[0].ConversionKind
2141 == ImplicitConversionSequence::BadConversion) {
2142 Candidate.Viable = false;
2143 return;
2144 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002145 }
2146
2147 // Determine the implicit conversion sequences for each of the
2148 // arguments.
2149 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2150 if (ArgIdx < NumArgsInProto) {
2151 // (C++ 13.3.2p3): for F to be a viable function, there shall
2152 // exist for each argument an implicit conversion sequence
2153 // (13.3.3.1) that converts that argument to the corresponding
2154 // parameter of F.
2155 QualType ParamType = Proto->getArgType(ArgIdx);
2156 Candidate.Conversions[ArgIdx + 1]
2157 = TryCopyInitialization(Args[ArgIdx], ParamType,
2158 SuppressUserConversions);
2159 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2160 == ImplicitConversionSequence::BadConversion) {
2161 Candidate.Viable = false;
2162 break;
2163 }
2164 } else {
2165 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2166 // argument for which there is no corresponding parameter is
2167 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2168 Candidate.Conversions[ArgIdx + 1].ConversionKind
2169 = ImplicitConversionSequence::EllipsisConversion;
2170 }
2171 }
2172}
2173
Douglas Gregor60714f92008-11-07 22:36:19 +00002174/// AddConversionCandidate - Add a C++ conversion function as a
2175/// candidate in the candidate set (C++ [over.match.conv],
2176/// C++ [over.match.copy]). From is the expression we're converting from,
2177/// and ToType is the type that we're eventually trying to convert to
2178/// (which may or may not be the same type as the type that the
2179/// conversion function produces).
2180void
2181Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2182 Expr *From, QualType ToType,
2183 OverloadCandidateSet& CandidateSet) {
2184 // Add this candidate
2185 CandidateSet.push_back(OverloadCandidate());
2186 OverloadCandidate& Candidate = CandidateSet.back();
2187 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002188 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002189 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002190 Candidate.FinalConversion.setAsIdentityConversion();
2191 Candidate.FinalConversion.FromTypePtr
2192 = Conversion->getConversionType().getAsOpaquePtr();
2193 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2194
Douglas Gregor5ed15042008-11-18 23:14:02 +00002195 // Determine the implicit conversion sequence for the implicit
2196 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002197 Candidate.Viable = true;
2198 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002199 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002200
Douglas Gregor60714f92008-11-07 22:36:19 +00002201 if (Candidate.Conversions[0].ConversionKind
2202 == ImplicitConversionSequence::BadConversion) {
2203 Candidate.Viable = false;
2204 return;
2205 }
2206
2207 // To determine what the conversion from the result of calling the
2208 // conversion function to the type we're eventually trying to
2209 // convert to (ToType), we need to synthesize a call to the
2210 // conversion function and attempt copy initialization from it. This
2211 // makes sure that we get the right semantics with respect to
2212 // lvalues/rvalues and the type. Fortunately, we can allocate this
2213 // call on the stack and we don't need its arguments to be
2214 // well-formed.
2215 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2216 SourceLocation());
2217 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregor70d26122008-11-12 17:17:38 +00002218 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002219
2220 // Note that it is safe to allocate CallExpr on the stack here because
2221 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2222 // allocator).
2223 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002224 Conversion->getConversionType().getNonReferenceType(),
2225 SourceLocation());
2226 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2227 switch (ICS.ConversionKind) {
2228 case ImplicitConversionSequence::StandardConversion:
2229 Candidate.FinalConversion = ICS.Standard;
2230 break;
2231
2232 case ImplicitConversionSequence::BadConversion:
2233 Candidate.Viable = false;
2234 break;
2235
2236 default:
2237 assert(false &&
2238 "Can only end up with a standard conversion sequence or failure");
2239 }
2240}
2241
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002242/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2243/// converts the given @c Object to a function pointer via the
2244/// conversion function @c Conversion, and then attempts to call it
2245/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2246/// the type of function that we'll eventually be calling.
2247void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002248 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002249 Expr *Object, Expr **Args, unsigned NumArgs,
2250 OverloadCandidateSet& CandidateSet) {
2251 CandidateSet.push_back(OverloadCandidate());
2252 OverloadCandidate& Candidate = CandidateSet.back();
2253 Candidate.Function = 0;
2254 Candidate.Surrogate = Conversion;
2255 Candidate.Viable = true;
2256 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002257 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002258 Candidate.Conversions.resize(NumArgs + 1);
2259
2260 // Determine the implicit conversion sequence for the implicit
2261 // object parameter.
2262 ImplicitConversionSequence ObjectInit
2263 = TryObjectArgumentInitialization(Object, Conversion);
2264 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2265 Candidate.Viable = false;
2266 return;
2267 }
2268
2269 // The first conversion is actually a user-defined conversion whose
2270 // first conversion is ObjectInit's standard conversion (which is
2271 // effectively a reference binding). Record it as such.
2272 Candidate.Conversions[0].ConversionKind
2273 = ImplicitConversionSequence::UserDefinedConversion;
2274 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2275 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2276 Candidate.Conversions[0].UserDefined.After
2277 = Candidate.Conversions[0].UserDefined.Before;
2278 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2279
2280 // Find the
2281 unsigned NumArgsInProto = Proto->getNumArgs();
2282
2283 // (C++ 13.3.2p2): A candidate function having fewer than m
2284 // parameters is viable only if it has an ellipsis in its parameter
2285 // list (8.3.5).
2286 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2287 Candidate.Viable = false;
2288 return;
2289 }
2290
2291 // Function types don't have any default arguments, so just check if
2292 // we have enough arguments.
2293 if (NumArgs < NumArgsInProto) {
2294 // Not enough arguments.
2295 Candidate.Viable = false;
2296 return;
2297 }
2298
2299 // Determine the implicit conversion sequences for each of the
2300 // arguments.
2301 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2302 if (ArgIdx < NumArgsInProto) {
2303 // (C++ 13.3.2p3): for F to be a viable function, there shall
2304 // exist for each argument an implicit conversion sequence
2305 // (13.3.3.1) that converts that argument to the corresponding
2306 // parameter of F.
2307 QualType ParamType = Proto->getArgType(ArgIdx);
2308 Candidate.Conversions[ArgIdx + 1]
2309 = TryCopyInitialization(Args[ArgIdx], ParamType,
2310 /*SuppressUserConversions=*/false);
2311 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2312 == ImplicitConversionSequence::BadConversion) {
2313 Candidate.Viable = false;
2314 break;
2315 }
2316 } else {
2317 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2318 // argument for which there is no corresponding parameter is
2319 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2320 Candidate.Conversions[ArgIdx + 1].ConversionKind
2321 = ImplicitConversionSequence::EllipsisConversion;
2322 }
2323 }
2324}
2325
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002326// FIXME: This will eventually be removed, once we've migrated all of
2327// the operator overloading logic over to the scheme used by binary
2328// operators, which works for template instantiation.
2329void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002330 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002331 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002332 OverloadCandidateSet& CandidateSet,
2333 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002334
2335 FunctionSet Functions;
2336
2337 QualType T1 = Args[0]->getType();
2338 QualType T2;
2339 if (NumArgs > 1)
2340 T2 = Args[1]->getType();
2341
2342 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2343 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2344 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2345 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2346 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2347 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2348}
2349
2350/// \brief Add overload candidates for overloaded operators that are
2351/// member functions.
2352///
2353/// Add the overloaded operator candidates that are member functions
2354/// for the operator Op that was used in an operator expression such
2355/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2356/// CandidateSet will store the added overload candidates. (C++
2357/// [over.match.oper]).
2358void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2359 SourceLocation OpLoc,
2360 Expr **Args, unsigned NumArgs,
2361 OverloadCandidateSet& CandidateSet,
2362 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002363 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2364
2365 // C++ [over.match.oper]p3:
2366 // For a unary operator @ with an operand of a type whose
2367 // cv-unqualified version is T1, and for a binary operator @ with
2368 // a left operand of a type whose cv-unqualified version is T1 and
2369 // a right operand of a type whose cv-unqualified version is T2,
2370 // three sets of candidate functions, designated member
2371 // candidates, non-member candidates and built-in candidates, are
2372 // constructed as follows:
2373 QualType T1 = Args[0]->getType();
2374 QualType T2;
2375 if (NumArgs > 1)
2376 T2 = Args[1]->getType();
2377
2378 // -- If T1 is a class type, the set of member candidates is the
2379 // result of the qualified lookup of T1::operator@
2380 // (13.3.1.1.1); otherwise, the set of member candidates is
2381 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002382 // FIXME: Lookup in base classes, too!
Douglas Gregor5ed15042008-11-18 23:14:02 +00002383 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002384 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00002385 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002386 Oper != OperEnd; ++Oper)
2387 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2388 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002389 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002390 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002391}
2392
Douglas Gregor70d26122008-11-12 17:17:38 +00002393/// AddBuiltinCandidate - Add a candidate for a built-in
2394/// operator. ResultTy and ParamTys are the result and parameter types
2395/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002396/// arguments being passed to the candidate. IsAssignmentOperator
2397/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002398/// operator. NumContextualBoolArguments is the number of arguments
2399/// (at the beginning of the argument list) that will be contextually
2400/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002401void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2402 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002403 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002404 bool IsAssignmentOperator,
2405 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002406 // Add this candidate
2407 CandidateSet.push_back(OverloadCandidate());
2408 OverloadCandidate& Candidate = CandidateSet.back();
2409 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002410 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002411 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002412 Candidate.BuiltinTypes.ResultTy = ResultTy;
2413 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2414 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2415
2416 // Determine the implicit conversion sequences for each of the
2417 // arguments.
2418 Candidate.Viable = true;
2419 Candidate.Conversions.resize(NumArgs);
2420 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002421 // C++ [over.match.oper]p4:
2422 // For the built-in assignment operators, conversions of the
2423 // left operand are restricted as follows:
2424 // -- no temporaries are introduced to hold the left operand, and
2425 // -- no user-defined conversions are applied to the left
2426 // operand to achieve a type match with the left-most
2427 // parameter of a built-in candidate.
2428 //
2429 // We block these conversions by turning off user-defined
2430 // conversions, since that is the only way that initialization of
2431 // a reference to a non-class type can occur from something that
2432 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002433 if (ArgIdx < NumContextualBoolArguments) {
2434 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2435 "Contextual conversion to bool requires bool type");
2436 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2437 } else {
2438 Candidate.Conversions[ArgIdx]
2439 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2440 ArgIdx == 0 && IsAssignmentOperator);
2441 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002442 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002443 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002444 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002445 break;
2446 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002447 }
2448}
2449
2450/// BuiltinCandidateTypeSet - A set of types that will be used for the
2451/// candidate operator functions for built-in operators (C++
2452/// [over.built]). The types are separated into pointer types and
2453/// enumeration types.
2454class BuiltinCandidateTypeSet {
2455 /// TypeSet - A set of types.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002456 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002457
2458 /// PointerTypes - The set of pointer types that will be used in the
2459 /// built-in candidates.
2460 TypeSet PointerTypes;
2461
2462 /// EnumerationTypes - The set of enumeration types that will be
2463 /// used in the built-in candidates.
2464 TypeSet EnumerationTypes;
2465
2466 /// Context - The AST context in which we will build the type sets.
2467 ASTContext &Context;
2468
2469 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2470
2471public:
2472 /// iterator - Iterates through the types that are part of the set.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002473 class iterator {
2474 TypeSet::iterator Base;
2475
2476 public:
2477 typedef QualType value_type;
2478 typedef QualType reference;
2479 typedef QualType pointer;
2480 typedef std::ptrdiff_t difference_type;
2481 typedef std::input_iterator_tag iterator_category;
2482
2483 iterator(TypeSet::iterator B) : Base(B) { }
2484
2485 iterator& operator++() {
2486 ++Base;
2487 return *this;
2488 }
2489
2490 iterator operator++(int) {
2491 iterator tmp(*this);
2492 ++(*this);
2493 return tmp;
2494 }
2495
2496 reference operator*() const {
2497 return QualType::getFromOpaquePtr(*Base);
2498 }
2499
2500 pointer operator->() const {
2501 return **this;
2502 }
2503
2504 friend bool operator==(iterator LHS, iterator RHS) {
2505 return LHS.Base == RHS.Base;
2506 }
2507
2508 friend bool operator!=(iterator LHS, iterator RHS) {
2509 return LHS.Base != RHS.Base;
2510 }
2511 };
Douglas Gregor70d26122008-11-12 17:17:38 +00002512
2513 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2514
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002515 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2516 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002517
2518 /// pointer_begin - First pointer type found;
2519 iterator pointer_begin() { return PointerTypes.begin(); }
2520
2521 /// pointer_end - Last pointer type found;
2522 iterator pointer_end() { return PointerTypes.end(); }
2523
2524 /// enumeration_begin - First enumeration type found;
2525 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2526
2527 /// enumeration_end - Last enumeration type found;
2528 iterator enumeration_end() { return EnumerationTypes.end(); }
2529};
2530
2531/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2532/// the set of pointer types along with any more-qualified variants of
2533/// that type. For example, if @p Ty is "int const *", this routine
2534/// will add "int const *", "int const volatile *", "int const
2535/// restrict *", and "int const volatile restrict *" to the set of
2536/// pointer types. Returns true if the add of @p Ty itself succeeded,
2537/// false otherwise.
2538bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2539 // Insert this type.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002540 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregor70d26122008-11-12 17:17:38 +00002541 return false;
2542
2543 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2544 QualType PointeeTy = PointerTy->getPointeeType();
2545 // FIXME: Optimize this so that we don't keep trying to add the same types.
2546
2547 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2548 // with all pointer conversions that don't cast away constness?
2549 if (!PointeeTy.isConstQualified())
2550 AddWithMoreQualifiedTypeVariants
2551 (Context.getPointerType(PointeeTy.withConst()));
2552 if (!PointeeTy.isVolatileQualified())
2553 AddWithMoreQualifiedTypeVariants
2554 (Context.getPointerType(PointeeTy.withVolatile()));
2555 if (!PointeeTy.isRestrictQualified())
2556 AddWithMoreQualifiedTypeVariants
2557 (Context.getPointerType(PointeeTy.withRestrict()));
2558 }
2559
2560 return true;
2561}
2562
2563/// AddTypesConvertedFrom - Add each of the types to which the type @p
2564/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002565/// primarily interested in pointer types and enumeration types.
2566/// AllowUserConversions is true if we should look at the conversion
2567/// functions of a class type, and AllowExplicitConversions if we
2568/// should also include the explicit conversion functions of a class
2569/// type.
2570void
2571BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2572 bool AllowUserConversions,
2573 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002574 // Only deal with canonical types.
2575 Ty = Context.getCanonicalType(Ty);
2576
2577 // Look through reference types; they aren't part of the type of an
2578 // expression for the purposes of conversions.
2579 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2580 Ty = RefTy->getPointeeType();
2581
2582 // We don't care about qualifiers on the type.
2583 Ty = Ty.getUnqualifiedType();
2584
2585 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2586 QualType PointeeTy = PointerTy->getPointeeType();
2587
2588 // Insert our type, and its more-qualified variants, into the set
2589 // of types.
2590 if (!AddWithMoreQualifiedTypeVariants(Ty))
2591 return;
2592
2593 // Add 'cv void*' to our set of types.
2594 if (!Ty->isVoidType()) {
2595 QualType QualVoid
2596 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2597 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2598 }
2599
2600 // If this is a pointer to a class type, add pointers to its bases
2601 // (with the same level of cv-qualification as the original
2602 // derived class, of course).
2603 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2604 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2605 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2606 Base != ClassDecl->bases_end(); ++Base) {
2607 QualType BaseTy = Context.getCanonicalType(Base->getType());
2608 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2609
2610 // Add the pointer type, recursively, so that we get all of
2611 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002612 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002613 }
2614 }
2615 } else if (Ty->isEnumeralType()) {
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002616 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregor70d26122008-11-12 17:17:38 +00002617 } else if (AllowUserConversions) {
2618 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2619 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2620 // FIXME: Visit conversion functions in the base classes, too.
2621 OverloadedFunctionDecl *Conversions
2622 = ClassDecl->getConversionFunctions();
2623 for (OverloadedFunctionDecl::function_iterator Func
2624 = Conversions->function_begin();
2625 Func != Conversions->function_end(); ++Func) {
2626 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002627 if (AllowExplicitConversions || !Conv->isExplicit())
2628 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002629 }
2630 }
2631 }
2632}
2633
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002634/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2635/// operator overloads to the candidate set (C++ [over.built]), based
2636/// on the operator @p Op and the arguments given. For example, if the
2637/// operator is a binary '+', this routine might add "int
2638/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002639void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002640Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2641 Expr **Args, unsigned NumArgs,
2642 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002643 // The set of "promoted arithmetic types", which are the arithmetic
2644 // types are that preserved by promotion (C++ [over.built]p2). Note
2645 // that the first few of these types are the promoted integral
2646 // types; these types need to be first.
2647 // FIXME: What about complex?
2648 const unsigned FirstIntegralType = 0;
2649 const unsigned LastIntegralType = 13;
2650 const unsigned FirstPromotedIntegralType = 7,
2651 LastPromotedIntegralType = 13;
2652 const unsigned FirstPromotedArithmeticType = 7,
2653 LastPromotedArithmeticType = 16;
2654 const unsigned NumArithmeticTypes = 16;
2655 QualType ArithmeticTypes[NumArithmeticTypes] = {
2656 Context.BoolTy, Context.CharTy, Context.WCharTy,
2657 Context.SignedCharTy, Context.ShortTy,
2658 Context.UnsignedCharTy, Context.UnsignedShortTy,
2659 Context.IntTy, Context.LongTy, Context.LongLongTy,
2660 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2661 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2662 };
2663
2664 // Find all of the types that the arguments can convert to, but only
2665 // if the operator we're looking at has built-in operator candidates
2666 // that make use of these types.
2667 BuiltinCandidateTypeSet CandidateTypes(Context);
2668 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2669 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002670 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002671 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002672 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2673 (Op == OO_Star && NumArgs == 1)) {
2674 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002675 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2676 true,
2677 (Op == OO_Exclaim ||
2678 Op == OO_AmpAmp ||
2679 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002680 }
2681
2682 bool isComparison = false;
2683 switch (Op) {
2684 case OO_None:
2685 case NUM_OVERLOADED_OPERATORS:
2686 assert(false && "Expected an overloaded operator");
2687 break;
2688
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002689 case OO_Star: // '*' is either unary or binary
2690 if (NumArgs == 1)
2691 goto UnaryStar;
2692 else
2693 goto BinaryStar;
2694 break;
2695
2696 case OO_Plus: // '+' is either unary or binary
2697 if (NumArgs == 1)
2698 goto UnaryPlus;
2699 else
2700 goto BinaryPlus;
2701 break;
2702
2703 case OO_Minus: // '-' is either unary or binary
2704 if (NumArgs == 1)
2705 goto UnaryMinus;
2706 else
2707 goto BinaryMinus;
2708 break;
2709
2710 case OO_Amp: // '&' is either unary or binary
2711 if (NumArgs == 1)
2712 goto UnaryAmp;
2713 else
2714 goto BinaryAmp;
2715
2716 case OO_PlusPlus:
2717 case OO_MinusMinus:
2718 // C++ [over.built]p3:
2719 //
2720 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2721 // is either volatile or empty, there exist candidate operator
2722 // functions of the form
2723 //
2724 // VQ T& operator++(VQ T&);
2725 // T operator++(VQ T&, int);
2726 //
2727 // C++ [over.built]p4:
2728 //
2729 // For every pair (T, VQ), where T is an arithmetic type other
2730 // than bool, and VQ is either volatile or empty, there exist
2731 // candidate operator functions of the form
2732 //
2733 // VQ T& operator--(VQ T&);
2734 // T operator--(VQ T&, int);
2735 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2736 Arith < NumArithmeticTypes; ++Arith) {
2737 QualType ArithTy = ArithmeticTypes[Arith];
2738 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00002739 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002740
2741 // Non-volatile version.
2742 if (NumArgs == 1)
2743 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2744 else
2745 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2746
2747 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00002748 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002749 if (NumArgs == 1)
2750 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2751 else
2752 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2753 }
2754
2755 // C++ [over.built]p5:
2756 //
2757 // For every pair (T, VQ), where T is a cv-qualified or
2758 // cv-unqualified object type, and VQ is either volatile or
2759 // empty, there exist candidate operator functions of the form
2760 //
2761 // T*VQ& operator++(T*VQ&);
2762 // T*VQ& operator--(T*VQ&);
2763 // T* operator++(T*VQ&, int);
2764 // T* operator--(T*VQ&, int);
2765 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2766 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2767 // Skip pointer types that aren't pointers to object types.
Douglas Gregor24a90a52008-11-26 23:31:11 +00002768 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002769 continue;
2770
2771 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002772 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002773 };
2774
2775 // Without volatile
2776 if (NumArgs == 1)
2777 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2778 else
2779 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2780
2781 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2782 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00002783 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002784 if (NumArgs == 1)
2785 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2786 else
2787 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2788 }
2789 }
2790 break;
2791
2792 UnaryStar:
2793 // C++ [over.built]p6:
2794 // For every cv-qualified or cv-unqualified object type T, there
2795 // exist candidate operator functions of the form
2796 //
2797 // T& operator*(T*);
2798 //
2799 // C++ [over.built]p7:
2800 // For every function type T, there exist candidate operator
2801 // functions of the form
2802 // T& operator*(T*);
2803 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2804 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2805 QualType ParamTy = *Ptr;
2806 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00002807 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002808 &ParamTy, Args, 1, CandidateSet);
2809 }
2810 break;
2811
2812 UnaryPlus:
2813 // C++ [over.built]p8:
2814 // For every type T, there exist candidate operator functions of
2815 // the form
2816 //
2817 // T* operator+(T*);
2818 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2819 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2820 QualType ParamTy = *Ptr;
2821 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2822 }
2823
2824 // Fall through
2825
2826 UnaryMinus:
2827 // C++ [over.built]p9:
2828 // For every promoted arithmetic type T, there exist candidate
2829 // operator functions of the form
2830 //
2831 // T operator+(T);
2832 // T operator-(T);
2833 for (unsigned Arith = FirstPromotedArithmeticType;
2834 Arith < LastPromotedArithmeticType; ++Arith) {
2835 QualType ArithTy = ArithmeticTypes[Arith];
2836 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2837 }
2838 break;
2839
2840 case OO_Tilde:
2841 // C++ [over.built]p10:
2842 // For every promoted integral type T, there exist candidate
2843 // operator functions of the form
2844 //
2845 // T operator~(T);
2846 for (unsigned Int = FirstPromotedIntegralType;
2847 Int < LastPromotedIntegralType; ++Int) {
2848 QualType IntTy = ArithmeticTypes[Int];
2849 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2850 }
2851 break;
2852
Douglas Gregor70d26122008-11-12 17:17:38 +00002853 case OO_New:
2854 case OO_Delete:
2855 case OO_Array_New:
2856 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00002857 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002858 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00002859 break;
2860
2861 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002862 UnaryAmp:
2863 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00002864 // C++ [over.match.oper]p3:
2865 // -- For the operator ',', the unary operator '&', or the
2866 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00002867 break;
2868
2869 case OO_Less:
2870 case OO_Greater:
2871 case OO_LessEqual:
2872 case OO_GreaterEqual:
2873 case OO_EqualEqual:
2874 case OO_ExclaimEqual:
2875 // C++ [over.built]p15:
2876 //
2877 // For every pointer or enumeration type T, there exist
2878 // candidate operator functions of the form
2879 //
2880 // bool operator<(T, T);
2881 // bool operator>(T, T);
2882 // bool operator<=(T, T);
2883 // bool operator>=(T, T);
2884 // bool operator==(T, T);
2885 // bool operator!=(T, T);
2886 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2887 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2888 QualType ParamTypes[2] = { *Ptr, *Ptr };
2889 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2890 }
2891 for (BuiltinCandidateTypeSet::iterator Enum
2892 = CandidateTypes.enumeration_begin();
2893 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2894 QualType ParamTypes[2] = { *Enum, *Enum };
2895 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2896 }
2897
2898 // Fall through.
2899 isComparison = true;
2900
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002901 BinaryPlus:
2902 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00002903 if (!isComparison) {
2904 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2905
2906 // C++ [over.built]p13:
2907 //
2908 // For every cv-qualified or cv-unqualified object type T
2909 // there exist candidate operator functions of the form
2910 //
2911 // T* operator+(T*, ptrdiff_t);
2912 // T& operator[](T*, ptrdiff_t); [BELOW]
2913 // T* operator-(T*, ptrdiff_t);
2914 // T* operator+(ptrdiff_t, T*);
2915 // T& operator[](ptrdiff_t, T*); [BELOW]
2916 //
2917 // C++ [over.built]p14:
2918 //
2919 // For every T, where T is a pointer to object type, there
2920 // exist candidate operator functions of the form
2921 //
2922 // ptrdiff_t operator-(T, T);
2923 for (BuiltinCandidateTypeSet::iterator Ptr
2924 = CandidateTypes.pointer_begin();
2925 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2926 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2927
2928 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2929 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2930
2931 if (Op == OO_Plus) {
2932 // T* operator+(ptrdiff_t, T*);
2933 ParamTypes[0] = ParamTypes[1];
2934 ParamTypes[1] = *Ptr;
2935 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2936 } else {
2937 // ptrdiff_t operator-(T, T);
2938 ParamTypes[1] = *Ptr;
2939 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2940 Args, 2, CandidateSet);
2941 }
2942 }
2943 }
2944 // Fall through
2945
Douglas Gregor70d26122008-11-12 17:17:38 +00002946 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002947 BinaryStar:
Douglas Gregor70d26122008-11-12 17:17:38 +00002948 // C++ [over.built]p12:
2949 //
2950 // For every pair of promoted arithmetic types L and R, there
2951 // exist candidate operator functions of the form
2952 //
2953 // LR operator*(L, R);
2954 // LR operator/(L, R);
2955 // LR operator+(L, R);
2956 // LR operator-(L, R);
2957 // bool operator<(L, R);
2958 // bool operator>(L, R);
2959 // bool operator<=(L, R);
2960 // bool operator>=(L, R);
2961 // bool operator==(L, R);
2962 // bool operator!=(L, R);
2963 //
2964 // where LR is the result of the usual arithmetic conversions
2965 // between types L and R.
2966 for (unsigned Left = FirstPromotedArithmeticType;
2967 Left < LastPromotedArithmeticType; ++Left) {
2968 for (unsigned Right = FirstPromotedArithmeticType;
2969 Right < LastPromotedArithmeticType; ++Right) {
2970 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2971 QualType Result
2972 = isComparison? Context.BoolTy
2973 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2974 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2975 }
2976 }
2977 break;
2978
2979 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002980 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00002981 case OO_Caret:
2982 case OO_Pipe:
2983 case OO_LessLess:
2984 case OO_GreaterGreater:
2985 // C++ [over.built]p17:
2986 //
2987 // For every pair of promoted integral types L and R, there
2988 // exist candidate operator functions of the form
2989 //
2990 // LR operator%(L, R);
2991 // LR operator&(L, R);
2992 // LR operator^(L, R);
2993 // LR operator|(L, R);
2994 // L operator<<(L, R);
2995 // L operator>>(L, R);
2996 //
2997 // where LR is the result of the usual arithmetic conversions
2998 // between types L and R.
2999 for (unsigned Left = FirstPromotedIntegralType;
3000 Left < LastPromotedIntegralType; ++Left) {
3001 for (unsigned Right = FirstPromotedIntegralType;
3002 Right < LastPromotedIntegralType; ++Right) {
3003 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3004 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3005 ? LandR[0]
3006 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3007 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3008 }
3009 }
3010 break;
3011
3012 case OO_Equal:
3013 // C++ [over.built]p20:
3014 //
3015 // For every pair (T, VQ), where T is an enumeration or
3016 // (FIXME:) pointer to member type and VQ is either volatile or
3017 // empty, there exist candidate operator functions of the form
3018 //
3019 // VQ T& operator=(VQ T&, T);
3020 for (BuiltinCandidateTypeSet::iterator Enum
3021 = CandidateTypes.enumeration_begin();
3022 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3023 QualType ParamTypes[2];
3024
3025 // T& operator=(T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003026 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregor70d26122008-11-12 17:17:38 +00003027 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003028 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003029 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003030
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003031 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3032 // volatile T& operator=(volatile T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003033 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003034 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003035 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003036 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003037 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003038 }
3039 // Fall through.
3040
3041 case OO_PlusEqual:
3042 case OO_MinusEqual:
3043 // C++ [over.built]p19:
3044 //
3045 // For every pair (T, VQ), where T is any type and VQ is either
3046 // volatile or empty, there exist candidate operator functions
3047 // of the form
3048 //
3049 // T*VQ& operator=(T*VQ&, T*);
3050 //
3051 // C++ [over.built]p21:
3052 //
3053 // For every pair (T, VQ), where T is a cv-qualified or
3054 // cv-unqualified object type and VQ is either volatile or
3055 // empty, there exist candidate operator functions of the form
3056 //
3057 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3058 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3059 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3060 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3061 QualType ParamTypes[2];
3062 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3063
3064 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003065 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003066 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3067 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003068
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003069 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3070 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003071 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003072 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3073 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003074 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003075 }
3076 // Fall through.
3077
3078 case OO_StarEqual:
3079 case OO_SlashEqual:
3080 // C++ [over.built]p18:
3081 //
3082 // For every triple (L, VQ, R), where L is an arithmetic type,
3083 // VQ is either volatile or empty, and R is a promoted
3084 // arithmetic type, there exist candidate operator functions of
3085 // the form
3086 //
3087 // VQ L& operator=(VQ L&, R);
3088 // VQ L& operator*=(VQ L&, R);
3089 // VQ L& operator/=(VQ L&, R);
3090 // VQ L& operator+=(VQ L&, R);
3091 // VQ L& operator-=(VQ L&, R);
3092 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3093 for (unsigned Right = FirstPromotedArithmeticType;
3094 Right < LastPromotedArithmeticType; ++Right) {
3095 QualType ParamTypes[2];
3096 ParamTypes[1] = ArithmeticTypes[Right];
3097
3098 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003099 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003100 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3101 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003102
3103 // Add this built-in operator as a candidate (VQ is 'volatile').
3104 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003105 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003106 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3107 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003108 }
3109 }
3110 break;
3111
3112 case OO_PercentEqual:
3113 case OO_LessLessEqual:
3114 case OO_GreaterGreaterEqual:
3115 case OO_AmpEqual:
3116 case OO_CaretEqual:
3117 case OO_PipeEqual:
3118 // C++ [over.built]p22:
3119 //
3120 // For every triple (L, VQ, R), where L is an integral type, VQ
3121 // is either volatile or empty, and R is a promoted integral
3122 // type, there exist candidate operator functions of the form
3123 //
3124 // VQ L& operator%=(VQ L&, R);
3125 // VQ L& operator<<=(VQ L&, R);
3126 // VQ L& operator>>=(VQ L&, R);
3127 // VQ L& operator&=(VQ L&, R);
3128 // VQ L& operator^=(VQ L&, R);
3129 // VQ L& operator|=(VQ L&, R);
3130 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3131 for (unsigned Right = FirstPromotedIntegralType;
3132 Right < LastPromotedIntegralType; ++Right) {
3133 QualType ParamTypes[2];
3134 ParamTypes[1] = ArithmeticTypes[Right];
3135
3136 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003137 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003138 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3139
3140 // Add this built-in operator as a candidate (VQ is 'volatile').
3141 ParamTypes[0] = ArithmeticTypes[Left];
3142 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003143 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003144 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3145 }
3146 }
3147 break;
3148
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003149 case OO_Exclaim: {
3150 // C++ [over.operator]p23:
3151 //
3152 // There also exist candidate operator functions of the form
3153 //
3154 // bool operator!(bool);
3155 // bool operator&&(bool, bool); [BELOW]
3156 // bool operator||(bool, bool); [BELOW]
3157 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003158 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3159 /*IsAssignmentOperator=*/false,
3160 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003161 break;
3162 }
3163
Douglas Gregor70d26122008-11-12 17:17:38 +00003164 case OO_AmpAmp:
3165 case OO_PipePipe: {
3166 // C++ [over.operator]p23:
3167 //
3168 // There also exist candidate operator functions of the form
3169 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003170 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003171 // bool operator&&(bool, bool);
3172 // bool operator||(bool, bool);
3173 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003174 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3175 /*IsAssignmentOperator=*/false,
3176 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003177 break;
3178 }
3179
3180 case OO_Subscript:
3181 // C++ [over.built]p13:
3182 //
3183 // For every cv-qualified or cv-unqualified object type T there
3184 // exist candidate operator functions of the form
3185 //
3186 // T* operator+(T*, ptrdiff_t); [ABOVE]
3187 // T& operator[](T*, ptrdiff_t);
3188 // T* operator-(T*, ptrdiff_t); [ABOVE]
3189 // T* operator+(ptrdiff_t, T*); [ABOVE]
3190 // T& operator[](ptrdiff_t, T*);
3191 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3192 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3193 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3194 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003195 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003196
3197 // T& operator[](T*, ptrdiff_t)
3198 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3199
3200 // T& operator[](ptrdiff_t, T*);
3201 ParamTypes[0] = ParamTypes[1];
3202 ParamTypes[1] = *Ptr;
3203 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3204 }
3205 break;
3206
3207 case OO_ArrowStar:
3208 // FIXME: No support for pointer-to-members yet.
3209 break;
3210 }
3211}
3212
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003213/// \brief Add function candidates found via argument-dependent lookup
3214/// to the set of overloading candidates.
3215///
3216/// This routine performs argument-dependent name lookup based on the
3217/// given function name (which may also be an operator name) and adds
3218/// all of the overload candidates found by ADL to the overload
3219/// candidate set (C++ [basic.lookup.argdep]).
3220void
3221Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3222 Expr **Args, unsigned NumArgs,
3223 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003224 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003225
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003226 // Record all of the function candidates that we've already
3227 // added to the overload set, so that we don't add those same
3228 // candidates a second time.
3229 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3230 CandEnd = CandidateSet.end();
3231 Cand != CandEnd; ++Cand)
3232 if (Cand->Function)
3233 Functions.insert(Cand->Function);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003234
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003235 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003236
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003237 // Erase all of the candidates we already knew about.
3238 // FIXME: This is suboptimal. Is there a better way?
3239 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3240 CandEnd = CandidateSet.end();
3241 Cand != CandEnd; ++Cand)
3242 if (Cand->Function)
3243 Functions.erase(Cand->Function);
3244
3245 // For each of the ADL candidates we found, add it to the overload
3246 // set.
3247 for (FunctionSet::iterator Func = Functions.begin(),
3248 FuncEnd = Functions.end();
3249 Func != FuncEnd; ++Func)
3250 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003251}
3252
Douglas Gregord2baafd2008-10-21 16:13:35 +00003253/// isBetterOverloadCandidate - Determines whether the first overload
3254/// candidate is a better candidate than the second (C++ 13.3.3p1).
3255bool
3256Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3257 const OverloadCandidate& Cand2)
3258{
3259 // Define viable functions to be better candidates than non-viable
3260 // functions.
3261 if (!Cand2.Viable)
3262 return Cand1.Viable;
3263 else if (!Cand1.Viable)
3264 return false;
3265
Douglas Gregor3257fb52008-12-22 05:46:06 +00003266 // C++ [over.match.best]p1:
3267 //
3268 // -- if F is a static member function, ICS1(F) is defined such
3269 // that ICS1(F) is neither better nor worse than ICS1(G) for
3270 // any function G, and, symmetrically, ICS1(G) is neither
3271 // better nor worse than ICS1(F).
3272 unsigned StartArg = 0;
3273 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3274 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003275
3276 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3277 // function than another viable function F2 if for all arguments i,
3278 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3279 // then...
3280 unsigned NumArgs = Cand1.Conversions.size();
3281 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3282 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003283 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003284 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3285 Cand2.Conversions[ArgIdx])) {
3286 case ImplicitConversionSequence::Better:
3287 // Cand1 has a better conversion sequence.
3288 HasBetterConversion = true;
3289 break;
3290
3291 case ImplicitConversionSequence::Worse:
3292 // Cand1 can't be better than Cand2.
3293 return false;
3294
3295 case ImplicitConversionSequence::Indistinguishable:
3296 // Do nothing.
3297 break;
3298 }
3299 }
3300
3301 if (HasBetterConversion)
3302 return true;
3303
Douglas Gregor70d26122008-11-12 17:17:38 +00003304 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3305 // implemented, but they require template support.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003306
Douglas Gregor60714f92008-11-07 22:36:19 +00003307 // C++ [over.match.best]p1b4:
3308 //
3309 // -- the context is an initialization by user-defined conversion
3310 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3311 // from the return type of F1 to the destination type (i.e.,
3312 // the type of the entity being initialized) is a better
3313 // conversion sequence than the standard conversion sequence
3314 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003315 if (Cand1.Function && Cand2.Function &&
3316 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003317 isa<CXXConversionDecl>(Cand2.Function)) {
3318 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3319 Cand2.FinalConversion)) {
3320 case ImplicitConversionSequence::Better:
3321 // Cand1 has a better conversion sequence.
3322 return true;
3323
3324 case ImplicitConversionSequence::Worse:
3325 // Cand1 can't be better than Cand2.
3326 return false;
3327
3328 case ImplicitConversionSequence::Indistinguishable:
3329 // Do nothing
3330 break;
3331 }
3332 }
3333
Douglas Gregord2baafd2008-10-21 16:13:35 +00003334 return false;
3335}
3336
3337/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3338/// within an overload candidate set. If overloading is successful,
3339/// the result will be OR_Success and Best will be set to point to the
3340/// best viable function within the candidate set. Otherwise, one of
3341/// several kinds of errors will be returned; see
3342/// Sema::OverloadingResult.
3343Sema::OverloadingResult
3344Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3345 OverloadCandidateSet::iterator& Best)
3346{
3347 // Find the best viable function.
3348 Best = CandidateSet.end();
3349 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3350 Cand != CandidateSet.end(); ++Cand) {
3351 if (Cand->Viable) {
3352 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3353 Best = Cand;
3354 }
3355 }
3356
3357 // If we didn't find any viable functions, abort.
3358 if (Best == CandidateSet.end())
3359 return OR_No_Viable_Function;
3360
3361 // Make sure that this function is better than every other viable
3362 // function. If not, we have an ambiguity.
3363 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3364 Cand != CandidateSet.end(); ++Cand) {
3365 if (Cand->Viable &&
3366 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003367 !isBetterOverloadCandidate(*Best, *Cand)) {
3368 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003369 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003370 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003371 }
3372
3373 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003374 if (Best->Function &&
3375 (Best->Function->isDeleted() ||
3376 Best->Function->getAttr<UnavailableAttr>()))
3377 return OR_Deleted;
3378
3379 // If Best refers to a function that is either deleted (C++0x) or
3380 // unavailable (Clang extension) report an error.
3381
Douglas Gregord2baafd2008-10-21 16:13:35 +00003382 return OR_Success;
3383}
3384
3385/// PrintOverloadCandidates - When overload resolution fails, prints
3386/// diagnostic messages containing the candidates in the candidate
3387/// set. If OnlyViable is true, only viable candidates will be printed.
3388void
3389Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3390 bool OnlyViable)
3391{
3392 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3393 LastCand = CandidateSet.end();
3394 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003395 if (Cand->Viable || !OnlyViable) {
3396 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003397 if (Cand->Function->isDeleted() ||
3398 Cand->Function->getAttr<UnavailableAttr>()) {
3399 // Deleted or "unavailable" function.
3400 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3401 << Cand->Function->isDeleted();
3402 } else {
3403 // Normal function
3404 // FIXME: Give a better reason!
3405 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3406 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003407 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003408 // Desugar the type of the surrogate down to a function type,
3409 // retaining as many typedefs as possible while still showing
3410 // the function type (and, therefore, its parameter types).
3411 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003412 bool isLValueReference = false;
3413 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003414 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003415 if (const LValueReferenceType *FnTypeRef =
3416 FnType->getAsLValueReferenceType()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003417 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003418 isLValueReference = true;
3419 } else if (const RValueReferenceType *FnTypeRef =
3420 FnType->getAsRValueReferenceType()) {
3421 FnType = FnTypeRef->getPointeeType();
3422 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003423 }
3424 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3425 FnType = FnTypePtr->getPointeeType();
3426 isPointer = true;
3427 }
3428 // Desugar down to a function type.
3429 FnType = QualType(FnType->getAsFunctionType(), 0);
3430 // Reconstruct the pointer/reference as appropriate.
3431 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003432 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3433 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003434
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003435 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003436 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003437 } else {
3438 // FIXME: We need to get the identifier in here
3439 // FIXME: Do we want the error message to point at the
3440 // operator? (built-ins won't have a location)
3441 QualType FnType
3442 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3443 Cand->BuiltinTypes.ParamTypes,
3444 Cand->Conversions.size(),
3445 false, 0);
3446
Chris Lattner4bfd2232008-11-24 06:25:27 +00003447 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003448 }
3449 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003450 }
3451}
3452
Douglas Gregor45014fd2008-11-10 20:40:00 +00003453/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3454/// an overloaded function (C++ [over.over]), where @p From is an
3455/// expression with overloaded function type and @p ToType is the type
3456/// we're trying to resolve to. For example:
3457///
3458/// @code
3459/// int f(double);
3460/// int f(int);
3461///
3462/// int (*pfd)(double) = f; // selects f(double)
3463/// @endcode
3464///
3465/// This routine returns the resulting FunctionDecl if it could be
3466/// resolved, and NULL otherwise. When @p Complain is true, this
3467/// routine will emit diagnostics if there is an error.
3468FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003469Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003470 bool Complain) {
3471 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003472 bool IsMember = false;
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003473 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003474 FunctionType = ToTypePtr->getPointeeType();
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003475 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3476 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003477 else if (const MemberPointerType *MemTypePtr =
3478 ToType->getAsMemberPointerType()) {
3479 FunctionType = MemTypePtr->getPointeeType();
3480 IsMember = true;
3481 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003482
3483 // We only look at pointers or references to functions.
3484 if (!FunctionType->isFunctionType())
3485 return 0;
3486
3487 // Find the actual overloaded function declaration.
3488 OverloadedFunctionDecl *Ovl = 0;
3489
3490 // C++ [over.over]p1:
3491 // [...] [Note: any redundant set of parentheses surrounding the
3492 // overloaded function name is ignored (5.1). ]
3493 Expr *OvlExpr = From->IgnoreParens();
3494
3495 // C++ [over.over]p1:
3496 // [...] The overloaded function name can be preceded by the &
3497 // operator.
3498 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3499 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3500 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3501 }
3502
3503 // Try to dig out the overloaded function.
3504 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3505 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3506
3507 // If there's no overloaded function declaration, we're done.
3508 if (!Ovl)
3509 return 0;
3510
3511 // Look through all of the overloaded functions, searching for one
3512 // whose type matches exactly.
3513 // FIXME: When templates or using declarations come along, we'll actually
3514 // have to deal with duplicates, partial ordering, etc. For now, we
3515 // can just do a simple search.
3516 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3517 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3518 Fun != Ovl->function_end(); ++Fun) {
3519 // C++ [over.over]p3:
3520 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003521 // targets of type "pointer-to-function" or "reference-to-function."
3522 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003523 // type "pointer-to-member-function."
3524 // Note that according to DR 247, the containing class does not matter.
3525 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3526 // Skip non-static functions when converting to pointer, and static
3527 // when converting to member pointer.
3528 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003529 continue;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003530 } else if (IsMember)
3531 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003532
3533 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3534 return *Fun;
3535 }
3536
3537 return 0;
3538}
3539
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003540/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003541/// (which eventually refers to the declaration Func) and the call
3542/// arguments Args/NumArgs, attempt to resolve the function call down
3543/// to a specific function. If overload resolution succeeds, returns
3544/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003545/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003546/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003547FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003548 DeclarationName UnqualifiedName,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003549 SourceLocation LParenLoc,
3550 Expr **Args, unsigned NumArgs,
3551 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003552 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003553 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003554 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003555
3556 // Add the functions denoted by Callee to the set of candidate
3557 // functions. While we're doing so, track whether argument-dependent
3558 // lookup still applies, per:
3559 //
3560 // C++0x [basic.lookup.argdep]p3:
3561 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3562 // and let Y be the lookup set produced by argument dependent
3563 // lookup (defined as follows). If X contains
3564 //
3565 // -- a declaration of a class member, or
3566 //
3567 // -- a block-scope function declaration that is not a
3568 // using-declaration, or
3569 //
3570 // -- a declaration that is neither a function or a function
3571 // template
3572 //
3573 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003574 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003575 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3576 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3577 FuncEnd = Ovl->function_end();
3578 Func != FuncEnd; ++Func) {
3579 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3580
3581 if ((*Func)->getDeclContext()->isRecord() ||
3582 (*Func)->getDeclContext()->isFunctionOrMethod())
3583 ArgumentDependentLookup = false;
3584 }
3585 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3586 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3587
3588 if (Func->getDeclContext()->isRecord() ||
3589 Func->getDeclContext()->isFunctionOrMethod())
3590 ArgumentDependentLookup = false;
3591 }
3592
3593 if (Callee)
3594 UnqualifiedName = Callee->getDeclName();
3595
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003596 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003597 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003598 CandidateSet);
3599
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003600 OverloadCandidateSet::iterator Best;
3601 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003602 case OR_Success:
3603 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003604
3605 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00003606 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003607 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00003608 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003609 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3610 break;
3611
3612 case OR_Ambiguous:
3613 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003614 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003615 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3616 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00003617
3618 case OR_Deleted:
3619 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3620 << Best->Function->isDeleted()
3621 << UnqualifiedName
3622 << Fn->getSourceRange();
3623 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3624 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003625 }
3626
3627 // Overload resolution failed. Destroy all of the subexpressions and
3628 // return NULL.
3629 Fn->Destroy(Context);
3630 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3631 Args[Arg]->Destroy(Context);
3632 return 0;
3633}
3634
Douglas Gregorc78182d2009-03-13 23:49:33 +00003635/// \brief Create a unary operation that may resolve to an overloaded
3636/// operator.
3637///
3638/// \param OpLoc The location of the operator itself (e.g., '*').
3639///
3640/// \param OpcIn The UnaryOperator::Opcode that describes this
3641/// operator.
3642///
3643/// \param Functions The set of non-member functions that will be
3644/// considered by overload resolution. The caller needs to build this
3645/// set based on the context using, e.g.,
3646/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3647/// set should not contain any member functions; those will be added
3648/// by CreateOverloadedUnaryOp().
3649///
3650/// \param input The input argument.
3651Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3652 unsigned OpcIn,
3653 FunctionSet &Functions,
3654 ExprArg input) {
3655 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3656 Expr *Input = (Expr *)input.get();
3657
3658 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3659 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3660 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3661
3662 Expr *Args[2] = { Input, 0 };
3663 unsigned NumArgs = 1;
3664
3665 // For post-increment and post-decrement, add the implicit '0' as
3666 // the second argument, so that we know this is a post-increment or
3667 // post-decrement.
3668 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3669 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3670 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3671 SourceLocation());
3672 NumArgs = 2;
3673 }
3674
3675 if (Input->isTypeDependent()) {
3676 OverloadedFunctionDecl *Overloads
3677 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3678 for (FunctionSet::iterator Func = Functions.begin(),
3679 FuncEnd = Functions.end();
3680 Func != FuncEnd; ++Func)
3681 Overloads->addOverload(*Func);
3682
3683 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3684 OpLoc, false, false);
3685
3686 input.release();
3687 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3688 &Args[0], NumArgs,
3689 Context.DependentTy,
3690 OpLoc));
3691 }
3692
3693 // Build an empty overload set.
3694 OverloadCandidateSet CandidateSet;
3695
3696 // Add the candidates from the given function set.
3697 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3698
3699 // Add operator candidates that are member functions.
3700 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3701
3702 // Add builtin operator candidates.
3703 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3704
3705 // Perform overload resolution.
3706 OverloadCandidateSet::iterator Best;
3707 switch (BestViableFunction(CandidateSet, Best)) {
3708 case OR_Success: {
3709 // We found a built-in operator or an overloaded operator.
3710 FunctionDecl *FnDecl = Best->Function;
3711
3712 if (FnDecl) {
3713 // We matched an overloaded operator. Build a call to that
3714 // operator.
3715
3716 // Convert the arguments.
3717 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3718 if (PerformObjectArgumentInitialization(Input, Method))
3719 return ExprError();
3720 } else {
3721 // Convert the arguments.
3722 if (PerformCopyInitialization(Input,
3723 FnDecl->getParamDecl(0)->getType(),
3724 "passing"))
3725 return ExprError();
3726 }
3727
3728 // Determine the result type
3729 QualType ResultTy
3730 = FnDecl->getType()->getAsFunctionType()->getResultType();
3731 ResultTy = ResultTy.getNonReferenceType();
3732
3733 // Build the actual expression node.
3734 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3735 SourceLocation());
3736 UsualUnaryConversions(FnExpr);
3737
3738 input.release();
3739 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3740 &Input, 1, ResultTy,
3741 OpLoc));
3742 } else {
3743 // We matched a built-in operator. Convert the arguments, then
3744 // break out so that we will build the appropriate built-in
3745 // operator node.
3746 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3747 Best->Conversions[0], "passing"))
3748 return ExprError();
3749
3750 break;
3751 }
3752 }
3753
3754 case OR_No_Viable_Function:
3755 // No viable function; fall through to handling this as a
3756 // built-in operator, which will produce an error message for us.
3757 break;
3758
3759 case OR_Ambiguous:
3760 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3761 << UnaryOperator::getOpcodeStr(Opc)
3762 << Input->getSourceRange();
3763 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3764 return ExprError();
3765
3766 case OR_Deleted:
3767 Diag(OpLoc, diag::err_ovl_deleted_oper)
3768 << Best->Function->isDeleted()
3769 << UnaryOperator::getOpcodeStr(Opc)
3770 << Input->getSourceRange();
3771 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3772 return ExprError();
3773 }
3774
3775 // Either we found no viable overloaded operator or we matched a
3776 // built-in operator. In either case, fall through to trying to
3777 // build a built-in operation.
3778 input.release();
3779 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
3780}
3781
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003782/// \brief Create a binary operation that may resolve to an overloaded
3783/// operator.
3784///
3785/// \param OpLoc The location of the operator itself (e.g., '+').
3786///
3787/// \param OpcIn The BinaryOperator::Opcode that describes this
3788/// operator.
3789///
3790/// \param Functions The set of non-member functions that will be
3791/// considered by overload resolution. The caller needs to build this
3792/// set based on the context using, e.g.,
3793/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3794/// set should not contain any member functions; those will be added
3795/// by CreateOverloadedBinOp().
3796///
3797/// \param LHS Left-hand argument.
3798/// \param RHS Right-hand argument.
3799Sema::OwningExprResult
3800Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
3801 unsigned OpcIn,
3802 FunctionSet &Functions,
3803 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003804 Expr *Args[2] = { LHS, RHS };
3805
3806 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
3807 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
3808 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3809
3810 // If either side is type-dependent, create an appropriate dependent
3811 // expression.
3812 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
3813 // .* cannot be overloaded.
3814 if (Opc == BinaryOperator::PtrMemD)
3815 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
3816 Context.DependentTy, OpLoc));
3817
3818 OverloadedFunctionDecl *Overloads
3819 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3820 for (FunctionSet::iterator Func = Functions.begin(),
3821 FuncEnd = Functions.end();
3822 Func != FuncEnd; ++Func)
3823 Overloads->addOverload(*Func);
3824
3825 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3826 OpLoc, false, false);
3827
3828 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3829 Args, 2,
3830 Context.DependentTy,
3831 OpLoc));
3832 }
3833
3834 // If this is the .* operator, which is not overloadable, just
3835 // create a built-in binary operator.
3836 if (Opc == BinaryOperator::PtrMemD)
3837 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3838
3839 // If this is one of the assignment operators, we only perform
3840 // overload resolution if the left-hand side is a class or
3841 // enumeration type (C++ [expr.ass]p3).
3842 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3843 !LHS->getType()->isOverloadableType())
3844 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3845
Douglas Gregorc78182d2009-03-13 23:49:33 +00003846 // Build an empty overload set.
3847 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003848
3849 // Add the candidates from the given function set.
3850 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
3851
3852 // Add operator candidates that are member functions.
3853 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
3854
3855 // Add builtin operator candidates.
3856 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
3857
3858 // Perform overload resolution.
3859 OverloadCandidateSet::iterator Best;
3860 switch (BestViableFunction(CandidateSet, Best)) {
3861 case OR_Success: {
3862 // We found a built-in operator or an overloaded operator.
3863 FunctionDecl *FnDecl = Best->Function;
3864
3865 if (FnDecl) {
3866 // We matched an overloaded operator. Build a call to that
3867 // operator.
3868
3869 // Convert the arguments.
3870 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3871 if (PerformObjectArgumentInitialization(LHS, Method) ||
3872 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
3873 "passing"))
3874 return ExprError();
3875 } else {
3876 // Convert the arguments.
3877 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
3878 "passing") ||
3879 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
3880 "passing"))
3881 return ExprError();
3882 }
3883
3884 // Determine the result type
3885 QualType ResultTy
3886 = FnDecl->getType()->getAsFunctionType()->getResultType();
3887 ResultTy = ResultTy.getNonReferenceType();
3888
3889 // Build the actual expression node.
3890 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3891 SourceLocation());
3892 UsualUnaryConversions(FnExpr);
3893
3894 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3895 Args, 2, ResultTy,
3896 OpLoc));
3897 } else {
3898 // We matched a built-in operator. Convert the arguments, then
3899 // break out so that we will build the appropriate built-in
3900 // operator node.
3901 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
3902 Best->Conversions[0], "passing") ||
3903 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
3904 Best->Conversions[1], "passing"))
3905 return ExprError();
3906
3907 break;
3908 }
3909 }
3910
3911 case OR_No_Viable_Function:
3912 // No viable function; fall through to handling this as a
3913 // built-in operator, which will produce an error message for us.
3914 break;
3915
3916 case OR_Ambiguous:
3917 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3918 << BinaryOperator::getOpcodeStr(Opc)
3919 << LHS->getSourceRange() << RHS->getSourceRange();
3920 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3921 return ExprError();
3922
3923 case OR_Deleted:
3924 Diag(OpLoc, diag::err_ovl_deleted_oper)
3925 << Best->Function->isDeleted()
3926 << BinaryOperator::getOpcodeStr(Opc)
3927 << LHS->getSourceRange() << RHS->getSourceRange();
3928 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3929 return ExprError();
3930 }
3931
3932 // Either we found no viable overloaded operator or we matched a
3933 // built-in operator. In either case, try to build a built-in
3934 // operation.
3935 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3936}
3937
Douglas Gregor3257fb52008-12-22 05:46:06 +00003938/// BuildCallToMemberFunction - Build a call to a member
3939/// function. MemExpr is the expression that refers to the member
3940/// function (and includes the object parameter), Args/NumArgs are the
3941/// arguments to the function call (not including the object
3942/// parameter). The caller needs to validate that the member
3943/// expression refers to a member function or an overloaded member
3944/// function.
3945Sema::ExprResult
3946Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3947 SourceLocation LParenLoc, Expr **Args,
3948 unsigned NumArgs, SourceLocation *CommaLocs,
3949 SourceLocation RParenLoc) {
3950 // Dig out the member expression. This holds both the object
3951 // argument and the member function we're referring to.
3952 MemberExpr *MemExpr = 0;
3953 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3954 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3955 else
3956 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3957 assert(MemExpr && "Building member call without member expression");
3958
3959 // Extract the object argument.
3960 Expr *ObjectArg = MemExpr->getBase();
3961 if (MemExpr->isArrow())
Ted Kremenek0c97e042009-02-07 01:47:29 +00003962 ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref,
3963 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
Douglas Gregor8d103492009-02-19 00:52:42 +00003964 ObjectArg->getLocStart());
Douglas Gregor3257fb52008-12-22 05:46:06 +00003965 CXXMethodDecl *Method = 0;
3966 if (OverloadedFunctionDecl *Ovl
3967 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3968 // Add overload candidates
3969 OverloadCandidateSet CandidateSet;
3970 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3971 FuncEnd = Ovl->function_end();
3972 Func != FuncEnd; ++Func) {
3973 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3974 Method = cast<CXXMethodDecl>(*Func);
3975 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3976 /*SuppressUserConversions=*/false);
3977 }
3978
3979 OverloadCandidateSet::iterator Best;
3980 switch (BestViableFunction(CandidateSet, Best)) {
3981 case OR_Success:
3982 Method = cast<CXXMethodDecl>(Best->Function);
3983 break;
3984
3985 case OR_No_Viable_Function:
3986 Diag(MemExpr->getSourceRange().getBegin(),
3987 diag::err_ovl_no_viable_member_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00003988 << Ovl->getDeclName() << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00003989 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3990 // FIXME: Leaking incoming expressions!
3991 return true;
3992
3993 case OR_Ambiguous:
3994 Diag(MemExpr->getSourceRange().getBegin(),
3995 diag::err_ovl_ambiguous_member_call)
3996 << Ovl->getDeclName() << MemExprE->getSourceRange();
3997 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3998 // FIXME: Leaking incoming expressions!
3999 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004000
4001 case OR_Deleted:
4002 Diag(MemExpr->getSourceRange().getBegin(),
4003 diag::err_ovl_deleted_member_call)
4004 << Best->Function->isDeleted()
4005 << Ovl->getDeclName() << MemExprE->getSourceRange();
4006 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4007 // FIXME: Leaking incoming expressions!
4008 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004009 }
4010
4011 FixOverloadedFunctionReference(MemExpr, Method);
4012 } else {
4013 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4014 }
4015
4016 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004017 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004018 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4019 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004020 Method->getResultType().getNonReferenceType(),
4021 RParenLoc));
4022
4023 // Convert the object argument (for a non-static member function call).
4024 if (!Method->isStatic() &&
4025 PerformObjectArgumentInitialization(ObjectArg, Method))
4026 return true;
4027 MemExpr->setBase(ObjectArg);
4028
4029 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004030 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004031 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4032 RParenLoc))
4033 return true;
4034
Sebastian Redl8b769972009-01-19 00:08:26 +00004035 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004036}
4037
Douglas Gregor10f3c502008-11-19 21:05:33 +00004038/// BuildCallToObjectOfClassType - Build a call to an object of class
4039/// type (C++ [over.call.object]), which can end up invoking an
4040/// overloaded function call operator (@c operator()) or performing a
4041/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004042Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004043Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4044 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004045 Expr **Args, unsigned NumArgs,
4046 SourceLocation *CommaLocs,
4047 SourceLocation RParenLoc) {
4048 assert(Object->getType()->isRecordType() && "Requires object type argument");
4049 const RecordType *Record = Object->getType()->getAsRecordType();
4050
4051 // C++ [over.call.object]p1:
4052 // If the primary-expression E in the function call syntax
4053 // evaluates to a class object of type “cv T”, then the set of
4054 // candidate functions includes at least the function call
4055 // operators of T. The function call operators of T are obtained by
4056 // ordinary lookup of the name operator() in the context of
4057 // (E).operator().
4058 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004059 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004060 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00004061 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004062 Oper != OperEnd; ++Oper)
4063 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4064 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004065
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004066 // C++ [over.call.object]p2:
4067 // In addition, for each conversion function declared in T of the
4068 // form
4069 //
4070 // operator conversion-type-id () cv-qualifier;
4071 //
4072 // where cv-qualifier is the same cv-qualification as, or a
4073 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004074 // denotes the type "pointer to function of (P1,...,Pn) returning
4075 // R", or the type "reference to pointer to function of
4076 // (P1,...,Pn) returning R", or the type "reference to function
4077 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004078 // is also considered as a candidate function. Similarly,
4079 // surrogate call functions are added to the set of candidate
4080 // functions for each conversion function declared in an
4081 // accessible base class provided the function is not hidden
4082 // within T by another intervening declaration.
4083 //
4084 // FIXME: Look in base classes for more conversion operators!
4085 OverloadedFunctionDecl *Conversions
4086 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004087 for (OverloadedFunctionDecl::function_iterator
4088 Func = Conversions->function_begin(),
4089 FuncEnd = Conversions->function_end();
4090 Func != FuncEnd; ++Func) {
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004091 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4092
4093 // Strip the reference type (if any) and then the pointer type (if
4094 // any) to get down to what might be a function type.
4095 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4096 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4097 ConvType = ConvPtrType->getPointeeType();
4098
Douglas Gregor4fa58902009-02-26 23:50:07 +00004099 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004100 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4101 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004102
4103 // Perform overload resolution.
4104 OverloadCandidateSet::iterator Best;
4105 switch (BestViableFunction(CandidateSet, Best)) {
4106 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004107 // Overload resolution succeeded; we'll build the appropriate call
4108 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004109 break;
4110
4111 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004112 Diag(Object->getSourceRange().getBegin(),
4113 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004114 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004115 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004116 break;
4117
4118 case OR_Ambiguous:
4119 Diag(Object->getSourceRange().getBegin(),
4120 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004121 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004122 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4123 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004124
4125 case OR_Deleted:
4126 Diag(Object->getSourceRange().getBegin(),
4127 diag::err_ovl_deleted_object_call)
4128 << Best->Function->isDeleted()
4129 << Object->getType() << Object->getSourceRange();
4130 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4131 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004132 }
4133
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004134 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004135 // We had an error; delete all of the subexpressions and return
4136 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004137 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004138 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004139 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004140 return true;
4141 }
4142
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004143 if (Best->Function == 0) {
4144 // Since there is no function declaration, this is one of the
4145 // surrogate candidates. Dig out the conversion function.
4146 CXXConversionDecl *Conv
4147 = cast<CXXConversionDecl>(
4148 Best->Conversions[0].UserDefined.ConversionFunction);
4149
4150 // We selected one of the surrogate functions that converts the
4151 // object parameter to a function pointer. Perform the conversion
4152 // on the object argument, then let ActOnCallExpr finish the job.
4153 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004154 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004155 Conv->getConversionType().getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +00004156 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004157 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4158 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4159 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004160 }
4161
4162 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4163 // that calls this method, using Object for the implicit object
4164 // parameter and passing along the remaining arguments.
4165 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004166 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004167
4168 unsigned NumArgsInProto = Proto->getNumArgs();
4169 unsigned NumArgsToCheck = NumArgs;
4170
4171 // Build the full argument list for the method call (the
4172 // implicit object parameter is placed at the beginning of the
4173 // list).
4174 Expr **MethodArgs;
4175 if (NumArgs < NumArgsInProto) {
4176 NumArgsToCheck = NumArgsInProto;
4177 MethodArgs = new Expr*[NumArgsInProto + 1];
4178 } else {
4179 MethodArgs = new Expr*[NumArgs + 1];
4180 }
4181 MethodArgs[0] = Object;
4182 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4183 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4184
Ted Kremenek0c97e042009-02-07 01:47:29 +00004185 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4186 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004187 UsualUnaryConversions(NewFn);
4188
4189 // Once we've built TheCall, all of the expressions are properly
4190 // owned.
4191 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004192 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004193 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4194 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004195 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004196 delete [] MethodArgs;
4197
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004198 // We may have default arguments. If so, we need to allocate more
4199 // slots in the call for them.
4200 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004201 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004202 else if (NumArgs > NumArgsInProto)
4203 NumArgsToCheck = NumArgsInProto;
4204
Douglas Gregor10f3c502008-11-19 21:05:33 +00004205 // Initialize the implicit object parameter.
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004206 if (PerformObjectArgumentInitialization(Object, Method))
Douglas Gregor10f3c502008-11-19 21:05:33 +00004207 return true;
4208 TheCall->setArg(0, Object);
4209
4210 // Check the argument types.
4211 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004212 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004213 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004214 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004215
4216 // Pass the argument.
4217 QualType ProtoArgType = Proto->getArgType(i);
4218 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
4219 return true;
4220 } else {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004221 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004222 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004223
4224 TheCall->setArg(i + 1, Arg);
4225 }
4226
4227 // If this is a variadic call, handle args passed through "...".
4228 if (Proto->isVariadic()) {
4229 // Promote the arguments (C99 6.5.2.2p7).
4230 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4231 Expr *Arg = Args[i];
Anders Carlssonfde627e2009-01-13 05:48:52 +00004232
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00004233 DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004234 TheCall->setArg(i + 1, Arg);
4235 }
4236 }
4237
Sebastian Redl8b769972009-01-19 00:08:26 +00004238 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004239}
4240
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004241/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4242/// (if one exists), where @c Base is an expression of class type and
4243/// @c Member is the name of the member we're trying to find.
4244Action::ExprResult
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004245Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004246 SourceLocation MemberLoc,
4247 IdentifierInfo &Member) {
4248 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4249
4250 // C++ [over.ref]p1:
4251 //
4252 // [...] An expression x->m is interpreted as (x.operator->())->m
4253 // for a class object x of type T if T::operator->() exists and if
4254 // the operator is selected as the best match function by the
4255 // overload resolution mechanism (13.3).
4256 // FIXME: look in base classes.
4257 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4258 OverloadCandidateSet CandidateSet;
4259 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004260
4261 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00004262 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004263 Oper != OperEnd; ++Oper)
4264 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004265 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004266
Ted Kremenek0c97e042009-02-07 01:47:29 +00004267 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004268
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004269 // Perform overload resolution.
4270 OverloadCandidateSet::iterator Best;
4271 switch (BestViableFunction(CandidateSet, Best)) {
4272 case OR_Success:
4273 // Overload resolution succeeded; we'll build the call below.
4274 break;
4275
4276 case OR_No_Viable_Function:
4277 if (CandidateSet.empty())
4278 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004279 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004280 else
4281 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Chris Lattner4a526112009-02-17 07:29:20 +00004282 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004283 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004284 return true;
4285
4286 case OR_Ambiguous:
4287 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004288 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004289 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004290 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004291
4292 case OR_Deleted:
4293 Diag(OpLoc, diag::err_ovl_deleted_oper)
4294 << Best->Function->isDeleted()
4295 << "operator->" << BasePtr->getSourceRange();
4296 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4297 return true;
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004298 }
4299
4300 // Convert the object parameter.
4301 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004302 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004303 return true;
Douglas Gregor9c690e92008-11-21 03:04:22 +00004304
4305 // No concerns about early exits now.
4306 BasePtr.take();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004307
4308 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004309 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4310 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004311 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004312 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004313 Method->getResultType().getNonReferenceType(),
4314 OpLoc);
Sebastian Redl8b769972009-01-19 00:08:26 +00004315 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
4316 MemberLoc, Member).release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004317}
4318
Douglas Gregor45014fd2008-11-10 20:40:00 +00004319/// FixOverloadedFunctionReference - E is an expression that refers to
4320/// a C++ overloaded function (possibly with some parentheses and
4321/// perhaps a '&' around it). We have resolved the overloaded function
4322/// to the function declaration Fn, so patch up the expression E to
4323/// refer (possibly indirectly) to Fn.
4324void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4325 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4326 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4327 E->setType(PE->getSubExpr()->getType());
4328 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4329 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4330 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004331 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4332 if (Method->isStatic()) {
4333 // Do nothing: static member functions aren't any different
4334 // from non-member functions.
4335 }
4336 else if (QualifiedDeclRefExpr *DRE
4337 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4338 // We have taken the address of a pointer to member
4339 // function. Perform the computation here so that we get the
4340 // appropriate pointer to member type.
4341 DRE->setDecl(Fn);
4342 DRE->setType(Fn->getType());
4343 QualType ClassType
4344 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4345 E->setType(Context.getMemberPointerType(Fn->getType(),
4346 ClassType.getTypePtr()));
4347 return;
4348 }
4349 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004350 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004351 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004352 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4353 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4354 "Expected overloaded function");
4355 DR->setDecl(Fn);
4356 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004357 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4358 MemExpr->setMemberDecl(Fn);
4359 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004360 } else {
4361 assert(false && "Invalid reference to overloaded function");
4362 }
4363}
4364
Douglas Gregord2baafd2008-10-21 16:13:35 +00004365} // end namespace clang