blob: b7f698eb0b5ea061d433892e514c424441e78673 [file] [log] [blame]
Douglas Gregor8e9bebd2008-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 Gregor94b1dd22008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-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 Gregor5cdf8212009-02-12 00:15:05 +000042 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000045 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000050 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000051 ICC_Conversion,
Douglas Gregor8e9bebd2008-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 Gregor5cdf8212009-02-12 00:15:05 +000069 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000077 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000078 ICR_Conversion,
Douglas Gregor8e9bebd2008-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 Gregor5cdf8212009-02-12 00:15:05 +000095 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000096 "Integral conversion",
97 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000098 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000099 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Pointer conversion",
102 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000103 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000104 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000105 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 };
107 return Name[Kind];
108}
109
Douglas Gregor60d62c22008-10-31 16:23:19 +0000110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113 First = ICK_Identity;
114 Second = ICK_Identity;
115 Third = ICK_Identity;
116 Deprecated = false;
117 ReferenceBinding = false;
118 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000119 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000120 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000121}
122
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000123/// getRank - Retrieve the rank of this standard conversion sequence
124/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
125/// implicit conversions.
126ImplicitConversionRank StandardConversionSequence::getRank() const {
127 ImplicitConversionRank Rank = ICR_Exact_Match;
128 if (GetConversionRank(First) > Rank)
129 Rank = GetConversionRank(First);
130 if (GetConversionRank(Second) > Rank)
131 Rank = GetConversionRank(Second);
132 if (GetConversionRank(Third) > Rank)
133 Rank = GetConversionRank(Third);
134 return Rank;
135}
136
137/// isPointerConversionToBool - Determines whether this conversion is
138/// a conversion of a pointer or pointer-to-member to bool. This is
139/// used as part of the ranking of standard conversion sequences
140/// (C++ 13.3.3.2p4).
141bool StandardConversionSequence::isPointerConversionToBool() const
142{
143 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
144 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
145
146 // Note that FromType has not necessarily been transformed by the
147 // array-to-pointer or function-to-pointer implicit conversions, so
148 // check for their presence as well as checking whether FromType is
149 // a pointer.
150 if (ToType->isBooleanType() &&
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000151 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
153 return true;
154
155 return false;
156}
157
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000158/// isPointerConversionToVoidPointer - Determines whether this
159/// conversion is a conversion of a pointer to a void pointer. This is
160/// used as part of the ranking of standard conversion sequences (C++
161/// 13.3.3.2p4).
162bool
163StandardConversionSequence::
164isPointerConversionToVoidPointer(ASTContext& Context) const
165{
166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
176 if (const PointerType* ToPtrType = ToType->getAsPointerType())
177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
263// FunctionDecl that New cannot be overloaded with.
264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
272// so IsOverload will not be used.
273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl)
288{
289 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
290 // Is this new function an overload of every function in the
291 // overload set?
292 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
293 FuncEnd = Ovl->function_end();
294 for (; Func != FuncEnd; ++Func) {
295 if (!IsOverload(New, *Func, MatchedDecl)) {
296 MatchedDecl = Func;
297 return false;
298 }
299 }
300
301 // This function overloads every function in the overload set.
302 return true;
Douglas Gregore53060f2009-06-25 22:08:12 +0000303 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
304 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
305 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000306 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
307 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
308
309 // C++ [temp.fct]p2:
310 // A function template can be overloaded with other function templates
311 // and with normal (non-template) functions.
312 if ((OldTemplate == 0) != (NewTemplate == 0))
313 return true;
314
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000315 // Is the function New an overload of the function Old?
316 QualType OldQType = Context.getCanonicalType(Old->getType());
317 QualType NewQType = Context.getCanonicalType(New->getType());
318
319 // Compare the signatures (C++ 1.3.10) of the two functions to
320 // determine whether they are overloads. If we find any mismatch
321 // in the signature, they are overloads.
322
323 // If either of these functions is a K&R-style function (no
324 // prototype), then we consider them to have matching signatures.
Douglas Gregor72564e72009-02-26 23:50:07 +0000325 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
326 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000327 return false;
328
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000329 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
330 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000331
332 // The signature of a function includes the types of its
333 // parameters (C++ 1.3.10), which includes the presence or absence
334 // of the ellipsis; see C++ DR 357).
335 if (OldQType != NewQType &&
336 (OldType->getNumArgs() != NewType->getNumArgs() ||
337 OldType->isVariadic() != NewType->isVariadic() ||
338 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
339 NewType->arg_type_begin())))
340 return true;
341
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000342 // C++ [temp.over.link]p4:
343 // The signature of a function template consists of its function
344 // signature, its return type and its template parameter list. The names
345 // of the template parameters are significant only for establishing the
346 // relationship between the template parameters and the rest of the
347 // signature.
348 //
349 // We check the return type and template parameter lists for function
350 // templates first; the remaining checks follow.
351 if (NewTemplate &&
352 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
353 OldTemplate->getTemplateParameters(),
354 false, false, SourceLocation()) ||
355 OldType->getResultType() != NewType->getResultType()))
356 return true;
357
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000358 // If the function is a class member, its signature includes the
359 // cv-qualifiers (if any) on the function itself.
360 //
361 // As part of this, also check whether one of the member functions
362 // is static, in which case they are not overloads (C++
363 // 13.1p2). While not part of the definition of the signature,
364 // this check is important to determine whether these functions
365 // can be overloaded.
366 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
367 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
368 if (OldMethod && NewMethod &&
369 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000370 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000371 return true;
372
373 // The signatures match; this is not an overload.
374 return false;
375 } else {
376 // (C++ 13p1):
377 // Only function declarations can be overloaded; object and type
378 // declarations cannot be overloaded.
379 return false;
380 }
381}
382
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000383/// TryImplicitConversion - Attempt to perform an implicit conversion
384/// from the given expression (Expr) to the given type (ToType). This
385/// function returns an implicit conversion sequence that can be used
386/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000387///
388/// void f(float f);
389/// void g(int i) { f(i); }
390///
391/// this routine would produce an implicit conversion sequence to
392/// describe the initialization of f from i, which will be a standard
393/// conversion sequence containing an lvalue-to-rvalue conversion (C++
394/// 4.1) followed by a floating-integral conversion (C++ 4.9).
395//
396/// Note that this routine only determines how the conversion can be
397/// performed; it does not actually perform the conversion. As such,
398/// it will not produce any diagnostics if no conversion is available,
399/// but will instead return an implicit conversion sequence of kind
400/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000401///
402/// If @p SuppressUserConversions, then user-defined conversions are
403/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000404/// If @p AllowExplicit, then explicit user-defined conversions are
405/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000406/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
407/// no matter its actual lvalueness.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000408ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000409Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000410 bool SuppressUserConversions,
Sebastian Redle2b68332009-04-12 17:16:29 +0000411 bool AllowExplicit, bool ForceRValue)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000412{
413 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000414 if (IsStandardConversion(From, ToType, ICS.Standard))
415 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000416 else if (getLangOptions().CPlusPlus &&
417 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redle2b68332009-04-12 17:16:29 +0000418 !SuppressUserConversions, AllowExplicit,
419 ForceRValue)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000420 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000421 // C++ [over.ics.user]p4:
422 // A conversion of an expression of class type to the same class
423 // type is given Exact Match rank, and a conversion of an
424 // expression of class type to a base class of that type is
425 // given Conversion rank, in spite of the fact that a copy
426 // constructor (i.e., a user-defined conversion function) is
427 // called for those cases.
428 if (CXXConstructorDecl *Constructor
429 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000430 QualType FromCanon
431 = Context.getCanonicalType(From->getType().getUnqualifiedType());
432 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
433 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000434 // Turn this into a "standard" conversion sequence, so that it
435 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000436 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
437 ICS.Standard.setAsIdentityConversion();
438 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
439 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000440 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000441 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000442 ICS.Standard.Second = ICK_Derived_To_Base;
443 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000444 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000445
446 // C++ [over.best.ics]p4:
447 // However, when considering the argument of a user-defined
448 // conversion function that is a candidate by 13.3.1.3 when
449 // invoked for the copying of the temporary in the second step
450 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
451 // 13.3.1.6 in all cases, only standard conversion sequences and
452 // ellipsis conversion sequences are allowed.
453 if (SuppressUserConversions &&
454 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
455 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000456 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000457 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000458
459 return ICS;
460}
461
462/// IsStandardConversion - Determines whether there is a standard
463/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
464/// expression From to the type ToType. Standard conversion sequences
465/// only consider non-class types; for conversions that involve class
466/// types, use TryImplicitConversion. If a conversion exists, SCS will
467/// contain the standard conversion sequence required to perform this
468/// conversion and this routine will return true. Otherwise, this
469/// routine will return false and the value of SCS is unspecified.
470bool
471Sema::IsStandardConversion(Expr* From, QualType ToType,
472 StandardConversionSequence &SCS)
473{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 QualType FromType = From->getType();
475
Douglas Gregor60d62c22008-10-31 16:23:19 +0000476 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000477 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000478 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000479 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000480 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000481 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482
Douglas Gregorf9201e02009-02-11 23:02:49 +0000483 // There are no standard conversions for class types in C++, so
484 // abort early. When overloading in C, however, we do permit
485 if (FromType->isRecordType() || ToType->isRecordType()) {
486 if (getLangOptions().CPlusPlus)
487 return false;
488
489 // When we're overloading in C, we allow, as standard conversions,
490 }
491
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000492 // The first conversion can be an lvalue-to-rvalue conversion,
493 // array-to-pointer conversion, or function-to-pointer conversion
494 // (C++ 4p1).
495
496 // Lvalue-to-rvalue conversion (C++ 4.1):
497 // An lvalue (3.10) of a non-function, non-array type T can be
498 // converted to an rvalue.
499 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
500 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000501 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000502 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000503 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504
505 // If T is a non-class type, the type of the rvalue is the
506 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000507 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
508 // just strip the qualifiers because they don't matter.
509
510 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor60d62c22008-10-31 16:23:19 +0000511 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000512 }
513 // Array-to-pointer conversion (C++ 4.2)
514 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000515 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516
517 // An lvalue or rvalue of type "array of N T" or "array of unknown
518 // bound of T" can be converted to an rvalue of type "pointer to
519 // T" (C++ 4.2p1).
520 FromType = Context.getArrayDecayedType(FromType);
521
522 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
523 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000524 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000525
526 // For the purpose of ranking in overload resolution
527 // (13.3.3.1.1), this conversion is considered an
528 // array-to-pointer conversion followed by a qualification
529 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000530 SCS.Second = ICK_Identity;
531 SCS.Third = ICK_Qualification;
532 SCS.ToTypePtr = ToType.getAsOpaquePtr();
533 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534 }
535 }
536 // Function-to-pointer conversion (C++ 4.3).
537 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000538 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000539
540 // An lvalue of function type T can be converted to an rvalue of
541 // type "pointer to T." The result is a pointer to the
542 // function. (C++ 4.3p1).
543 FromType = Context.getPointerType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000544 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000545 // Address of overloaded function (C++ [over.over]).
546 else if (FunctionDecl *Fn
547 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
548 SCS.First = ICK_Function_To_Pointer;
549
550 // We were able to resolve the address of the overloaded function,
551 // so we can convert to the type of that function.
552 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000553 if (ToType->isLValueReferenceType())
554 FromType = Context.getLValueReferenceType(FromType);
555 else if (ToType->isRValueReferenceType())
556 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000557 else if (ToType->isMemberPointerType()) {
558 // Resolve address only succeeds if both sides are member pointers,
559 // but it doesn't have to be the same class. See DR 247.
560 // Note that this means that the type of &Derived::fn can be
561 // Ret (Base::*)(Args) if the fn overload actually found is from the
562 // base class, even if it was brought into the derived class via a
563 // using declaration. The standard isn't clear on this issue at all.
564 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
565 FromType = Context.getMemberPointerType(FromType,
566 Context.getTypeDeclType(M->getParent()).getTypePtr());
567 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000568 FromType = Context.getPointerType(FromType);
569 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000570 // We don't require any conversions for the first step.
571 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000572 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000573 }
574
575 // The second conversion can be an integral promotion, floating
576 // point promotion, integral conversion, floating point conversion,
577 // floating-integral conversion, pointer conversion,
578 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000579 // For overloading in C, this can also be a "compatible-type"
580 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000581 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000582 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000583 // The unqualified versions of the types are the same: there's no
584 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000585 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000586 }
587 // Integral promotion (C++ 4.5).
588 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000589 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000590 FromType = ToType.getUnqualifiedType();
591 }
592 // Floating point promotion (C++ 4.6).
593 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000594 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000595 FromType = ToType.getUnqualifiedType();
596 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000597 // Complex promotion (Clang extension)
598 else if (IsComplexPromotion(FromType, ToType)) {
599 SCS.Second = ICK_Complex_Promotion;
600 FromType = ToType.getUnqualifiedType();
601 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000602 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000603 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000605 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000606 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000607 FromType = ToType.getUnqualifiedType();
608 }
609 // Floating point conversions (C++ 4.8).
610 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000611 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000612 FromType = ToType.getUnqualifiedType();
613 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000614 // Complex conversions (C99 6.3.1.6)
615 else if (FromType->isComplexType() && ToType->isComplexType()) {
616 SCS.Second = ICK_Complex_Conversion;
617 FromType = ToType.getUnqualifiedType();
618 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000619 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000620 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000621 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000622 ToType->isIntegralType() && !ToType->isBooleanType() &&
623 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000624 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
625 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000626 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000627 FromType = ToType.getUnqualifiedType();
628 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000629 // Complex-real conversions (C99 6.3.1.7)
630 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631 (ToType->isComplexType() && FromType->isArithmeticType())) {
632 SCS.Second = ICK_Complex_Real;
633 FromType = ToType.getUnqualifiedType();
634 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000635 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000636 else if (IsPointerConversion(From, FromType, ToType, FromType,
637 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000638 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000639 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000640 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000641 // Pointer to member conversions (4.11).
642 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
643 SCS.Second = ICK_Pointer_Member;
644 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000645 // Boolean conversions (C++ 4.12).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000646 else if (ToType->isBooleanType() &&
647 (FromType->isArithmeticType() ||
648 FromType->isEnumeralType() ||
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000649 FromType->isPointerType() ||
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000650 FromType->isBlockPointerType() ||
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000651 FromType->isMemberPointerType() ||
652 FromType->isNullPtrType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000653 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000654 FromType = Context.BoolTy;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000655 }
656 // Compatible conversions (Clang extension for C function overloading)
657 else if (!getLangOptions().CPlusPlus &&
658 Context.typesAreCompatible(ToType, FromType)) {
659 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000660 } else {
661 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000662 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000663 }
664
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000665 QualType CanonFrom;
666 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000667 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000668 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000669 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000670 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000671 CanonFrom = Context.getCanonicalType(FromType);
672 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000673 } else {
674 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000675 SCS.Third = ICK_Identity;
676
677 // C++ [over.best.ics]p6:
678 // [...] Any difference in top-level cv-qualification is
679 // subsumed by the initialization itself and does not constitute
680 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000681 CanonFrom = Context.getCanonicalType(FromType);
682 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000683 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000684 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
685 FromType = ToType;
686 CanonFrom = CanonTo;
687 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000688 }
689
690 // If we have not converted the argument type to the parameter type,
691 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000692 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000693 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000694
Douglas Gregor60d62c22008-10-31 16:23:19 +0000695 SCS.ToTypePtr = FromType.getAsOpaquePtr();
696 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000697}
698
699/// IsIntegralPromotion - Determines whether the conversion from the
700/// expression From (whose potentially-adjusted type is FromType) to
701/// ToType is an integral promotion (C++ 4.5). If so, returns true and
702/// sets PromotedType to the promoted type.
703bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
704{
705 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000706 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000707 if (!To) {
708 return false;
709 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000710
711 // An rvalue of type char, signed char, unsigned char, short int, or
712 // unsigned short int can be converted to an rvalue of type int if
713 // int can represent all the values of the source type; otherwise,
714 // the source rvalue can be converted to an rvalue of type unsigned
715 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000717 if (// We can promote any signed, promotable integer type to an int
718 (FromType->isSignedIntegerType() ||
719 // We can promote any unsigned integer type whose size is
720 // less than int to an int.
721 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000722 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000723 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000724 }
725
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000726 return To->getKind() == BuiltinType::UInt;
727 }
728
729 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
730 // can be converted to an rvalue of the first of the following types
731 // that can represent all the values of its underlying type: int,
732 // unsigned int, long, or unsigned long (C++ 4.5p2).
733 if ((FromType->isEnumeralType() || FromType->isWideCharType())
734 && ToType->isIntegerType()) {
735 // Determine whether the type we're converting from is signed or
736 // unsigned.
737 bool FromIsSigned;
738 uint64_t FromSize = Context.getTypeSize(FromType);
739 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
740 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
741 FromIsSigned = UnderlyingType->isSignedIntegerType();
742 } else {
743 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
744 FromIsSigned = true;
745 }
746
747 // The types we'll try to promote to, in the appropriate
748 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000749 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000750 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000751 Context.LongTy, Context.UnsignedLongTy ,
752 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000753 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000754 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000755 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
756 if (FromSize < ToSize ||
757 (FromSize == ToSize &&
758 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
759 // We found the type that we can promote to. If this is the
760 // type we wanted, we have a promotion. Otherwise, no
761 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000762 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000763 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
764 }
765 }
766 }
767
768 // An rvalue for an integral bit-field (9.6) can be converted to an
769 // rvalue of type int if int can represent all the values of the
770 // bit-field; otherwise, it can be converted to unsigned int if
771 // unsigned int can represent all the values of the bit-field. If
772 // the bit-field is larger yet, no integral promotion applies to
773 // it. If the bit-field has an enumerated type, it is treated as any
774 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000775 // FIXME: We should delay checking of bit-fields until we actually perform the
776 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000777 using llvm::APSInt;
778 if (From)
779 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000780 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000781 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
782 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
783 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
784 ToSize = Context.getTypeSize(ToType);
Douglas Gregor86f19402008-12-20 23:49:58 +0000785
786 // Are we promoting to an int from a bitfield that fits in an int?
787 if (BitWidth < ToSize ||
788 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
789 return To->getKind() == BuiltinType::Int;
790 }
791
792 // Are we promoting to an unsigned int from an unsigned bitfield
793 // that fits into an unsigned int?
794 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
795 return To->getKind() == BuiltinType::UInt;
796 }
797
798 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000799 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000800 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000801
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000802 // An rvalue of type bool can be converted to an rvalue of type int,
803 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000804 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000805 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000806 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000807
808 return false;
809}
810
811/// IsFloatingPointPromotion - Determines whether the conversion from
812/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
813/// returns true and sets PromotedType to the promoted type.
814bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
815{
816 /// An rvalue of type float can be converted to an rvalue of type
817 /// double. (C++ 4.6p1).
818 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000819 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000820 if (FromBuiltin->getKind() == BuiltinType::Float &&
821 ToBuiltin->getKind() == BuiltinType::Double)
822 return true;
823
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000824 // C99 6.3.1.5p1:
825 // When a float is promoted to double or long double, or a
826 // double is promoted to long double [...].
827 if (!getLangOptions().CPlusPlus &&
828 (FromBuiltin->getKind() == BuiltinType::Float ||
829 FromBuiltin->getKind() == BuiltinType::Double) &&
830 (ToBuiltin->getKind() == BuiltinType::LongDouble))
831 return true;
832 }
833
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000834 return false;
835}
836
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000837/// \brief Determine if a conversion is a complex promotion.
838///
839/// A complex promotion is defined as a complex -> complex conversion
840/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000841/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000842bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
843 const ComplexType *FromComplex = FromType->getAsComplexType();
844 if (!FromComplex)
845 return false;
846
847 const ComplexType *ToComplex = ToType->getAsComplexType();
848 if (!ToComplex)
849 return false;
850
851 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000852 ToComplex->getElementType()) ||
853 IsIntegralPromotion(0, FromComplex->getElementType(),
854 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000855}
856
Douglas Gregorcb7de522008-11-26 23:31:11 +0000857/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
858/// the pointer type FromPtr to a pointer to type ToPointee, with the
859/// same type qualifiers as FromPtr has on its pointee type. ToType,
860/// if non-empty, will be a pointer to ToType that may or may not have
861/// the right set of qualifiers on its pointee.
862static QualType
863BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
864 QualType ToPointee, QualType ToType,
865 ASTContext &Context) {
866 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
867 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
868 unsigned Quals = CanonFromPointee.getCVRQualifiers();
869
870 // Exact qualifier match -> return the pointer type we're converting to.
871 if (CanonToPointee.getCVRQualifiers() == Quals) {
872 // ToType is exactly what we need. Return it.
873 if (ToType.getTypePtr())
874 return ToType;
875
876 // Build a pointer to ToPointee. It has the right qualifiers
877 // already.
878 return Context.getPointerType(ToPointee);
879 }
880
881 // Just build a canonical type that has the right qualifiers.
882 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
883}
884
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000885/// IsPointerConversion - Determines whether the conversion of the
886/// expression From, which has the (possibly adjusted) type FromType,
887/// can be converted to the type ToType via a pointer conversion (C++
888/// 4.10). If so, returns true and places the converted type (that
889/// might differ from ToType in its cv-qualifiers at some level) into
890/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000891///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000892/// This routine also supports conversions to and from block pointers
893/// and conversions with Objective-C's 'id', 'id<protocols...>', and
894/// pointers to interfaces. FIXME: Once we've determined the
895/// appropriate overloading rules for Objective-C, we may want to
896/// split the Objective-C checks into a different routine; however,
897/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000898/// conversions, so for now they live here. IncompatibleObjC will be
899/// set if the conversion is an allowed Objective-C conversion that
900/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000901bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000902 QualType& ConvertedType,
903 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000904{
Douglas Gregor45920e82008-12-19 17:40:08 +0000905 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000906 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
907 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000908
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000909 // Conversion from a null pointer constant to any Objective-C pointer type.
910 if (Context.isObjCObjectPointerType(ToType) &&
911 From->isNullPointerConstant(Context)) {
912 ConvertedType = ToType;
913 return true;
914 }
915
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000916 // Blocks: Block pointers can be converted to void*.
917 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
918 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
919 ConvertedType = ToType;
920 return true;
921 }
922 // Blocks: A null pointer constant can be converted to a block
923 // pointer type.
924 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
925 ConvertedType = ToType;
926 return true;
927 }
928
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000929 // If the left-hand-side is nullptr_t, the right side can be a null
930 // pointer constant.
931 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
932 ConvertedType = ToType;
933 return true;
934 }
935
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000936 const PointerType* ToTypePtr = ToType->getAsPointerType();
937 if (!ToTypePtr)
938 return false;
939
940 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
941 if (From->isNullPointerConstant(Context)) {
942 ConvertedType = ToType;
943 return true;
944 }
Sebastian Redl07779722008-10-31 14:43:28 +0000945
Douglas Gregorcb7de522008-11-26 23:31:11 +0000946 // Beyond this point, both types need to be pointers.
947 const PointerType *FromTypePtr = FromType->getAsPointerType();
948 if (!FromTypePtr)
949 return false;
950
951 QualType FromPointeeType = FromTypePtr->getPointeeType();
952 QualType ToPointeeType = ToTypePtr->getPointeeType();
953
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000954 // An rvalue of type "pointer to cv T," where T is an object type,
955 // can be converted to an rvalue of type "pointer to cv void" (C++
956 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +0000957 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000958 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
959 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000960 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000961 return true;
962 }
963
Douglas Gregorf9201e02009-02-11 23:02:49 +0000964 // When we're overloading in C, we allow a special kind of pointer
965 // conversion for compatible-but-not-identical pointee types.
966 if (!getLangOptions().CPlusPlus &&
967 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
969 ToPointeeType,
970 ToType, Context);
971 return true;
972 }
973
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000974 // C++ [conv.ptr]p3:
975 //
976 // An rvalue of type "pointer to cv D," where D is a class type,
977 // can be converted to an rvalue of type "pointer to cv B," where
978 // B is a base class (clause 10) of D. If B is an inaccessible
979 // (clause 11) or ambiguous (10.2) base class of D, a program that
980 // necessitates this conversion is ill-formed. The result of the
981 // conversion is a pointer to the base class sub-object of the
982 // derived class object. The null pointer value is converted to
983 // the null pointer value of the destination type.
984 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000985 // Note that we do not check for ambiguity or inaccessibility
986 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +0000987 if (getLangOptions().CPlusPlus &&
988 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorcb7de522008-11-26 23:31:11 +0000989 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000990 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
991 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000992 ToType, Context);
993 return true;
994 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000995
Douglas Gregorc7887512008-12-19 19:13:09 +0000996 return false;
997}
998
999/// isObjCPointerConversion - Determines whether this is an
1000/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1001/// with the same arguments and return values.
1002bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1003 QualType& ConvertedType,
1004 bool &IncompatibleObjC) {
1005 if (!getLangOptions().ObjC1)
1006 return false;
1007
Steve Naroff14108da2009-07-10 23:34:53 +00001008 // First, we handle all conversions on ObjC object pointer types.
1009 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
1010 const ObjCObjectPointerType *FromObjCPtr =
1011 FromType->getAsObjCObjectPointerType();
Douglas Gregorc7887512008-12-19 19:13:09 +00001012
Steve Naroff14108da2009-07-10 23:34:53 +00001013 if (ToObjCPtr && FromObjCPtr) {
1014 // Objective C++: We're able to convert between "id" and a pointer
1015 // to any interface (in both directions).
1016 if (ToObjCPtr->isObjCIdType() && FromObjCPtr->isObjCIdType()) {
1017 ConvertedType = ToType;
1018 return true;
1019 }
1020 // Objective C++: Allow conversions between the Objective-C "Class" and a
1021 // pointer to any interface (in both directions).
1022 if (ToObjCPtr->isObjCClassType() || FromObjCPtr->isObjCClassType()) {
1023 ConvertedType = ToType;
1024 return true;
1025 }
1026 // Conversions with Objective-C's id<...>.
1027 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1028 ToObjCPtr->isObjCQualifiedIdType()) &&
1029 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
1030 ConvertedType = ToType;
1031 return true;
1032 }
1033 // Objective C++: We're able to convert from a pointer to an
1034 // interface to a pointer to a different interface.
1035 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1036 ConvertedType = ToType;
1037 return true;
1038 }
1039
1040 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1041 // Okay: this is some kind of implicit downcast of Objective-C
1042 // interfaces, which is permitted. However, we're going to
1043 // complain about it.
1044 IncompatibleObjC = true;
1045 ConvertedType = FromType;
1046 return true;
1047 }
1048 }
1049 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001050 QualType ToPointeeType;
Steve Naroff14108da2009-07-10 23:34:53 +00001051 if (const PointerType *ToCPtr = ToType->getAsPointerType())
1052 ToPointeeType = ToCPtr->getPointeeType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001053 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
1054 ToPointeeType = ToBlockPtr->getPointeeType();
1055 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001056 return false;
1057
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001058 QualType FromPointeeType;
Steve Naroff14108da2009-07-10 23:34:53 +00001059 if (const PointerType *FromCPtr = FromType->getAsPointerType())
1060 FromPointeeType = FromCPtr->getPointeeType();
1061 else if (const BlockPointerType *FromBlockPtr = FromType->getAsBlockPointerType())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001062 FromPointeeType = FromBlockPtr->getPointeeType();
1063 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001064 return false;
1065
Douglas Gregorc7887512008-12-19 19:13:09 +00001066 // If we have pointers to pointers, recursively check whether this
1067 // is an Objective-C conversion.
1068 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1069 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1070 IncompatibleObjC)) {
1071 // We always complain about this conversion.
1072 IncompatibleObjC = true;
1073 ConvertedType = ToType;
1074 return true;
1075 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001076 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001077 // differences in the argument and result types are in Objective-C
1078 // pointer conversions. If so, we permit the conversion (but
1079 // complain about it).
Douglas Gregor72564e72009-02-26 23:50:07 +00001080 const FunctionProtoType *FromFunctionType
1081 = FromPointeeType->getAsFunctionProtoType();
1082 const FunctionProtoType *ToFunctionType
1083 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregorc7887512008-12-19 19:13:09 +00001084 if (FromFunctionType && ToFunctionType) {
1085 // If the function types are exactly the same, this isn't an
1086 // Objective-C pointer conversion.
1087 if (Context.getCanonicalType(FromPointeeType)
1088 == Context.getCanonicalType(ToPointeeType))
1089 return false;
1090
1091 // Perform the quick checks that will tell us whether these
1092 // function types are obviously different.
1093 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1094 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1095 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1096 return false;
1097
1098 bool HasObjCConversion = false;
1099 if (Context.getCanonicalType(FromFunctionType->getResultType())
1100 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1101 // Okay, the types match exactly. Nothing to do.
1102 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1103 ToFunctionType->getResultType(),
1104 ConvertedType, IncompatibleObjC)) {
1105 // Okay, we have an Objective-C pointer conversion.
1106 HasObjCConversion = true;
1107 } else {
1108 // Function types are too different. Abort.
1109 return false;
1110 }
1111
1112 // Check argument types.
1113 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1114 ArgIdx != NumArgs; ++ArgIdx) {
1115 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1116 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1117 if (Context.getCanonicalType(FromArgType)
1118 == Context.getCanonicalType(ToArgType)) {
1119 // Okay, the types match exactly. Nothing to do.
1120 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1121 ConvertedType, IncompatibleObjC)) {
1122 // Okay, we have an Objective-C pointer conversion.
1123 HasObjCConversion = true;
1124 } else {
1125 // Argument types are too different. Abort.
1126 return false;
1127 }
1128 }
1129
1130 if (HasObjCConversion) {
1131 // We had an Objective-C conversion. Allow this pointer
1132 // conversion, but complain about it.
1133 ConvertedType = ToType;
1134 IncompatibleObjC = true;
1135 return true;
1136 }
1137 }
1138
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001139 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001140}
1141
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001142/// CheckPointerConversion - Check the pointer conversion from the
1143/// expression From to the type ToType. This routine checks for
1144/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1145/// conversions for which IsPointerConversion has already returned
1146/// true. It returns true and produces a diagnostic if there was an
1147/// error, or returns false otherwise.
1148bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1149 QualType FromType = From->getType();
1150
1151 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1152 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001153 QualType FromPointeeType = FromPtrType->getPointeeType(),
1154 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001155
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001156 if (FromPointeeType->isRecordType() &&
1157 ToPointeeType->isRecordType()) {
1158 // We must have a derived-to-base conversion. Check an
1159 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001160 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1161 From->getExprLoc(),
1162 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001163 }
1164 }
Steve Naroff14108da2009-07-10 23:34:53 +00001165 if (const ObjCObjectPointerType *FromPtrType =
1166 FromType->getAsObjCObjectPointerType())
1167 if (const ObjCObjectPointerType *ToPtrType =
1168 ToType->getAsObjCObjectPointerType()) {
1169 // Objective-C++ conversions are always okay.
1170 // FIXME: We should have a different class of conversions for the
1171 // Objective-C++ implicit conversions.
1172 if (FromPtrType->isObjCIdType() || ToPtrType->isObjCIdType() ||
1173 FromPtrType->isObjCClassType() || ToPtrType->isObjCClassType())
1174 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001175
Steve Naroff14108da2009-07-10 23:34:53 +00001176 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001177 return false;
1178}
1179
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001180/// IsMemberPointerConversion - Determines whether the conversion of the
1181/// expression From, which has the (possibly adjusted) type FromType, can be
1182/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1183/// If so, returns true and places the converted type (that might differ from
1184/// ToType in its cv-qualifiers at some level) into ConvertedType.
1185bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1186 QualType ToType, QualType &ConvertedType)
1187{
1188 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1189 if (!ToTypePtr)
1190 return false;
1191
1192 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1193 if (From->isNullPointerConstant(Context)) {
1194 ConvertedType = ToType;
1195 return true;
1196 }
1197
1198 // Otherwise, both types have to be member pointers.
1199 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1200 if (!FromTypePtr)
1201 return false;
1202
1203 // A pointer to member of B can be converted to a pointer to member of D,
1204 // where D is derived from B (C++ 4.11p2).
1205 QualType FromClass(FromTypePtr->getClass(), 0);
1206 QualType ToClass(ToTypePtr->getClass(), 0);
1207 // FIXME: What happens when these are dependent? Is this function even called?
1208
1209 if (IsDerivedFrom(ToClass, FromClass)) {
1210 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1211 ToClass.getTypePtr());
1212 return true;
1213 }
1214
1215 return false;
1216}
1217
1218/// CheckMemberPointerConversion - Check the member pointer conversion from the
1219/// expression From to the type ToType. This routine checks for ambiguous or
1220/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1221/// for which IsMemberPointerConversion has already returned true. It returns
1222/// true and produces a diagnostic if there was an error, or returns false
1223/// otherwise.
1224bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1225 QualType FromType = From->getType();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001226 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1227 if (!FromPtrType)
1228 return false;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001229
Sebastian Redl21593ac2009-01-28 18:33:18 +00001230 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1231 assert(ToPtrType && "No member pointer cast has a target type "
1232 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001233
Sebastian Redl21593ac2009-01-28 18:33:18 +00001234 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1235 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001236
Sebastian Redl21593ac2009-01-28 18:33:18 +00001237 // FIXME: What about dependent types?
1238 assert(FromClass->isRecordType() && "Pointer into non-class.");
1239 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001240
Sebastian Redl21593ac2009-01-28 18:33:18 +00001241 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1242 /*DetectVirtual=*/true);
1243 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1244 assert(DerivationOkay &&
1245 "Should not have been called if derivation isn't OK.");
1246 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001247
Sebastian Redl21593ac2009-01-28 18:33:18 +00001248 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1249 getUnqualifiedType())) {
1250 // Derivation is ambiguous. Redo the check to find the exact paths.
1251 Paths.clear();
1252 Paths.setRecordingPaths(true);
1253 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1254 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1255 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001256
Sebastian Redl21593ac2009-01-28 18:33:18 +00001257 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1258 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1259 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1260 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001261 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001262
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001263 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001264 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1265 << FromClass << ToClass << QualType(VBase, 0)
1266 << From->getSourceRange();
1267 return true;
1268 }
1269
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001270 return false;
1271}
1272
Douglas Gregor98cd5992008-10-21 23:43:52 +00001273/// IsQualificationConversion - Determines whether the conversion from
1274/// an rvalue of type FromType to ToType is a qualification conversion
1275/// (C++ 4.4).
1276bool
1277Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1278{
1279 FromType = Context.getCanonicalType(FromType);
1280 ToType = Context.getCanonicalType(ToType);
1281
1282 // If FromType and ToType are the same type, this is not a
1283 // qualification conversion.
1284 if (FromType == ToType)
1285 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001286
Douglas Gregor98cd5992008-10-21 23:43:52 +00001287 // (C++ 4.4p4):
1288 // A conversion can add cv-qualifiers at levels other than the first
1289 // in multi-level pointers, subject to the following rules: [...]
1290 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001291 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001292 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001293 // Within each iteration of the loop, we check the qualifiers to
1294 // determine if this still looks like a qualification
1295 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001296 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001297 // until there are no more pointers or pointers-to-members left to
1298 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001299 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001300
1301 // -- for every j > 0, if const is in cv 1,j then const is in cv
1302 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001303 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001304 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001305
Douglas Gregor98cd5992008-10-21 23:43:52 +00001306 // -- if the cv 1,j and cv 2,j are different, then const is in
1307 // every cv for 0 < k < j.
1308 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001309 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001310 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001311
Douglas Gregor98cd5992008-10-21 23:43:52 +00001312 // Keep track of whether all prior cv-qualifiers in the "to" type
1313 // include const.
1314 PreviousToQualsIncludeConst
1315 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001316 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001317
1318 // We are left with FromType and ToType being the pointee types
1319 // after unwrapping the original FromType and ToType the same number
1320 // of types. If we unwrapped any pointers, and if FromType and
1321 // ToType have the same unqualified type (since we checked
1322 // qualifiers above), then this is a qualification conversion.
1323 return UnwrappedAnyPointer &&
1324 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1325}
1326
Douglas Gregor734d9862009-01-30 23:27:23 +00001327/// Determines whether there is a user-defined conversion sequence
1328/// (C++ [over.ics.user]) that converts expression From to the type
1329/// ToType. If such a conversion exists, User will contain the
1330/// user-defined conversion sequence that performs such a conversion
1331/// and this routine will return true. Otherwise, this routine returns
1332/// false and User is unspecified.
1333///
1334/// \param AllowConversionFunctions true if the conversion should
1335/// consider conversion functions at all. If false, only constructors
1336/// will be considered.
1337///
1338/// \param AllowExplicit true if the conversion should consider C++0x
1339/// "explicit" conversion functions as well as non-explicit conversion
1340/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001341///
1342/// \param ForceRValue true if the expression should be treated as an rvalue
1343/// for overload resolution.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001344bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001345 UserDefinedConversionSequence& User,
Douglas Gregor734d9862009-01-30 23:27:23 +00001346 bool AllowConversionFunctions,
Sebastian Redle2b68332009-04-12 17:16:29 +00001347 bool AllowExplicit, bool ForceRValue)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001348{
1349 OverloadCandidateSet CandidateSet;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001350 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1351 if (CXXRecordDecl *ToRecordDecl
1352 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1353 // C++ [over.match.ctor]p1:
1354 // When objects of class type are direct-initialized (8.5), or
1355 // copy-initialized from an expression of the same or a
1356 // derived class type (8.5), overload resolution selects the
1357 // constructor. [...] For copy-initialization, the candidate
1358 // functions are all the converting constructors (12.3.1) of
1359 // that class. The argument list is the expression-list within
1360 // the parentheses of the initializer.
1361 DeclarationName ConstructorName
1362 = Context.DeclarationNames.getCXXConstructorName(
1363 Context.getCanonicalType(ToType).getUnqualifiedType());
1364 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001365 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001366 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001367 Con != ConEnd; ++Con) {
1368 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1369 if (Constructor->isConvertingConstructor())
1370 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00001371 /*SuppressUserConversions=*/true, ForceRValue);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001372 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001373 }
1374 }
1375
Douglas Gregor734d9862009-01-30 23:27:23 +00001376 if (!AllowConversionFunctions) {
1377 // Don't allow any conversion functions to enter the overload set.
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001378 } else if (const RecordType *FromRecordType
1379 = From->getType()->getAsRecordType()) {
1380 if (CXXRecordDecl *FromRecordDecl
1381 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1382 // Add all of the conversion functions as candidates.
1383 // FIXME: Look for conversions in base classes!
1384 OverloadedFunctionDecl *Conversions
1385 = FromRecordDecl->getConversionFunctions();
1386 for (OverloadedFunctionDecl::function_iterator Func
1387 = Conversions->function_begin();
1388 Func != Conversions->function_end(); ++Func) {
1389 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1390 if (AllowExplicit || !Conv->isExplicit())
1391 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1392 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001393 }
1394 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001395
1396 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001397 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001398 case OR_Success:
1399 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001400 if (CXXConstructorDecl *Constructor
1401 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1402 // C++ [over.ics.user]p1:
1403 // If the user-defined conversion is specified by a
1404 // constructor (12.3.1), the initial standard conversion
1405 // sequence converts the source type to the type required by
1406 // the argument of the constructor.
1407 //
1408 // FIXME: What about ellipsis conversions?
1409 QualType ThisType = Constructor->getThisType(Context);
1410 User.Before = Best->Conversions[0].Standard;
1411 User.ConversionFunction = Constructor;
1412 User.After.setAsIdentityConversion();
1413 User.After.FromTypePtr
1414 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1415 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1416 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001417 } else if (CXXConversionDecl *Conversion
1418 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1419 // C++ [over.ics.user]p1:
1420 //
1421 // [...] If the user-defined conversion is specified by a
1422 // conversion function (12.3.2), the initial standard
1423 // conversion sequence converts the source type to the
1424 // implicit object parameter of the conversion function.
1425 User.Before = Best->Conversions[0].Standard;
1426 User.ConversionFunction = Conversion;
1427
1428 // C++ [over.ics.user]p2:
1429 // The second standard conversion sequence converts the
1430 // result of the user-defined conversion to the target type
1431 // for the sequence. Since an implicit conversion sequence
1432 // is an initialization, the special rules for
1433 // initialization by user-defined conversion apply when
1434 // selecting the best user-defined conversion for a
1435 // user-defined conversion sequence (see 13.3.3 and
1436 // 13.3.3.1).
1437 User.After = Best->FinalConversion;
1438 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001439 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001440 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001441 return false;
1442 }
1443
1444 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001445 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001446 // No conversion here! We're done.
1447 return false;
1448
1449 case OR_Ambiguous:
1450 // FIXME: See C++ [over.best.ics]p10 for the handling of
1451 // ambiguous conversion sequences.
1452 return false;
1453 }
1454
1455 return false;
1456}
1457
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001458/// CompareImplicitConversionSequences - Compare two implicit
1459/// conversion sequences to determine whether one is better than the
1460/// other or if they are indistinguishable (C++ 13.3.3.2).
1461ImplicitConversionSequence::CompareKind
1462Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1463 const ImplicitConversionSequence& ICS2)
1464{
1465 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1466 // conversion sequences (as defined in 13.3.3.1)
1467 // -- a standard conversion sequence (13.3.3.1.1) is a better
1468 // conversion sequence than a user-defined conversion sequence or
1469 // an ellipsis conversion sequence, and
1470 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1471 // conversion sequence than an ellipsis conversion sequence
1472 // (13.3.3.1.3).
1473 //
1474 if (ICS1.ConversionKind < ICS2.ConversionKind)
1475 return ImplicitConversionSequence::Better;
1476 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1477 return ImplicitConversionSequence::Worse;
1478
1479 // Two implicit conversion sequences of the same form are
1480 // indistinguishable conversion sequences unless one of the
1481 // following rules apply: (C++ 13.3.3.2p3):
1482 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1483 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1484 else if (ICS1.ConversionKind ==
1485 ImplicitConversionSequence::UserDefinedConversion) {
1486 // User-defined conversion sequence U1 is a better conversion
1487 // sequence than another user-defined conversion sequence U2 if
1488 // they contain the same user-defined conversion function or
1489 // constructor and if the second standard conversion sequence of
1490 // U1 is better than the second standard conversion sequence of
1491 // U2 (C++ 13.3.3.2p3).
1492 if (ICS1.UserDefined.ConversionFunction ==
1493 ICS2.UserDefined.ConversionFunction)
1494 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1495 ICS2.UserDefined.After);
1496 }
1497
1498 return ImplicitConversionSequence::Indistinguishable;
1499}
1500
1501/// CompareStandardConversionSequences - Compare two standard
1502/// conversion sequences to determine whether one is better than the
1503/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1504ImplicitConversionSequence::CompareKind
1505Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1506 const StandardConversionSequence& SCS2)
1507{
1508 // Standard conversion sequence S1 is a better conversion sequence
1509 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1510
1511 // -- S1 is a proper subsequence of S2 (comparing the conversion
1512 // sequences in the canonical form defined by 13.3.3.1.1,
1513 // excluding any Lvalue Transformation; the identity conversion
1514 // sequence is considered to be a subsequence of any
1515 // non-identity conversion sequence) or, if not that,
1516 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1517 // Neither is a proper subsequence of the other. Do nothing.
1518 ;
1519 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1520 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1521 (SCS1.Second == ICK_Identity &&
1522 SCS1.Third == ICK_Identity))
1523 // SCS1 is a proper subsequence of SCS2.
1524 return ImplicitConversionSequence::Better;
1525 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1526 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1527 (SCS2.Second == ICK_Identity &&
1528 SCS2.Third == ICK_Identity))
1529 // SCS2 is a proper subsequence of SCS1.
1530 return ImplicitConversionSequence::Worse;
1531
1532 // -- the rank of S1 is better than the rank of S2 (by the rules
1533 // defined below), or, if not that,
1534 ImplicitConversionRank Rank1 = SCS1.getRank();
1535 ImplicitConversionRank Rank2 = SCS2.getRank();
1536 if (Rank1 < Rank2)
1537 return ImplicitConversionSequence::Better;
1538 else if (Rank2 < Rank1)
1539 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001540
Douglas Gregor57373262008-10-22 14:17:15 +00001541 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1542 // are indistinguishable unless one of the following rules
1543 // applies:
1544
1545 // A conversion that is not a conversion of a pointer, or
1546 // pointer to member, to bool is better than another conversion
1547 // that is such a conversion.
1548 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1549 return SCS2.isPointerConversionToBool()
1550 ? ImplicitConversionSequence::Better
1551 : ImplicitConversionSequence::Worse;
1552
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001553 // C++ [over.ics.rank]p4b2:
1554 //
1555 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001556 // conversion of B* to A* is better than conversion of B* to
1557 // void*, and conversion of A* to void* is better than conversion
1558 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001559 bool SCS1ConvertsToVoid
1560 = SCS1.isPointerConversionToVoidPointer(Context);
1561 bool SCS2ConvertsToVoid
1562 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001563 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1564 // Exactly one of the conversion sequences is a conversion to
1565 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001566 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1567 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001568 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1569 // Neither conversion sequence converts to a void pointer; compare
1570 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001571 if (ImplicitConversionSequence::CompareKind DerivedCK
1572 = CompareDerivedToBaseConversions(SCS1, SCS2))
1573 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001574 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1575 // Both conversion sequences are conversions to void
1576 // pointers. Compare the source types to determine if there's an
1577 // inheritance relationship in their sources.
1578 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1579 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1580
1581 // Adjust the types we're converting from via the array-to-pointer
1582 // conversion, if we need to.
1583 if (SCS1.First == ICK_Array_To_Pointer)
1584 FromType1 = Context.getArrayDecayedType(FromType1);
1585 if (SCS2.First == ICK_Array_To_Pointer)
1586 FromType2 = Context.getArrayDecayedType(FromType2);
1587
1588 QualType FromPointee1
1589 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1590 QualType FromPointee2
1591 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1592
1593 if (IsDerivedFrom(FromPointee2, FromPointee1))
1594 return ImplicitConversionSequence::Better;
1595 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1596 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001597
1598 // Objective-C++: If one interface is more specific than the
1599 // other, it is the better one.
1600 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1601 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1602 if (FromIface1 && FromIface1) {
1603 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1604 return ImplicitConversionSequence::Better;
1605 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1606 return ImplicitConversionSequence::Worse;
1607 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001608 }
Douglas Gregor57373262008-10-22 14:17:15 +00001609
1610 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1611 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001612 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001613 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001614 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001615
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001616 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001617 // C++0x [over.ics.rank]p3b4:
1618 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1619 // implicit object parameter of a non-static member function declared
1620 // without a ref-qualifier, and S1 binds an rvalue reference to an
1621 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001622 // FIXME: We don't know if we're dealing with the implicit object parameter,
1623 // or if the member function in this case has a ref qualifier.
1624 // (Of course, we don't have ref qualifiers yet.)
1625 if (SCS1.RRefBinding != SCS2.RRefBinding)
1626 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1627 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001628
1629 // C++ [over.ics.rank]p3b4:
1630 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1631 // which the references refer are the same type except for
1632 // top-level cv-qualifiers, and the type to which the reference
1633 // initialized by S2 refers is more cv-qualified than the type
1634 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001635 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1636 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001637 T1 = Context.getCanonicalType(T1);
1638 T2 = Context.getCanonicalType(T2);
1639 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1640 if (T2.isMoreQualifiedThan(T1))
1641 return ImplicitConversionSequence::Better;
1642 else if (T1.isMoreQualifiedThan(T2))
1643 return ImplicitConversionSequence::Worse;
1644 }
1645 }
Douglas Gregor57373262008-10-22 14:17:15 +00001646
1647 return ImplicitConversionSequence::Indistinguishable;
1648}
1649
1650/// CompareQualificationConversions - Compares two standard conversion
1651/// sequences to determine whether they can be ranked based on their
1652/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1653ImplicitConversionSequence::CompareKind
1654Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1655 const StandardConversionSequence& SCS2)
1656{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001657 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001658 // -- S1 and S2 differ only in their qualification conversion and
1659 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1660 // cv-qualification signature of type T1 is a proper subset of
1661 // the cv-qualification signature of type T2, and S1 is not the
1662 // deprecated string literal array-to-pointer conversion (4.2).
1663 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1664 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1665 return ImplicitConversionSequence::Indistinguishable;
1666
1667 // FIXME: the example in the standard doesn't use a qualification
1668 // conversion (!)
1669 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1670 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1671 T1 = Context.getCanonicalType(T1);
1672 T2 = Context.getCanonicalType(T2);
1673
1674 // If the types are the same, we won't learn anything by unwrapped
1675 // them.
1676 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1677 return ImplicitConversionSequence::Indistinguishable;
1678
1679 ImplicitConversionSequence::CompareKind Result
1680 = ImplicitConversionSequence::Indistinguishable;
1681 while (UnwrapSimilarPointerTypes(T1, T2)) {
1682 // Within each iteration of the loop, we check the qualifiers to
1683 // determine if this still looks like a qualification
1684 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001685 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001686 // until there are no more pointers or pointers-to-members left
1687 // to unwrap. This essentially mimics what
1688 // IsQualificationConversion does, but here we're checking for a
1689 // strict subset of qualifiers.
1690 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1691 // The qualifiers are the same, so this doesn't tell us anything
1692 // about how the sequences rank.
1693 ;
1694 else if (T2.isMoreQualifiedThan(T1)) {
1695 // T1 has fewer qualifiers, so it could be the better sequence.
1696 if (Result == ImplicitConversionSequence::Worse)
1697 // Neither has qualifiers that are a subset of the other's
1698 // qualifiers.
1699 return ImplicitConversionSequence::Indistinguishable;
1700
1701 Result = ImplicitConversionSequence::Better;
1702 } else if (T1.isMoreQualifiedThan(T2)) {
1703 // T2 has fewer qualifiers, so it could be the better sequence.
1704 if (Result == ImplicitConversionSequence::Better)
1705 // Neither has qualifiers that are a subset of the other's
1706 // qualifiers.
1707 return ImplicitConversionSequence::Indistinguishable;
1708
1709 Result = ImplicitConversionSequence::Worse;
1710 } else {
1711 // Qualifiers are disjoint.
1712 return ImplicitConversionSequence::Indistinguishable;
1713 }
1714
1715 // If the types after this point are equivalent, we're done.
1716 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1717 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001718 }
1719
Douglas Gregor57373262008-10-22 14:17:15 +00001720 // Check that the winning standard conversion sequence isn't using
1721 // the deprecated string literal array to pointer conversion.
1722 switch (Result) {
1723 case ImplicitConversionSequence::Better:
1724 if (SCS1.Deprecated)
1725 Result = ImplicitConversionSequence::Indistinguishable;
1726 break;
1727
1728 case ImplicitConversionSequence::Indistinguishable:
1729 break;
1730
1731 case ImplicitConversionSequence::Worse:
1732 if (SCS2.Deprecated)
1733 Result = ImplicitConversionSequence::Indistinguishable;
1734 break;
1735 }
1736
1737 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001738}
1739
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001740/// CompareDerivedToBaseConversions - Compares two standard conversion
1741/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001742/// various kinds of derived-to-base conversions (C++
1743/// [over.ics.rank]p4b3). As part of these checks, we also look at
1744/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001745ImplicitConversionSequence::CompareKind
1746Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1747 const StandardConversionSequence& SCS2) {
1748 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1749 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1750 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1751 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1752
1753 // Adjust the types we're converting from via the array-to-pointer
1754 // conversion, if we need to.
1755 if (SCS1.First == ICK_Array_To_Pointer)
1756 FromType1 = Context.getArrayDecayedType(FromType1);
1757 if (SCS2.First == ICK_Array_To_Pointer)
1758 FromType2 = Context.getArrayDecayedType(FromType2);
1759
1760 // Canonicalize all of the types.
1761 FromType1 = Context.getCanonicalType(FromType1);
1762 ToType1 = Context.getCanonicalType(ToType1);
1763 FromType2 = Context.getCanonicalType(FromType2);
1764 ToType2 = Context.getCanonicalType(ToType2);
1765
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001766 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001767 //
1768 // If class B is derived directly or indirectly from class A and
1769 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001770 //
1771 // For Objective-C, we let A, B, and C also be Objective-C
1772 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001773
1774 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001775 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001776 SCS2.Second == ICK_Pointer_Conversion &&
1777 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1778 FromType1->isPointerType() && FromType2->isPointerType() &&
1779 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001780 QualType FromPointee1
1781 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1782 QualType ToPointee1
1783 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1784 QualType FromPointee2
1785 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1786 QualType ToPointee2
1787 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001788
1789 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1790 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1791 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1792 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1793
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001794 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001795 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1796 if (IsDerivedFrom(ToPointee1, ToPointee2))
1797 return ImplicitConversionSequence::Better;
1798 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1799 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001800
1801 if (ToIface1 && ToIface2) {
1802 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1803 return ImplicitConversionSequence::Better;
1804 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1805 return ImplicitConversionSequence::Worse;
1806 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001807 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001808
1809 // -- conversion of B* to A* is better than conversion of C* to A*,
1810 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1811 if (IsDerivedFrom(FromPointee2, FromPointee1))
1812 return ImplicitConversionSequence::Better;
1813 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1814 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001815
1816 if (FromIface1 && FromIface2) {
1817 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1818 return ImplicitConversionSequence::Better;
1819 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1820 return ImplicitConversionSequence::Worse;
1821 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001822 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001823 }
1824
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001825 // Compare based on reference bindings.
1826 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1827 SCS1.Second == ICK_Derived_To_Base) {
1828 // -- binding of an expression of type C to a reference of type
1829 // B& is better than binding an expression of type C to a
1830 // reference of type A&,
1831 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1832 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1833 if (IsDerivedFrom(ToType1, ToType2))
1834 return ImplicitConversionSequence::Better;
1835 else if (IsDerivedFrom(ToType2, ToType1))
1836 return ImplicitConversionSequence::Worse;
1837 }
1838
Douglas Gregor225c41e2008-11-03 19:09:14 +00001839 // -- binding of an expression of type B to a reference of type
1840 // A& is better than binding an expression of type C to a
1841 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001842 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1843 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1844 if (IsDerivedFrom(FromType2, FromType1))
1845 return ImplicitConversionSequence::Better;
1846 else if (IsDerivedFrom(FromType1, FromType2))
1847 return ImplicitConversionSequence::Worse;
1848 }
1849 }
1850
1851
1852 // FIXME: conversion of A::* to B::* is better than conversion of
1853 // A::* to C::*,
1854
1855 // FIXME: conversion of B::* to C::* is better than conversion of
1856 // A::* to C::*, and
1857
Douglas Gregor225c41e2008-11-03 19:09:14 +00001858 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1859 SCS1.Second == ICK_Derived_To_Base) {
1860 // -- conversion of C to B is better than conversion of C to A,
1861 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1862 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1863 if (IsDerivedFrom(ToType1, ToType2))
1864 return ImplicitConversionSequence::Better;
1865 else if (IsDerivedFrom(ToType2, ToType1))
1866 return ImplicitConversionSequence::Worse;
1867 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001868
Douglas Gregor225c41e2008-11-03 19:09:14 +00001869 // -- conversion of B to A is better than conversion of C to A.
1870 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1871 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1872 if (IsDerivedFrom(FromType2, FromType1))
1873 return ImplicitConversionSequence::Better;
1874 else if (IsDerivedFrom(FromType1, FromType2))
1875 return ImplicitConversionSequence::Worse;
1876 }
1877 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001878
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001879 return ImplicitConversionSequence::Indistinguishable;
1880}
1881
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001882/// TryCopyInitialization - Try to copy-initialize a value of type
1883/// ToType from the expression From. Return the implicit conversion
1884/// sequence required to pass this argument, which may be a bad
1885/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001886/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00001887/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1888/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001889ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001890Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001891 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001892 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001893 ImplicitConversionSequence ICS;
Sebastian Redle2b68332009-04-12 17:16:29 +00001894 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1895 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001896 return ICS;
1897 } else {
Sebastian Redle2b68332009-04-12 17:16:29 +00001898 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1899 ForceRValue);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001900 }
1901}
1902
Sebastian Redle2b68332009-04-12 17:16:29 +00001903/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1904/// the expression @p From. Returns true (and emits a diagnostic) if there was
1905/// an error, returns false if the initialization succeeded. Elidable should
1906/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1907/// differently in C++0x for this case.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001908bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001909 const char* Flavor, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001910 if (!getLangOptions().CPlusPlus) {
1911 // In C, argument passing is the same as performing an assignment.
1912 QualType FromType = From->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00001913
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001914 AssignConvertType ConvTy =
1915 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00001916 if (ConvTy != Compatible &&
1917 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1918 ConvTy = Compatible;
1919
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001920 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1921 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001922 }
Sebastian Redle2b68332009-04-12 17:16:29 +00001923
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001924 if (ToType->isReferenceType())
1925 return CheckReferenceInit(From, ToType);
1926
Sebastian Redle2b68332009-04-12 17:16:29 +00001927 if (!PerformImplicitConversion(From, ToType, Flavor,
1928 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001929 return false;
Sebastian Redle2b68332009-04-12 17:16:29 +00001930
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001931 return Diag(From->getSourceRange().getBegin(),
1932 diag::err_typecheck_convert_incompatible)
1933 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001934}
1935
Douglas Gregor96176b32008-11-18 23:14:02 +00001936/// TryObjectArgumentInitialization - Try to initialize the object
1937/// parameter of the given member function (@c Method) from the
1938/// expression @p From.
1939ImplicitConversionSequence
1940Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1941 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1942 unsigned MethodQuals = Method->getTypeQualifiers();
1943 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1944
1945 // Set up the conversion sequence as a "bad" conversion, to allow us
1946 // to exit early.
1947 ImplicitConversionSequence ICS;
1948 ICS.Standard.setAsIdentityConversion();
1949 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1950
1951 // We need to have an object of class type.
1952 QualType FromType = From->getType();
Anders Carlssona552f7c2009-05-01 18:34:30 +00001953 if (const PointerType *PT = FromType->getAsPointerType())
1954 FromType = PT->getPointeeType();
1955
1956 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00001957
1958 // The implicit object parmeter is has the type "reference to cv X",
1959 // where X is the class of which the function is a member
1960 // (C++ [over.match.funcs]p4). However, when finding an implicit
1961 // conversion sequence for the argument, we are not allowed to
1962 // create temporaries or perform user-defined conversions
1963 // (C++ [over.match.funcs]p5). We perform a simplified version of
1964 // reference binding here, that allows class rvalues to bind to
1965 // non-constant references.
1966
1967 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1968 // with the implicit object parameter (C++ [over.match.funcs]p5).
1969 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1970 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1971 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1972 return ICS;
1973
1974 // Check that we have either the same type or a derived type. It
1975 // affects the conversion rank.
1976 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1977 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1978 ICS.Standard.Second = ICK_Identity;
1979 else if (IsDerivedFrom(FromType, ClassType))
1980 ICS.Standard.Second = ICK_Derived_To_Base;
1981 else
1982 return ICS;
1983
1984 // Success. Mark this as a reference binding.
1985 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1986 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1987 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1988 ICS.Standard.ReferenceBinding = true;
1989 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00001990 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001991 return ICS;
1992}
1993
1994/// PerformObjectArgumentInitialization - Perform initialization of
1995/// the implicit object parameter for the given Method with the given
1996/// expression.
1997bool
1998Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00001999 QualType FromRecordType, DestType;
2000 QualType ImplicitParamRecordType =
2001 Method->getThisType(Context)->getAsPointerType()->getPointeeType();
2002
2003 if (const PointerType *PT = From->getType()->getAsPointerType()) {
2004 FromRecordType = PT->getPointeeType();
2005 DestType = Method->getThisType(Context);
2006 } else {
2007 FromRecordType = From->getType();
2008 DestType = ImplicitParamRecordType;
2009 }
2010
Douglas Gregor96176b32008-11-18 23:14:02 +00002011 ImplicitConversionSequence ICS
2012 = TryObjectArgumentInitialization(From, Method);
2013 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2014 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002015 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002016 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2017
Douglas Gregor96176b32008-11-18 23:14:02 +00002018 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002019 CheckDerivedToBaseConversion(FromRecordType,
2020 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002021 From->getSourceRange().getBegin(),
2022 From->getSourceRange()))
2023 return true;
2024
Anders Carlssona552f7c2009-05-01 18:34:30 +00002025 ImpCastExprToType(From, DestType, /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002026 return false;
2027}
2028
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002029/// TryContextuallyConvertToBool - Attempt to contextually convert the
2030/// expression From to bool (C++0x [conv]p3).
2031ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2032 return TryImplicitConversion(From, Context.BoolTy, false, true);
2033}
2034
2035/// PerformContextuallyConvertToBool - Perform a contextual conversion
2036/// of the expression From to bool (C++0x [conv]p3).
2037bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2038 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2039 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2040 return false;
2041
2042 return Diag(From->getSourceRange().getBegin(),
2043 diag::err_typecheck_bool_condition)
2044 << From->getType() << From->getSourceRange();
2045}
2046
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002047/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002048/// candidate functions, using the given function call arguments. If
2049/// @p SuppressUserConversions, then don't allow user-defined
2050/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002051/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2052/// hacky way to implement the overloading rules for elidable copy
2053/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002054void
2055Sema::AddOverloadCandidate(FunctionDecl *Function,
2056 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002057 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002058 bool SuppressUserConversions,
2059 bool ForceRValue)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002060{
Douglas Gregor72564e72009-02-26 23:50:07 +00002061 const FunctionProtoType* Proto
2062 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002063 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002064 assert(!isa<CXXConversionDecl>(Function) &&
2065 "Use AddConversionCandidate for conversion functions");
Douglas Gregore53060f2009-06-25 22:08:12 +00002066 assert(!Function->getDescribedFunctionTemplate() &&
2067 "Use AddTemplateOverloadCandidate for function templates");
2068
Douglas Gregor88a35142008-12-22 05:46:06 +00002069 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002070 if (!isa<CXXConstructorDecl>(Method)) {
2071 // If we get here, it's because we're calling a member function
2072 // that is named without a member access expression (e.g.,
2073 // "this->f") that was either written explicitly or created
2074 // implicitly. This can happen with a qualified call to a member
2075 // function, e.g., X::f(). We use a NULL object as the implied
2076 // object argument (C++ [over.call.func]p3).
2077 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2078 SuppressUserConversions, ForceRValue);
2079 return;
2080 }
2081 // We treat a constructor like a non-member function, since its object
2082 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002083 }
2084
2085
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002086 // Add this candidate
2087 CandidateSet.push_back(OverloadCandidate());
2088 OverloadCandidate& Candidate = CandidateSet.back();
2089 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002090 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002091 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002092 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002093
2094 unsigned NumArgsInProto = Proto->getNumArgs();
2095
2096 // (C++ 13.3.2p2): A candidate function having fewer than m
2097 // parameters is viable only if it has an ellipsis in its parameter
2098 // list (8.3.5).
2099 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2100 Candidate.Viable = false;
2101 return;
2102 }
2103
2104 // (C++ 13.3.2p2): A candidate function having more than m parameters
2105 // is viable only if the (m+1)st parameter has a default argument
2106 // (8.3.6). For the purposes of overload resolution, the
2107 // parameter list is truncated on the right, so that there are
2108 // exactly m parameters.
2109 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2110 if (NumArgs < MinRequiredArgs) {
2111 // Not enough arguments.
2112 Candidate.Viable = false;
2113 return;
2114 }
2115
2116 // Determine the implicit conversion sequences for each of the
2117 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002118 Candidate.Conversions.resize(NumArgs);
2119 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2120 if (ArgIdx < NumArgsInProto) {
2121 // (C++ 13.3.2p3): for F to be a viable function, there shall
2122 // exist for each argument an implicit conversion sequence
2123 // (13.3.3.1) that converts that argument to the corresponding
2124 // parameter of F.
2125 QualType ParamType = Proto->getArgType(ArgIdx);
2126 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00002127 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redle2b68332009-04-12 17:16:29 +00002128 SuppressUserConversions, ForceRValue);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002129 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002130 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002131 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002132 break;
2133 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002134 } else {
2135 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2136 // argument for which there is no corresponding parameter is
2137 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2138 Candidate.Conversions[ArgIdx].ConversionKind
2139 = ImplicitConversionSequence::EllipsisConversion;
2140 }
2141 }
2142}
2143
Douglas Gregor063daf62009-03-13 18:40:31 +00002144/// \brief Add all of the function declarations in the given function set to
2145/// the overload canddiate set.
2146void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2147 Expr **Args, unsigned NumArgs,
2148 OverloadCandidateSet& CandidateSet,
2149 bool SuppressUserConversions) {
2150 for (FunctionSet::const_iterator F = Functions.begin(),
2151 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002152 F != FEnd; ++F) {
2153 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2154 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2155 SuppressUserConversions);
2156 else
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002157 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2158 /*FIXME: explicit args */false, 0, 0,
2159 Args, NumArgs, CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002160 SuppressUserConversions);
2161 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002162}
2163
Douglas Gregor96176b32008-11-18 23:14:02 +00002164/// AddMethodCandidate - Adds the given C++ member function to the set
2165/// of candidate functions, using the given function call arguments
2166/// and the object argument (@c Object). For example, in a call
2167/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2168/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2169/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002170/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2171/// a slightly hacky way to implement the overloading rules for elidable copy
2172/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor96176b32008-11-18 23:14:02 +00002173void
2174Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2175 Expr **Args, unsigned NumArgs,
2176 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002177 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor96176b32008-11-18 23:14:02 +00002178{
Douglas Gregor72564e72009-02-26 23:50:07 +00002179 const FunctionProtoType* Proto
2180 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002181 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002182 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor96176b32008-11-18 23:14:02 +00002183 "Use AddConversionCandidate for conversion functions");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002184 assert(!isa<CXXConstructorDecl>(Method) &&
2185 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002186
2187 // Add this candidate
2188 CandidateSet.push_back(OverloadCandidate());
2189 OverloadCandidate& Candidate = CandidateSet.back();
2190 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002191 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002192 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002193
2194 unsigned NumArgsInProto = Proto->getNumArgs();
2195
2196 // (C++ 13.3.2p2): A candidate function having fewer than m
2197 // parameters is viable only if it has an ellipsis in its parameter
2198 // list (8.3.5).
2199 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2200 Candidate.Viable = false;
2201 return;
2202 }
2203
2204 // (C++ 13.3.2p2): A candidate function having more than m parameters
2205 // is viable only if the (m+1)st parameter has a default argument
2206 // (8.3.6). For the purposes of overload resolution, the
2207 // parameter list is truncated on the right, so that there are
2208 // exactly m parameters.
2209 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2210 if (NumArgs < MinRequiredArgs) {
2211 // Not enough arguments.
2212 Candidate.Viable = false;
2213 return;
2214 }
2215
2216 Candidate.Viable = true;
2217 Candidate.Conversions.resize(NumArgs + 1);
2218
Douglas Gregor88a35142008-12-22 05:46:06 +00002219 if (Method->isStatic() || !Object)
2220 // The implicit object argument is ignored.
2221 Candidate.IgnoreObjectArgument = true;
2222 else {
2223 // Determine the implicit conversion sequence for the object
2224 // parameter.
2225 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2226 if (Candidate.Conversions[0].ConversionKind
2227 == ImplicitConversionSequence::BadConversion) {
2228 Candidate.Viable = false;
2229 return;
2230 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002231 }
2232
2233 // Determine the implicit conversion sequences for each of the
2234 // arguments.
2235 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2236 if (ArgIdx < NumArgsInProto) {
2237 // (C++ 13.3.2p3): for F to be a viable function, there shall
2238 // exist for each argument an implicit conversion sequence
2239 // (13.3.3.1) that converts that argument to the corresponding
2240 // parameter of F.
2241 QualType ParamType = Proto->getArgType(ArgIdx);
2242 Candidate.Conversions[ArgIdx + 1]
2243 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redle2b68332009-04-12 17:16:29 +00002244 SuppressUserConversions, ForceRValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00002245 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2246 == ImplicitConversionSequence::BadConversion) {
2247 Candidate.Viable = false;
2248 break;
2249 }
2250 } else {
2251 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2252 // argument for which there is no corresponding parameter is
2253 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2254 Candidate.Conversions[ArgIdx + 1].ConversionKind
2255 = ImplicitConversionSequence::EllipsisConversion;
2256 }
2257 }
2258}
2259
Douglas Gregore53060f2009-06-25 22:08:12 +00002260/// \brief Add a C++ function template as a candidate in the candidate set,
2261/// using template argument deduction to produce an appropriate function
2262/// template specialization.
2263void
2264Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002265 bool HasExplicitTemplateArgs,
2266 const TemplateArgument *ExplicitTemplateArgs,
2267 unsigned NumExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002268 Expr **Args, unsigned NumArgs,
2269 OverloadCandidateSet& CandidateSet,
2270 bool SuppressUserConversions,
2271 bool ForceRValue) {
2272 // C++ [over.match.funcs]p7:
2273 // In each case where a candidate is a function template, candidate
2274 // function template specializations are generated using template argument
2275 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2276 // candidate functions in the usual way.113) A given name can refer to one
2277 // or more function templates and also to a set of overloaded non-template
2278 // functions. In such a case, the candidate functions generated from each
2279 // function template are combined with the set of non-template candidate
2280 // functions.
2281 TemplateDeductionInfo Info(Context);
2282 FunctionDecl *Specialization = 0;
2283 if (TemplateDeductionResult Result
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002284 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2285 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2286 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002287 // FIXME: Record what happened with template argument deduction, so
2288 // that we can give the user a beautiful diagnostic.
2289 (void)Result;
2290 return;
2291 }
2292
2293 // Add the function template specialization produced by template argument
2294 // deduction as a candidate.
2295 assert(Specialization && "Missing function template specialization?");
2296 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2297 SuppressUserConversions, ForceRValue);
2298}
2299
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002300/// AddConversionCandidate - Add a C++ conversion function as a
2301/// candidate in the candidate set (C++ [over.match.conv],
2302/// C++ [over.match.copy]). From is the expression we're converting from,
2303/// and ToType is the type that we're eventually trying to convert to
2304/// (which may or may not be the same type as the type that the
2305/// conversion function produces).
2306void
2307Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2308 Expr *From, QualType ToType,
2309 OverloadCandidateSet& CandidateSet) {
2310 // Add this candidate
2311 CandidateSet.push_back(OverloadCandidate());
2312 OverloadCandidate& Candidate = CandidateSet.back();
2313 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002314 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002315 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002316 Candidate.FinalConversion.setAsIdentityConversion();
2317 Candidate.FinalConversion.FromTypePtr
2318 = Conversion->getConversionType().getAsOpaquePtr();
2319 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2320
Douglas Gregor96176b32008-11-18 23:14:02 +00002321 // Determine the implicit conversion sequence for the implicit
2322 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002323 Candidate.Viable = true;
2324 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002325 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002326
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002327 if (Candidate.Conversions[0].ConversionKind
2328 == ImplicitConversionSequence::BadConversion) {
2329 Candidate.Viable = false;
2330 return;
2331 }
2332
2333 // To determine what the conversion from the result of calling the
2334 // conversion function to the type we're eventually trying to
2335 // convert to (ToType), we need to synthesize a call to the
2336 // conversion function and attempt copy initialization from it. This
2337 // makes sure that we get the right semantics with respect to
2338 // lvalues/rvalues and the type. Fortunately, we can allocate this
2339 // call on the stack and we don't need its arguments to be
2340 // well-formed.
2341 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2342 SourceLocation());
2343 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002344 &ConversionRef, false);
Ted Kremenek668bf912009-02-09 20:51:47 +00002345
2346 // Note that it is safe to allocate CallExpr on the stack here because
2347 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2348 // allocator).
2349 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002350 Conversion->getConversionType().getNonReferenceType(),
2351 SourceLocation());
2352 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2353 switch (ICS.ConversionKind) {
2354 case ImplicitConversionSequence::StandardConversion:
2355 Candidate.FinalConversion = ICS.Standard;
2356 break;
2357
2358 case ImplicitConversionSequence::BadConversion:
2359 Candidate.Viable = false;
2360 break;
2361
2362 default:
2363 assert(false &&
2364 "Can only end up with a standard conversion sequence or failure");
2365 }
2366}
2367
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002368/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2369/// converts the given @c Object to a function pointer via the
2370/// conversion function @c Conversion, and then attempts to call it
2371/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2372/// the type of function that we'll eventually be calling.
2373void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor72564e72009-02-26 23:50:07 +00002374 const FunctionProtoType *Proto,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002375 Expr *Object, Expr **Args, unsigned NumArgs,
2376 OverloadCandidateSet& CandidateSet) {
2377 CandidateSet.push_back(OverloadCandidate());
2378 OverloadCandidate& Candidate = CandidateSet.back();
2379 Candidate.Function = 0;
2380 Candidate.Surrogate = Conversion;
2381 Candidate.Viable = true;
2382 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002383 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002384 Candidate.Conversions.resize(NumArgs + 1);
2385
2386 // Determine the implicit conversion sequence for the implicit
2387 // object parameter.
2388 ImplicitConversionSequence ObjectInit
2389 = TryObjectArgumentInitialization(Object, Conversion);
2390 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2391 Candidate.Viable = false;
2392 return;
2393 }
2394
2395 // The first conversion is actually a user-defined conversion whose
2396 // first conversion is ObjectInit's standard conversion (which is
2397 // effectively a reference binding). Record it as such.
2398 Candidate.Conversions[0].ConversionKind
2399 = ImplicitConversionSequence::UserDefinedConversion;
2400 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2401 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2402 Candidate.Conversions[0].UserDefined.After
2403 = Candidate.Conversions[0].UserDefined.Before;
2404 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2405
2406 // Find the
2407 unsigned NumArgsInProto = Proto->getNumArgs();
2408
2409 // (C++ 13.3.2p2): A candidate function having fewer than m
2410 // parameters is viable only if it has an ellipsis in its parameter
2411 // list (8.3.5).
2412 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2413 Candidate.Viable = false;
2414 return;
2415 }
2416
2417 // Function types don't have any default arguments, so just check if
2418 // we have enough arguments.
2419 if (NumArgs < NumArgsInProto) {
2420 // Not enough arguments.
2421 Candidate.Viable = false;
2422 return;
2423 }
2424
2425 // Determine the implicit conversion sequences for each of the
2426 // arguments.
2427 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2428 if (ArgIdx < NumArgsInProto) {
2429 // (C++ 13.3.2p3): for F to be a viable function, there shall
2430 // exist for each argument an implicit conversion sequence
2431 // (13.3.3.1) that converts that argument to the corresponding
2432 // parameter of F.
2433 QualType ParamType = Proto->getArgType(ArgIdx);
2434 Candidate.Conversions[ArgIdx + 1]
2435 = TryCopyInitialization(Args[ArgIdx], ParamType,
2436 /*SuppressUserConversions=*/false);
2437 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2438 == ImplicitConversionSequence::BadConversion) {
2439 Candidate.Viable = false;
2440 break;
2441 }
2442 } else {
2443 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2444 // argument for which there is no corresponding parameter is
2445 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2446 Candidate.Conversions[ArgIdx + 1].ConversionKind
2447 = ImplicitConversionSequence::EllipsisConversion;
2448 }
2449 }
2450}
2451
Mike Stump390b4cc2009-05-16 07:39:55 +00002452// FIXME: This will eventually be removed, once we've migrated all of the
2453// operator overloading logic over to the scheme used by binary operators, which
2454// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002455void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002456 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002457 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002458 OverloadCandidateSet& CandidateSet,
2459 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002460
2461 FunctionSet Functions;
2462
2463 QualType T1 = Args[0]->getType();
2464 QualType T2;
2465 if (NumArgs > 1)
2466 T2 = Args[1]->getType();
2467
2468 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002469 if (S)
2470 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002471 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2472 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2473 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2474 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2475}
2476
2477/// \brief Add overload candidates for overloaded operators that are
2478/// member functions.
2479///
2480/// Add the overloaded operator candidates that are member functions
2481/// for the operator Op that was used in an operator expression such
2482/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2483/// CandidateSet will store the added overload candidates. (C++
2484/// [over.match.oper]).
2485void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2486 SourceLocation OpLoc,
2487 Expr **Args, unsigned NumArgs,
2488 OverloadCandidateSet& CandidateSet,
2489 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002490 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2491
2492 // C++ [over.match.oper]p3:
2493 // For a unary operator @ with an operand of a type whose
2494 // cv-unqualified version is T1, and for a binary operator @ with
2495 // a left operand of a type whose cv-unqualified version is T1 and
2496 // a right operand of a type whose cv-unqualified version is T2,
2497 // three sets of candidate functions, designated member
2498 // candidates, non-member candidates and built-in candidates, are
2499 // constructed as follows:
2500 QualType T1 = Args[0]->getType();
2501 QualType T2;
2502 if (NumArgs > 1)
2503 T2 = Args[1]->getType();
2504
2505 // -- If T1 is a class type, the set of member candidates is the
2506 // result of the qualified lookup of T1::operator@
2507 // (13.3.1.1.1); otherwise, the set of member candidates is
2508 // empty.
Douglas Gregor063daf62009-03-13 18:40:31 +00002509 // FIXME: Lookup in base classes, too!
Douglas Gregor96176b32008-11-18 23:14:02 +00002510 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002511 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002512 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002513 Oper != OperEnd; ++Oper)
2514 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2515 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002516 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002517 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002518}
2519
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002520/// AddBuiltinCandidate - Add a candidate for a built-in
2521/// operator. ResultTy and ParamTys are the result and parameter types
2522/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002523/// arguments being passed to the candidate. IsAssignmentOperator
2524/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002525/// operator. NumContextualBoolArguments is the number of arguments
2526/// (at the beginning of the argument list) that will be contextually
2527/// converted to bool.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002528void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2529 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002530 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002531 bool IsAssignmentOperator,
2532 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002533 // Add this candidate
2534 CandidateSet.push_back(OverloadCandidate());
2535 OverloadCandidate& Candidate = CandidateSet.back();
2536 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002537 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002538 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002539 Candidate.BuiltinTypes.ResultTy = ResultTy;
2540 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2541 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2542
2543 // Determine the implicit conversion sequences for each of the
2544 // arguments.
2545 Candidate.Viable = true;
2546 Candidate.Conversions.resize(NumArgs);
2547 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002548 // C++ [over.match.oper]p4:
2549 // For the built-in assignment operators, conversions of the
2550 // left operand are restricted as follows:
2551 // -- no temporaries are introduced to hold the left operand, and
2552 // -- no user-defined conversions are applied to the left
2553 // operand to achieve a type match with the left-most
2554 // parameter of a built-in candidate.
2555 //
2556 // We block these conversions by turning off user-defined
2557 // conversions, since that is the only way that initialization of
2558 // a reference to a non-class type can occur from something that
2559 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002560 if (ArgIdx < NumContextualBoolArguments) {
2561 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2562 "Contextual conversion to bool requires bool type");
2563 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2564 } else {
2565 Candidate.Conversions[ArgIdx]
2566 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2567 ArgIdx == 0 && IsAssignmentOperator);
2568 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002569 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002570 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002571 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002572 break;
2573 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002574 }
2575}
2576
2577/// BuiltinCandidateTypeSet - A set of types that will be used for the
2578/// candidate operator functions for built-in operators (C++
2579/// [over.built]). The types are separated into pointer types and
2580/// enumeration types.
2581class BuiltinCandidateTypeSet {
2582 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002583 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002584
2585 /// PointerTypes - The set of pointer types that will be used in the
2586 /// built-in candidates.
2587 TypeSet PointerTypes;
2588
Sebastian Redl78eb8742009-04-19 21:53:20 +00002589 /// MemberPointerTypes - The set of member pointer types that will be
2590 /// used in the built-in candidates.
2591 TypeSet MemberPointerTypes;
2592
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002593 /// EnumerationTypes - The set of enumeration types that will be
2594 /// used in the built-in candidates.
2595 TypeSet EnumerationTypes;
2596
2597 /// Context - The AST context in which we will build the type sets.
2598 ASTContext &Context;
2599
Sebastian Redl78eb8742009-04-19 21:53:20 +00002600 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2601 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002602
2603public:
2604 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002605 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002606
2607 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2608
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002609 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2610 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002611
2612 /// pointer_begin - First pointer type found;
2613 iterator pointer_begin() { return PointerTypes.begin(); }
2614
Sebastian Redl78eb8742009-04-19 21:53:20 +00002615 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002616 iterator pointer_end() { return PointerTypes.end(); }
2617
Sebastian Redl78eb8742009-04-19 21:53:20 +00002618 /// member_pointer_begin - First member pointer type found;
2619 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2620
2621 /// member_pointer_end - Past the last member pointer type found;
2622 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2623
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002624 /// enumeration_begin - First enumeration type found;
2625 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2626
Sebastian Redl78eb8742009-04-19 21:53:20 +00002627 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002628 iterator enumeration_end() { return EnumerationTypes.end(); }
2629};
2630
Sebastian Redl78eb8742009-04-19 21:53:20 +00002631/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002632/// the set of pointer types along with any more-qualified variants of
2633/// that type. For example, if @p Ty is "int const *", this routine
2634/// will add "int const *", "int const volatile *", "int const
2635/// restrict *", and "int const volatile restrict *" to the set of
2636/// pointer types. Returns true if the add of @p Ty itself succeeded,
2637/// false otherwise.
Sebastian Redl78eb8742009-04-19 21:53:20 +00002638bool
2639BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002640 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002641 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002642 return false;
2643
2644 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2645 QualType PointeeTy = PointerTy->getPointeeType();
2646 // FIXME: Optimize this so that we don't keep trying to add the same types.
2647
Mike Stump390b4cc2009-05-16 07:39:55 +00002648 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2649 // pointer conversions that don't cast away constness?
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002650 if (!PointeeTy.isConstQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002651 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002652 (Context.getPointerType(PointeeTy.withConst()));
2653 if (!PointeeTy.isVolatileQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002654 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002655 (Context.getPointerType(PointeeTy.withVolatile()));
2656 if (!PointeeTy.isRestrictQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002657 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002658 (Context.getPointerType(PointeeTy.withRestrict()));
2659 }
2660
2661 return true;
2662}
2663
Sebastian Redl78eb8742009-04-19 21:53:20 +00002664/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2665/// to the set of pointer types along with any more-qualified variants of
2666/// that type. For example, if @p Ty is "int const *", this routine
2667/// will add "int const *", "int const volatile *", "int const
2668/// restrict *", and "int const volatile restrict *" to the set of
2669/// pointer types. Returns true if the add of @p Ty itself succeeded,
2670/// false otherwise.
2671bool
2672BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2673 QualType Ty) {
2674 // Insert this type.
2675 if (!MemberPointerTypes.insert(Ty))
2676 return false;
2677
2678 if (const MemberPointerType *PointerTy = Ty->getAsMemberPointerType()) {
2679 QualType PointeeTy = PointerTy->getPointeeType();
2680 const Type *ClassTy = PointerTy->getClass();
2681 // FIXME: Optimize this so that we don't keep trying to add the same types.
2682
2683 if (!PointeeTy.isConstQualified())
2684 AddMemberPointerWithMoreQualifiedTypeVariants
2685 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2686 if (!PointeeTy.isVolatileQualified())
2687 AddMemberPointerWithMoreQualifiedTypeVariants
2688 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2689 if (!PointeeTy.isRestrictQualified())
2690 AddMemberPointerWithMoreQualifiedTypeVariants
2691 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2692 }
2693
2694 return true;
2695}
2696
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002697/// AddTypesConvertedFrom - Add each of the types to which the type @p
2698/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00002699/// primarily interested in pointer types and enumeration types. We also
2700/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002701/// AllowUserConversions is true if we should look at the conversion
2702/// functions of a class type, and AllowExplicitConversions if we
2703/// should also include the explicit conversion functions of a class
2704/// type.
2705void
2706BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2707 bool AllowUserConversions,
2708 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002709 // Only deal with canonical types.
2710 Ty = Context.getCanonicalType(Ty);
2711
2712 // Look through reference types; they aren't part of the type of an
2713 // expression for the purposes of conversions.
2714 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2715 Ty = RefTy->getPointeeType();
2716
2717 // We don't care about qualifiers on the type.
2718 Ty = Ty.getUnqualifiedType();
2719
2720 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2721 QualType PointeeTy = PointerTy->getPointeeType();
2722
2723 // Insert our type, and its more-qualified variants, into the set
2724 // of types.
Sebastian Redl78eb8742009-04-19 21:53:20 +00002725 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002726 return;
2727
2728 // Add 'cv void*' to our set of types.
2729 if (!Ty->isVoidType()) {
2730 QualType QualVoid
2731 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl78eb8742009-04-19 21:53:20 +00002732 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002733 }
2734
2735 // If this is a pointer to a class type, add pointers to its bases
2736 // (with the same level of cv-qualification as the original
2737 // derived class, of course).
2738 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2739 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2740 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2741 Base != ClassDecl->bases_end(); ++Base) {
2742 QualType BaseTy = Context.getCanonicalType(Base->getType());
2743 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2744
2745 // Add the pointer type, recursively, so that we get all of
2746 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002747 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002748 }
2749 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00002750 } else if (Ty->isMemberPointerType()) {
2751 // Member pointers are far easier, since the pointee can't be converted.
2752 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2753 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002754 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00002755 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002756 } else if (AllowUserConversions) {
2757 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2758 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2759 // FIXME: Visit conversion functions in the base classes, too.
2760 OverloadedFunctionDecl *Conversions
2761 = ClassDecl->getConversionFunctions();
2762 for (OverloadedFunctionDecl::function_iterator Func
2763 = Conversions->function_begin();
2764 Func != Conversions->function_end(); ++Func) {
2765 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002766 if (AllowExplicitConversions || !Conv->isExplicit())
2767 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002768 }
2769 }
2770 }
2771}
2772
Douglas Gregor74253732008-11-19 15:42:04 +00002773/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2774/// operator overloads to the candidate set (C++ [over.built]), based
2775/// on the operator @p Op and the arguments given. For example, if the
2776/// operator is a binary '+', this routine might add "int
2777/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002778void
Douglas Gregor74253732008-11-19 15:42:04 +00002779Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2780 Expr **Args, unsigned NumArgs,
2781 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002782 // The set of "promoted arithmetic types", which are the arithmetic
2783 // types are that preserved by promotion (C++ [over.built]p2). Note
2784 // that the first few of these types are the promoted integral
2785 // types; these types need to be first.
2786 // FIXME: What about complex?
2787 const unsigned FirstIntegralType = 0;
2788 const unsigned LastIntegralType = 13;
2789 const unsigned FirstPromotedIntegralType = 7,
2790 LastPromotedIntegralType = 13;
2791 const unsigned FirstPromotedArithmeticType = 7,
2792 LastPromotedArithmeticType = 16;
2793 const unsigned NumArithmeticTypes = 16;
2794 QualType ArithmeticTypes[NumArithmeticTypes] = {
2795 Context.BoolTy, Context.CharTy, Context.WCharTy,
2796 Context.SignedCharTy, Context.ShortTy,
2797 Context.UnsignedCharTy, Context.UnsignedShortTy,
2798 Context.IntTy, Context.LongTy, Context.LongLongTy,
2799 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2800 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2801 };
2802
2803 // Find all of the types that the arguments can convert to, but only
2804 // if the operator we're looking at has built-in operator candidates
2805 // that make use of these types.
2806 BuiltinCandidateTypeSet CandidateTypes(Context);
2807 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2808 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002809 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002810 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002811 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002812 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00002813 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002814 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2815 true,
2816 (Op == OO_Exclaim ||
2817 Op == OO_AmpAmp ||
2818 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002819 }
2820
2821 bool isComparison = false;
2822 switch (Op) {
2823 case OO_None:
2824 case NUM_OVERLOADED_OPERATORS:
2825 assert(false && "Expected an overloaded operator");
2826 break;
2827
Douglas Gregor74253732008-11-19 15:42:04 +00002828 case OO_Star: // '*' is either unary or binary
2829 if (NumArgs == 1)
2830 goto UnaryStar;
2831 else
2832 goto BinaryStar;
2833 break;
2834
2835 case OO_Plus: // '+' is either unary or binary
2836 if (NumArgs == 1)
2837 goto UnaryPlus;
2838 else
2839 goto BinaryPlus;
2840 break;
2841
2842 case OO_Minus: // '-' is either unary or binary
2843 if (NumArgs == 1)
2844 goto UnaryMinus;
2845 else
2846 goto BinaryMinus;
2847 break;
2848
2849 case OO_Amp: // '&' is either unary or binary
2850 if (NumArgs == 1)
2851 goto UnaryAmp;
2852 else
2853 goto BinaryAmp;
2854
2855 case OO_PlusPlus:
2856 case OO_MinusMinus:
2857 // C++ [over.built]p3:
2858 //
2859 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2860 // is either volatile or empty, there exist candidate operator
2861 // functions of the form
2862 //
2863 // VQ T& operator++(VQ T&);
2864 // T operator++(VQ T&, int);
2865 //
2866 // C++ [over.built]p4:
2867 //
2868 // For every pair (T, VQ), where T is an arithmetic type other
2869 // than bool, and VQ is either volatile or empty, there exist
2870 // candidate operator functions of the form
2871 //
2872 // VQ T& operator--(VQ T&);
2873 // T operator--(VQ T&, int);
2874 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2875 Arith < NumArithmeticTypes; ++Arith) {
2876 QualType ArithTy = ArithmeticTypes[Arith];
2877 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002878 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00002879
2880 // Non-volatile version.
2881 if (NumArgs == 1)
2882 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2883 else
2884 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2885
2886 // Volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002887 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00002888 if (NumArgs == 1)
2889 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2890 else
2891 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2892 }
2893
2894 // C++ [over.built]p5:
2895 //
2896 // For every pair (T, VQ), where T is a cv-qualified or
2897 // cv-unqualified object type, and VQ is either volatile or
2898 // empty, there exist candidate operator functions of the form
2899 //
2900 // T*VQ& operator++(T*VQ&);
2901 // T*VQ& operator--(T*VQ&);
2902 // T* operator++(T*VQ&, int);
2903 // T* operator--(T*VQ&, int);
2904 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2905 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2906 // Skip pointer types that aren't pointers to object types.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002907 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002908 continue;
2909
2910 QualType ParamTypes[2] = {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002911 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00002912 };
2913
2914 // Without volatile
2915 if (NumArgs == 1)
2916 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2917 else
2918 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2919
2920 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2921 // With volatile
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002922 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00002923 if (NumArgs == 1)
2924 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2925 else
2926 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2927 }
2928 }
2929 break;
2930
2931 UnaryStar:
2932 // C++ [over.built]p6:
2933 // For every cv-qualified or cv-unqualified object type T, there
2934 // exist candidate operator functions of the form
2935 //
2936 // T& operator*(T*);
2937 //
2938 // C++ [over.built]p7:
2939 // For every function type T, there exist candidate operator
2940 // functions of the form
2941 // T& operator*(T*);
2942 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2943 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2944 QualType ParamTy = *Ptr;
2945 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002946 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00002947 &ParamTy, Args, 1, CandidateSet);
2948 }
2949 break;
2950
2951 UnaryPlus:
2952 // C++ [over.built]p8:
2953 // For every type T, there exist candidate operator functions of
2954 // the form
2955 //
2956 // T* operator+(T*);
2957 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2958 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2959 QualType ParamTy = *Ptr;
2960 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2961 }
2962
2963 // Fall through
2964
2965 UnaryMinus:
2966 // C++ [over.built]p9:
2967 // For every promoted arithmetic type T, there exist candidate
2968 // operator functions of the form
2969 //
2970 // T operator+(T);
2971 // T operator-(T);
2972 for (unsigned Arith = FirstPromotedArithmeticType;
2973 Arith < LastPromotedArithmeticType; ++Arith) {
2974 QualType ArithTy = ArithmeticTypes[Arith];
2975 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2976 }
2977 break;
2978
2979 case OO_Tilde:
2980 // C++ [over.built]p10:
2981 // For every promoted integral type T, there exist candidate
2982 // operator functions of the form
2983 //
2984 // T operator~(T);
2985 for (unsigned Int = FirstPromotedIntegralType;
2986 Int < LastPromotedIntegralType; ++Int) {
2987 QualType IntTy = ArithmeticTypes[Int];
2988 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2989 }
2990 break;
2991
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002992 case OO_New:
2993 case OO_Delete:
2994 case OO_Array_New:
2995 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002996 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002997 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002998 break;
2999
3000 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003001 UnaryAmp:
3002 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003003 // C++ [over.match.oper]p3:
3004 // -- For the operator ',', the unary operator '&', or the
3005 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003006 break;
3007
3008 case OO_Less:
3009 case OO_Greater:
3010 case OO_LessEqual:
3011 case OO_GreaterEqual:
3012 case OO_EqualEqual:
3013 case OO_ExclaimEqual:
3014 // C++ [over.built]p15:
3015 //
3016 // For every pointer or enumeration type T, there exist
3017 // candidate operator functions of the form
3018 //
3019 // bool operator<(T, T);
3020 // bool operator>(T, T);
3021 // bool operator<=(T, T);
3022 // bool operator>=(T, T);
3023 // bool operator==(T, T);
3024 // bool operator!=(T, T);
3025 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3026 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3027 QualType ParamTypes[2] = { *Ptr, *Ptr };
3028 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3029 }
3030 for (BuiltinCandidateTypeSet::iterator Enum
3031 = CandidateTypes.enumeration_begin();
3032 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3033 QualType ParamTypes[2] = { *Enum, *Enum };
3034 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3035 }
3036
3037 // Fall through.
3038 isComparison = true;
3039
Douglas Gregor74253732008-11-19 15:42:04 +00003040 BinaryPlus:
3041 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003042 if (!isComparison) {
3043 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3044
3045 // C++ [over.built]p13:
3046 //
3047 // For every cv-qualified or cv-unqualified object type T
3048 // there exist candidate operator functions of the form
3049 //
3050 // T* operator+(T*, ptrdiff_t);
3051 // T& operator[](T*, ptrdiff_t); [BELOW]
3052 // T* operator-(T*, ptrdiff_t);
3053 // T* operator+(ptrdiff_t, T*);
3054 // T& operator[](ptrdiff_t, T*); [BELOW]
3055 //
3056 // C++ [over.built]p14:
3057 //
3058 // For every T, where T is a pointer to object type, there
3059 // exist candidate operator functions of the form
3060 //
3061 // ptrdiff_t operator-(T, T);
3062 for (BuiltinCandidateTypeSet::iterator Ptr
3063 = CandidateTypes.pointer_begin();
3064 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3065 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3066
3067 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3068 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3069
3070 if (Op == OO_Plus) {
3071 // T* operator+(ptrdiff_t, T*);
3072 ParamTypes[0] = ParamTypes[1];
3073 ParamTypes[1] = *Ptr;
3074 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3075 } else {
3076 // ptrdiff_t operator-(T, T);
3077 ParamTypes[1] = *Ptr;
3078 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3079 Args, 2, CandidateSet);
3080 }
3081 }
3082 }
3083 // Fall through
3084
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003085 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003086 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003087 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003088 // C++ [over.built]p12:
3089 //
3090 // For every pair of promoted arithmetic types L and R, there
3091 // exist candidate operator functions of the form
3092 //
3093 // LR operator*(L, R);
3094 // LR operator/(L, R);
3095 // LR operator+(L, R);
3096 // LR operator-(L, R);
3097 // bool operator<(L, R);
3098 // bool operator>(L, R);
3099 // bool operator<=(L, R);
3100 // bool operator>=(L, R);
3101 // bool operator==(L, R);
3102 // bool operator!=(L, R);
3103 //
3104 // where LR is the result of the usual arithmetic conversions
3105 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003106 //
3107 // C++ [over.built]p24:
3108 //
3109 // For every pair of promoted arithmetic types L and R, there exist
3110 // candidate operator functions of the form
3111 //
3112 // LR operator?(bool, L, R);
3113 //
3114 // where LR is the result of the usual arithmetic conversions
3115 // between types L and R.
3116 // Our candidates ignore the first parameter.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003117 for (unsigned Left = FirstPromotedArithmeticType;
3118 Left < LastPromotedArithmeticType; ++Left) {
3119 for (unsigned Right = FirstPromotedArithmeticType;
3120 Right < LastPromotedArithmeticType; ++Right) {
3121 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3122 QualType Result
3123 = isComparison? Context.BoolTy
3124 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3125 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3126 }
3127 }
3128 break;
3129
3130 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003131 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003132 case OO_Caret:
3133 case OO_Pipe:
3134 case OO_LessLess:
3135 case OO_GreaterGreater:
3136 // C++ [over.built]p17:
3137 //
3138 // For every pair of promoted integral types L and R, there
3139 // exist candidate operator functions of the form
3140 //
3141 // LR operator%(L, R);
3142 // LR operator&(L, R);
3143 // LR operator^(L, R);
3144 // LR operator|(L, R);
3145 // L operator<<(L, R);
3146 // L operator>>(L, R);
3147 //
3148 // where LR is the result of the usual arithmetic conversions
3149 // between types L and R.
3150 for (unsigned Left = FirstPromotedIntegralType;
3151 Left < LastPromotedIntegralType; ++Left) {
3152 for (unsigned Right = FirstPromotedIntegralType;
3153 Right < LastPromotedIntegralType; ++Right) {
3154 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3155 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3156 ? LandR[0]
3157 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3158 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3159 }
3160 }
3161 break;
3162
3163 case OO_Equal:
3164 // C++ [over.built]p20:
3165 //
3166 // For every pair (T, VQ), where T is an enumeration or
3167 // (FIXME:) pointer to member type and VQ is either volatile or
3168 // empty, there exist candidate operator functions of the form
3169 //
3170 // VQ T& operator=(VQ T&, T);
3171 for (BuiltinCandidateTypeSet::iterator Enum
3172 = CandidateTypes.enumeration_begin();
3173 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3174 QualType ParamTypes[2];
3175
3176 // T& operator=(T&, T)
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003177 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003178 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003179 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003180 /*IsAssignmentOperator=*/false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003181
Douglas Gregor74253732008-11-19 15:42:04 +00003182 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3183 // volatile T& operator=(volatile T&, T)
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003184 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00003185 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003186 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003187 /*IsAssignmentOperator=*/false);
Douglas Gregor74253732008-11-19 15:42:04 +00003188 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003189 }
3190 // Fall through.
3191
3192 case OO_PlusEqual:
3193 case OO_MinusEqual:
3194 // C++ [over.built]p19:
3195 //
3196 // For every pair (T, VQ), where T is any type and VQ is either
3197 // volatile or empty, there exist candidate operator functions
3198 // of the form
3199 //
3200 // T*VQ& operator=(T*VQ&, T*);
3201 //
3202 // C++ [over.built]p21:
3203 //
3204 // For every pair (T, VQ), where T is a cv-qualified or
3205 // cv-unqualified object type and VQ is either volatile or
3206 // empty, there exist candidate operator functions of the form
3207 //
3208 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3209 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3210 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3211 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3212 QualType ParamTypes[2];
3213 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3214
3215 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003216 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003217 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3218 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003219
Douglas Gregor74253732008-11-19 15:42:04 +00003220 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3221 // volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003222 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003223 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3224 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003225 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003226 }
3227 // Fall through.
3228
3229 case OO_StarEqual:
3230 case OO_SlashEqual:
3231 // C++ [over.built]p18:
3232 //
3233 // For every triple (L, VQ, R), where L is an arithmetic type,
3234 // VQ is either volatile or empty, and R is a promoted
3235 // arithmetic type, there exist candidate operator functions of
3236 // the form
3237 //
3238 // VQ L& operator=(VQ L&, R);
3239 // VQ L& operator*=(VQ L&, R);
3240 // VQ L& operator/=(VQ L&, R);
3241 // VQ L& operator+=(VQ L&, R);
3242 // VQ L& operator-=(VQ L&, R);
3243 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3244 for (unsigned Right = FirstPromotedArithmeticType;
3245 Right < LastPromotedArithmeticType; ++Right) {
3246 QualType ParamTypes[2];
3247 ParamTypes[1] = ArithmeticTypes[Right];
3248
3249 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003250 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003251 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3252 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003253
3254 // Add this built-in operator as a candidate (VQ is 'volatile').
3255 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003256 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003257 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3258 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003259 }
3260 }
3261 break;
3262
3263 case OO_PercentEqual:
3264 case OO_LessLessEqual:
3265 case OO_GreaterGreaterEqual:
3266 case OO_AmpEqual:
3267 case OO_CaretEqual:
3268 case OO_PipeEqual:
3269 // C++ [over.built]p22:
3270 //
3271 // For every triple (L, VQ, R), where L is an integral type, VQ
3272 // is either volatile or empty, and R is a promoted integral
3273 // type, there exist candidate operator functions of the form
3274 //
3275 // VQ L& operator%=(VQ L&, R);
3276 // VQ L& operator<<=(VQ L&, R);
3277 // VQ L& operator>>=(VQ L&, R);
3278 // VQ L& operator&=(VQ L&, R);
3279 // VQ L& operator^=(VQ L&, R);
3280 // VQ L& operator|=(VQ L&, R);
3281 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3282 for (unsigned Right = FirstPromotedIntegralType;
3283 Right < LastPromotedIntegralType; ++Right) {
3284 QualType ParamTypes[2];
3285 ParamTypes[1] = ArithmeticTypes[Right];
3286
3287 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003288 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003289 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3290
3291 // Add this built-in operator as a candidate (VQ is 'volatile').
3292 ParamTypes[0] = ArithmeticTypes[Left];
3293 ParamTypes[0].addVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003294 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003295 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3296 }
3297 }
3298 break;
3299
Douglas Gregor74253732008-11-19 15:42:04 +00003300 case OO_Exclaim: {
3301 // C++ [over.operator]p23:
3302 //
3303 // There also exist candidate operator functions of the form
3304 //
3305 // bool operator!(bool);
3306 // bool operator&&(bool, bool); [BELOW]
3307 // bool operator||(bool, bool); [BELOW]
3308 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003309 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3310 /*IsAssignmentOperator=*/false,
3311 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003312 break;
3313 }
3314
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003315 case OO_AmpAmp:
3316 case OO_PipePipe: {
3317 // C++ [over.operator]p23:
3318 //
3319 // There also exist candidate operator functions of the form
3320 //
Douglas Gregor74253732008-11-19 15:42:04 +00003321 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003322 // bool operator&&(bool, bool);
3323 // bool operator||(bool, bool);
3324 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003325 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3326 /*IsAssignmentOperator=*/false,
3327 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003328 break;
3329 }
3330
3331 case OO_Subscript:
3332 // C++ [over.built]p13:
3333 //
3334 // For every cv-qualified or cv-unqualified object type T there
3335 // exist candidate operator functions of the form
3336 //
3337 // T* operator+(T*, ptrdiff_t); [ABOVE]
3338 // T& operator[](T*, ptrdiff_t);
3339 // T* operator-(T*, ptrdiff_t); [ABOVE]
3340 // T* operator+(ptrdiff_t, T*); [ABOVE]
3341 // T& operator[](ptrdiff_t, T*);
3342 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3343 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3344 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3345 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003346 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003347
3348 // T& operator[](T*, ptrdiff_t)
3349 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3350
3351 // T& operator[](ptrdiff_t, T*);
3352 ParamTypes[0] = ParamTypes[1];
3353 ParamTypes[1] = *Ptr;
3354 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3355 }
3356 break;
3357
3358 case OO_ArrowStar:
3359 // FIXME: No support for pointer-to-members yet.
3360 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003361
3362 case OO_Conditional:
3363 // Note that we don't consider the first argument, since it has been
3364 // contextually converted to bool long ago. The candidates below are
3365 // therefore added as binary.
3366 //
3367 // C++ [over.built]p24:
3368 // For every type T, where T is a pointer or pointer-to-member type,
3369 // there exist candidate operator functions of the form
3370 //
3371 // T operator?(bool, T, T);
3372 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003373 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3374 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3375 QualType ParamTypes[2] = { *Ptr, *Ptr };
3376 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3377 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00003378 for (BuiltinCandidateTypeSet::iterator Ptr =
3379 CandidateTypes.member_pointer_begin(),
3380 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3381 QualType ParamTypes[2] = { *Ptr, *Ptr };
3382 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3383 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003384 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003385 }
3386}
3387
Douglas Gregorfa047642009-02-04 00:32:51 +00003388/// \brief Add function candidates found via argument-dependent lookup
3389/// to the set of overloading candidates.
3390///
3391/// This routine performs argument-dependent name lookup based on the
3392/// given function name (which may also be an operator name) and adds
3393/// all of the overload candidates found by ADL to the overload
3394/// candidate set (C++ [basic.lookup.argdep]).
3395void
3396Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3397 Expr **Args, unsigned NumArgs,
3398 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003399 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00003400
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003401 // Record all of the function candidates that we've already
3402 // added to the overload set, so that we don't add those same
3403 // candidates a second time.
3404 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3405 CandEnd = CandidateSet.end();
3406 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003407 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003408 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003409 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3410 Functions.insert(FunTmpl);
3411 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003412
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003413 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00003414
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003415 // Erase all of the candidates we already knew about.
3416 // FIXME: This is suboptimal. Is there a better way?
3417 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3418 CandEnd = CandidateSet.end();
3419 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003420 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003421 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003422 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3423 Functions.erase(FunTmpl);
3424 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003425
3426 // For each of the ADL candidates we found, add it to the overload
3427 // set.
3428 for (FunctionSet::iterator Func = Functions.begin(),
3429 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00003430 Func != FuncEnd; ++Func) {
3431 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3432 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3433 else
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003434 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3435 /*FIXME: explicit args */false, 0, 0,
3436 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00003437 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003438}
3439
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003440/// isBetterOverloadCandidate - Determines whether the first overload
3441/// candidate is a better candidate than the second (C++ 13.3.3p1).
3442bool
3443Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3444 const OverloadCandidate& Cand2)
3445{
3446 // Define viable functions to be better candidates than non-viable
3447 // functions.
3448 if (!Cand2.Viable)
3449 return Cand1.Viable;
3450 else if (!Cand1.Viable)
3451 return false;
3452
Douglas Gregor88a35142008-12-22 05:46:06 +00003453 // C++ [over.match.best]p1:
3454 //
3455 // -- if F is a static member function, ICS1(F) is defined such
3456 // that ICS1(F) is neither better nor worse than ICS1(G) for
3457 // any function G, and, symmetrically, ICS1(G) is neither
3458 // better nor worse than ICS1(F).
3459 unsigned StartArg = 0;
3460 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3461 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003462
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003463 // C++ [over.match.best]p1:
3464 // A viable function F1 is defined to be a better function than another
3465 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3466 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003467 unsigned NumArgs = Cand1.Conversions.size();
3468 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3469 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003470 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003471 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3472 Cand2.Conversions[ArgIdx])) {
3473 case ImplicitConversionSequence::Better:
3474 // Cand1 has a better conversion sequence.
3475 HasBetterConversion = true;
3476 break;
3477
3478 case ImplicitConversionSequence::Worse:
3479 // Cand1 can't be better than Cand2.
3480 return false;
3481
3482 case ImplicitConversionSequence::Indistinguishable:
3483 // Do nothing.
3484 break;
3485 }
3486 }
3487
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003488 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3489 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003490 if (HasBetterConversion)
3491 return true;
3492
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003493 // - F1 is a non-template function and F2 is a function template
3494 // specialization, or, if not that,
3495 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3496 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3497 return true;
3498
3499 // -- F1 and F2 are function template specializations, and the function
3500 // template for F1 is more specialized than the template for F2
3501 // according to the partial ordering rules described in 14.5.5.2, or,
3502 // if not that,
3503
3504 // FIXME: Implement partial ordering of function templates.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003505
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003506 // -- the context is an initialization by user-defined conversion
3507 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3508 // from the return type of F1 to the destination type (i.e.,
3509 // the type of the entity being initialized) is a better
3510 // conversion sequence than the standard conversion sequence
3511 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003512 if (Cand1.Function && Cand2.Function &&
3513 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003514 isa<CXXConversionDecl>(Cand2.Function)) {
3515 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3516 Cand2.FinalConversion)) {
3517 case ImplicitConversionSequence::Better:
3518 // Cand1 has a better conversion sequence.
3519 return true;
3520
3521 case ImplicitConversionSequence::Worse:
3522 // Cand1 can't be better than Cand2.
3523 return false;
3524
3525 case ImplicitConversionSequence::Indistinguishable:
3526 // Do nothing
3527 break;
3528 }
3529 }
3530
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003531 return false;
3532}
3533
Douglas Gregore0762c92009-06-19 23:52:42 +00003534/// \brief Computes the best viable function (C++ 13.3.3)
3535/// within an overload candidate set.
3536///
3537/// \param CandidateSet the set of candidate functions.
3538///
3539/// \param Loc the location of the function name (or operator symbol) for
3540/// which overload resolution occurs.
3541///
3542/// \param Best f overload resolution was successful or found a deleted
3543/// function, Best points to the candidate function found.
3544///
3545/// \returns The result of overload resolution.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003546Sema::OverloadingResult
3547Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregore0762c92009-06-19 23:52:42 +00003548 SourceLocation Loc,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003549 OverloadCandidateSet::iterator& Best)
3550{
3551 // Find the best viable function.
3552 Best = CandidateSet.end();
3553 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3554 Cand != CandidateSet.end(); ++Cand) {
3555 if (Cand->Viable) {
3556 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3557 Best = Cand;
3558 }
3559 }
3560
3561 // If we didn't find any viable functions, abort.
3562 if (Best == CandidateSet.end())
3563 return OR_No_Viable_Function;
3564
3565 // Make sure that this function is better than every other viable
3566 // function. If not, we have an ambiguity.
3567 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3568 Cand != CandidateSet.end(); ++Cand) {
3569 if (Cand->Viable &&
3570 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003571 !isBetterOverloadCandidate(*Best, *Cand)) {
3572 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003573 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003574 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003575 }
3576
3577 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003578 if (Best->Function &&
3579 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003580 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003581 return OR_Deleted;
3582
Douglas Gregore0762c92009-06-19 23:52:42 +00003583 // C++ [basic.def.odr]p2:
3584 // An overloaded function is used if it is selected by overload resolution
3585 // when referred to from a potentially-evaluated expression. [Note: this
3586 // covers calls to named functions (5.2.2), operator overloading
3587 // (clause 13), user-defined conversions (12.3.2), allocation function for
3588 // placement new (5.3.4), as well as non-default initialization (8.5).
3589 if (Best->Function)
3590 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003591 return OR_Success;
3592}
3593
3594/// PrintOverloadCandidates - When overload resolution fails, prints
3595/// diagnostic messages containing the candidates in the candidate
3596/// set. If OnlyViable is true, only viable candidates will be printed.
3597void
3598Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3599 bool OnlyViable)
3600{
3601 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3602 LastCand = CandidateSet.end();
3603 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003604 if (Cand->Viable || !OnlyViable) {
3605 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003606 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003607 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003608 // Deleted or "unavailable" function.
3609 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3610 << Cand->Function->isDeleted();
3611 } else {
3612 // Normal function
3613 // FIXME: Give a better reason!
3614 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3615 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003616 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003617 // Desugar the type of the surrogate down to a function type,
3618 // retaining as many typedefs as possible while still showing
3619 // the function type (and, therefore, its parameter types).
3620 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003621 bool isLValueReference = false;
3622 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00003623 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003624 if (const LValueReferenceType *FnTypeRef =
3625 FnType->getAsLValueReferenceType()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003626 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003627 isLValueReference = true;
3628 } else if (const RValueReferenceType *FnTypeRef =
3629 FnType->getAsRValueReferenceType()) {
3630 FnType = FnTypeRef->getPointeeType();
3631 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00003632 }
3633 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3634 FnType = FnTypePtr->getPointeeType();
3635 isPointer = true;
3636 }
3637 // Desugar down to a function type.
3638 FnType = QualType(FnType->getAsFunctionType(), 0);
3639 // Reconstruct the pointer/reference as appropriate.
3640 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003641 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3642 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00003643
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003644 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003645 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003646 } else {
3647 // FIXME: We need to get the identifier in here
Mike Stump390b4cc2009-05-16 07:39:55 +00003648 // FIXME: Do we want the error message to point at the operator?
3649 // (built-ins won't have a location)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003650 QualType FnType
3651 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3652 Cand->BuiltinTypes.ParamTypes,
3653 Cand->Conversions.size(),
3654 false, 0);
3655
Chris Lattnerd1625842008-11-24 06:25:27 +00003656 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003657 }
3658 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003659 }
3660}
3661
Douglas Gregor904eed32008-11-10 20:40:00 +00003662/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3663/// an overloaded function (C++ [over.over]), where @p From is an
3664/// expression with overloaded function type and @p ToType is the type
3665/// we're trying to resolve to. For example:
3666///
3667/// @code
3668/// int f(double);
3669/// int f(int);
3670///
3671/// int (*pfd)(double) = f; // selects f(double)
3672/// @endcode
3673///
3674/// This routine returns the resulting FunctionDecl if it could be
3675/// resolved, and NULL otherwise. When @p Complain is true, this
3676/// routine will emit diagnostics if there is an error.
3677FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00003678Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003679 bool Complain) {
3680 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003681 bool IsMember = false;
Daniel Dunbarbb710012009-02-26 19:13:44 +00003682 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
Douglas Gregor904eed32008-11-10 20:40:00 +00003683 FunctionType = ToTypePtr->getPointeeType();
Daniel Dunbarbb710012009-02-26 19:13:44 +00003684 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3685 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00003686 else if (const MemberPointerType *MemTypePtr =
3687 ToType->getAsMemberPointerType()) {
3688 FunctionType = MemTypePtr->getPointeeType();
3689 IsMember = true;
3690 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003691
3692 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00003693 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00003694 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00003695 return 0;
3696
3697 // Find the actual overloaded function declaration.
3698 OverloadedFunctionDecl *Ovl = 0;
3699
3700 // C++ [over.over]p1:
3701 // [...] [Note: any redundant set of parentheses surrounding the
3702 // overloaded function name is ignored (5.1). ]
3703 Expr *OvlExpr = From->IgnoreParens();
3704
3705 // C++ [over.over]p1:
3706 // [...] The overloaded function name can be preceded by the &
3707 // operator.
3708 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3709 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3710 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3711 }
3712
3713 // Try to dig out the overloaded function.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003714 FunctionTemplateDecl *FunctionTemplate = 0;
3715 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003716 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor83314aa2009-07-08 20:55:45 +00003717 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3718 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003719
Douglas Gregor83314aa2009-07-08 20:55:45 +00003720 // If there's no overloaded function declaration or function template,
3721 // we're done.
3722 if (!Ovl && !FunctionTemplate)
Douglas Gregor904eed32008-11-10 20:40:00 +00003723 return 0;
3724
Douglas Gregor83314aa2009-07-08 20:55:45 +00003725 OverloadIterator Fun;
3726 if (Ovl)
3727 Fun = Ovl;
3728 else
3729 Fun = FunctionTemplate;
3730
Douglas Gregor904eed32008-11-10 20:40:00 +00003731 // Look through all of the overloaded functions, searching for one
3732 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00003733 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3734
3735 bool FoundNonTemplateFunction = false;
Douglas Gregor83314aa2009-07-08 20:55:45 +00003736 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003737 // C++ [over.over]p3:
3738 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00003739 // targets of type "pointer-to-function" or "reference-to-function."
3740 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00003741 // type "pointer-to-member-function."
3742 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003743
3744 if (FunctionTemplateDecl *FunctionTemplate
3745 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregor00aeb522009-07-08 23:33:52 +00003746 if (CXXMethodDecl *Method
3747 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3748 // Skip non-static function templates when converting to pointer, and
3749 // static when converting to member pointer.
3750 if (Method->isStatic() == IsMember)
3751 continue;
3752 } else if (IsMember)
3753 continue;
3754
3755 // C++ [over.over]p2:
3756 // If the name is a function template, template argument deduction is
3757 // done (14.8.2.2), and if the argument deduction succeeds, the
3758 // resulting template argument list is used to generate a single
3759 // function template specialization, which is added to the set of
3760 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003761 FunctionDecl *Specialization = 0;
3762 TemplateDeductionInfo Info(Context);
3763 if (TemplateDeductionResult Result
3764 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3765 /*FIXME:*/0, /*FIXME:*/0,
3766 FunctionType, Specialization, Info)) {
3767 // FIXME: make a note of the failed deduction for diagnostics.
3768 (void)Result;
3769 } else {
3770 assert(FunctionType
3771 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00003772 Matches.insert(
3773 cast<FunctionDecl>(Context.getCanonicalDecl(Specialization)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00003774 }
3775 }
3776
Sebastian Redl33b399a2009-02-04 21:23:32 +00003777 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3778 // Skip non-static functions when converting to pointer, and static
3779 // when converting to member pointer.
3780 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00003781 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00003782 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00003783 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00003784
Douglas Gregore53060f2009-06-25 22:08:12 +00003785 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregor00aeb522009-07-08 23:33:52 +00003786 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
3787 Matches.insert(cast<FunctionDecl>(Context.getCanonicalDecl(*Fun)));
3788 FoundNonTemplateFunction = true;
3789 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00003790 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003791 }
3792
Douglas Gregor00aeb522009-07-08 23:33:52 +00003793 // If there were 0 or 1 matches, we're done.
3794 if (Matches.empty())
3795 return 0;
3796 else if (Matches.size() == 1)
3797 return *Matches.begin();
3798
3799 // C++ [over.over]p4:
3800 // If more than one function is selected, [...]
3801 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
3802 if (FoundNonTemplateFunction) {
3803 // [...] any function template specializations in the set are eliminated
3804 // if the set also contains a non-template function, [...]
3805 for (llvm::SmallPtrSet<FunctionDecl *, 4>::iterator M = Matches.begin(),
3806 MEnd = Matches.end();
3807 M != MEnd; ++M)
3808 if ((*M)->getPrimaryTemplate() == 0)
3809 RemainingMatches.push_back(*M);
3810 } else {
3811 // [...] and any given function template specialization F1 is eliminated
3812 // if the set contains a second function template specialization whose
3813 // function template is more specialized than the function template of F1
3814 // according to the partial ordering rules of 14.5.5.2.
3815 // FIXME: Implement this!
3816 RemainingMatches.append(Matches.begin(), Matches.end());
3817 }
3818
3819 // [...] After such eliminations, if any, there shall remain exactly one
3820 // selected function.
3821 if (RemainingMatches.size() == 1)
3822 return RemainingMatches.front();
3823
3824 // FIXME: We should probably return the same thing that BestViableFunction
3825 // returns (even if we issue the diagnostics here).
3826 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
3827 << RemainingMatches[0]->getDeclName();
3828 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
3829 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00003830 return 0;
3831}
3832
Douglas Gregorf6b89692008-11-26 05:54:23 +00003833/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00003834/// (which eventually refers to the declaration Func) and the call
3835/// arguments Args/NumArgs, attempt to resolve the function call down
3836/// to a specific function. If overload resolution succeeds, returns
3837/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00003838/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003839/// arguments and Fn, and returns NULL.
Douglas Gregorfa047642009-02-04 00:32:51 +00003840FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor17330012009-02-04 15:01:18 +00003841 DeclarationName UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003842 bool HasExplicitTemplateArgs,
3843 const TemplateArgument *ExplicitTemplateArgs,
3844 unsigned NumExplicitTemplateArgs,
Douglas Gregor0a396682008-11-26 06:01:48 +00003845 SourceLocation LParenLoc,
3846 Expr **Args, unsigned NumArgs,
3847 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003848 SourceLocation RParenLoc,
Douglas Gregor17330012009-02-04 15:01:18 +00003849 bool &ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003850 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00003851
3852 // Add the functions denoted by Callee to the set of candidate
3853 // functions. While we're doing so, track whether argument-dependent
3854 // lookup still applies, per:
3855 //
3856 // C++0x [basic.lookup.argdep]p3:
3857 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3858 // and let Y be the lookup set produced by argument dependent
3859 // lookup (defined as follows). If X contains
3860 //
3861 // -- a declaration of a class member, or
3862 //
3863 // -- a block-scope function declaration that is not a
3864 // using-declaration, or
3865 //
3866 // -- a declaration that is neither a function or a function
3867 // template
3868 //
3869 // then Y is empty.
Douglas Gregorfa047642009-02-04 00:32:51 +00003870 if (OverloadedFunctionDecl *Ovl
Douglas Gregor17330012009-02-04 15:01:18 +00003871 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3872 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3873 FuncEnd = Ovl->function_end();
3874 Func != FuncEnd; ++Func) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003875 DeclContext *Ctx = 0;
3876 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003877 if (HasExplicitTemplateArgs)
3878 continue;
3879
Douglas Gregore53060f2009-06-25 22:08:12 +00003880 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
3881 Ctx = FunDecl->getDeclContext();
3882 } else {
3883 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003884 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
3885 ExplicitTemplateArgs,
3886 NumExplicitTemplateArgs,
3887 Args, NumArgs, CandidateSet);
Douglas Gregore53060f2009-06-25 22:08:12 +00003888 Ctx = FunTmpl->getDeclContext();
3889 }
Douglas Gregor17330012009-02-04 15:01:18 +00003890
Douglas Gregore53060f2009-06-25 22:08:12 +00003891
3892 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor17330012009-02-04 15:01:18 +00003893 ArgumentDependentLookup = false;
3894 }
3895 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003896 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor17330012009-02-04 15:01:18 +00003897 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3898
3899 if (Func->getDeclContext()->isRecord() ||
3900 Func->getDeclContext()->isFunctionOrMethod())
3901 ArgumentDependentLookup = false;
Douglas Gregore53060f2009-06-25 22:08:12 +00003902 } else if (FunctionTemplateDecl *FuncTemplate
3903 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003904 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
3905 ExplicitTemplateArgs,
3906 NumExplicitTemplateArgs,
3907 Args, NumArgs, CandidateSet);
Douglas Gregore53060f2009-06-25 22:08:12 +00003908
3909 if (FuncTemplate->getDeclContext()->isRecord())
3910 ArgumentDependentLookup = false;
3911 }
Douglas Gregor17330012009-02-04 15:01:18 +00003912
3913 if (Callee)
3914 UnqualifiedName = Callee->getDeclName();
3915
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003916 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregorfa047642009-02-04 00:32:51 +00003917 if (ArgumentDependentLookup)
Douglas Gregor17330012009-02-04 15:01:18 +00003918 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003919 CandidateSet);
3920
Douglas Gregorf6b89692008-11-26 05:54:23 +00003921 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003922 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003923 case OR_Success:
3924 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003925
3926 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00003927 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00003928 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00003929 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00003930 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3931 break;
3932
3933 case OR_Ambiguous:
3934 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00003935 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00003936 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3937 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003938
3939 case OR_Deleted:
3940 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3941 << Best->Function->isDeleted()
3942 << UnqualifiedName
3943 << Fn->getSourceRange();
3944 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3945 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003946 }
3947
3948 // Overload resolution failed. Destroy all of the subexpressions and
3949 // return NULL.
3950 Fn->Destroy(Context);
3951 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3952 Args[Arg]->Destroy(Context);
3953 return 0;
3954}
3955
Douglas Gregorbc736fc2009-03-13 23:49:33 +00003956/// \brief Create a unary operation that may resolve to an overloaded
3957/// operator.
3958///
3959/// \param OpLoc The location of the operator itself (e.g., '*').
3960///
3961/// \param OpcIn The UnaryOperator::Opcode that describes this
3962/// operator.
3963///
3964/// \param Functions The set of non-member functions that will be
3965/// considered by overload resolution. The caller needs to build this
3966/// set based on the context using, e.g.,
3967/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3968/// set should not contain any member functions; those will be added
3969/// by CreateOverloadedUnaryOp().
3970///
3971/// \param input The input argument.
3972Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3973 unsigned OpcIn,
3974 FunctionSet &Functions,
3975 ExprArg input) {
3976 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3977 Expr *Input = (Expr *)input.get();
3978
3979 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3980 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3981 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3982
3983 Expr *Args[2] = { Input, 0 };
3984 unsigned NumArgs = 1;
3985
3986 // For post-increment and post-decrement, add the implicit '0' as
3987 // the second argument, so that we know this is a post-increment or
3988 // post-decrement.
3989 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3990 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3991 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3992 SourceLocation());
3993 NumArgs = 2;
3994 }
3995
3996 if (Input->isTypeDependent()) {
3997 OverloadedFunctionDecl *Overloads
3998 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3999 for (FunctionSet::iterator Func = Functions.begin(),
4000 FuncEnd = Functions.end();
4001 Func != FuncEnd; ++Func)
4002 Overloads->addOverload(*Func);
4003
4004 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4005 OpLoc, false, false);
4006
4007 input.release();
4008 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4009 &Args[0], NumArgs,
4010 Context.DependentTy,
4011 OpLoc));
4012 }
4013
4014 // Build an empty overload set.
4015 OverloadCandidateSet CandidateSet;
4016
4017 // Add the candidates from the given function set.
4018 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4019
4020 // Add operator candidates that are member functions.
4021 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4022
4023 // Add builtin operator candidates.
4024 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4025
4026 // Perform overload resolution.
4027 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004028 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004029 case OR_Success: {
4030 // We found a built-in operator or an overloaded operator.
4031 FunctionDecl *FnDecl = Best->Function;
4032
4033 if (FnDecl) {
4034 // We matched an overloaded operator. Build a call to that
4035 // operator.
4036
4037 // Convert the arguments.
4038 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4039 if (PerformObjectArgumentInitialization(Input, Method))
4040 return ExprError();
4041 } else {
4042 // Convert the arguments.
4043 if (PerformCopyInitialization(Input,
4044 FnDecl->getParamDecl(0)->getType(),
4045 "passing"))
4046 return ExprError();
4047 }
4048
4049 // Determine the result type
4050 QualType ResultTy
4051 = FnDecl->getType()->getAsFunctionType()->getResultType();
4052 ResultTy = ResultTy.getNonReferenceType();
4053
4054 // Build the actual expression node.
4055 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4056 SourceLocation());
4057 UsualUnaryConversions(FnExpr);
4058
4059 input.release();
4060 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4061 &Input, 1, ResultTy,
4062 OpLoc));
4063 } else {
4064 // We matched a built-in operator. Convert the arguments, then
4065 // break out so that we will build the appropriate built-in
4066 // operator node.
4067 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4068 Best->Conversions[0], "passing"))
4069 return ExprError();
4070
4071 break;
4072 }
4073 }
4074
4075 case OR_No_Viable_Function:
4076 // No viable function; fall through to handling this as a
4077 // built-in operator, which will produce an error message for us.
4078 break;
4079
4080 case OR_Ambiguous:
4081 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4082 << UnaryOperator::getOpcodeStr(Opc)
4083 << Input->getSourceRange();
4084 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4085 return ExprError();
4086
4087 case OR_Deleted:
4088 Diag(OpLoc, diag::err_ovl_deleted_oper)
4089 << Best->Function->isDeleted()
4090 << UnaryOperator::getOpcodeStr(Opc)
4091 << Input->getSourceRange();
4092 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4093 return ExprError();
4094 }
4095
4096 // Either we found no viable overloaded operator or we matched a
4097 // built-in operator. In either case, fall through to trying to
4098 // build a built-in operation.
4099 input.release();
4100 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4101}
4102
Douglas Gregor063daf62009-03-13 18:40:31 +00004103/// \brief Create a binary operation that may resolve to an overloaded
4104/// operator.
4105///
4106/// \param OpLoc The location of the operator itself (e.g., '+').
4107///
4108/// \param OpcIn The BinaryOperator::Opcode that describes this
4109/// operator.
4110///
4111/// \param Functions The set of non-member functions that will be
4112/// considered by overload resolution. The caller needs to build this
4113/// set based on the context using, e.g.,
4114/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4115/// set should not contain any member functions; those will be added
4116/// by CreateOverloadedBinOp().
4117///
4118/// \param LHS Left-hand argument.
4119/// \param RHS Right-hand argument.
4120Sema::OwningExprResult
4121Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4122 unsigned OpcIn,
4123 FunctionSet &Functions,
4124 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004125 Expr *Args[2] = { LHS, RHS };
4126
4127 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4128 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4129 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4130
4131 // If either side is type-dependent, create an appropriate dependent
4132 // expression.
4133 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
4134 // .* cannot be overloaded.
4135 if (Opc == BinaryOperator::PtrMemD)
4136 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
4137 Context.DependentTy, OpLoc));
4138
4139 OverloadedFunctionDecl *Overloads
4140 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4141 for (FunctionSet::iterator Func = Functions.begin(),
4142 FuncEnd = Functions.end();
4143 Func != FuncEnd; ++Func)
4144 Overloads->addOverload(*Func);
4145
4146 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4147 OpLoc, false, false);
4148
4149 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4150 Args, 2,
4151 Context.DependentTy,
4152 OpLoc));
4153 }
4154
4155 // If this is the .* operator, which is not overloadable, just
4156 // create a built-in binary operator.
4157 if (Opc == BinaryOperator::PtrMemD)
4158 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4159
4160 // If this is one of the assignment operators, we only perform
4161 // overload resolution if the left-hand side is a class or
4162 // enumeration type (C++ [expr.ass]p3).
4163 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4164 !LHS->getType()->isOverloadableType())
4165 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4166
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004167 // Build an empty overload set.
4168 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00004169
4170 // Add the candidates from the given function set.
4171 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4172
4173 // Add operator candidates that are member functions.
4174 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4175
4176 // Add builtin operator candidates.
4177 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4178
4179 // Perform overload resolution.
4180 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004181 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004182 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00004183 // We found a built-in operator or an overloaded operator.
4184 FunctionDecl *FnDecl = Best->Function;
4185
4186 if (FnDecl) {
4187 // We matched an overloaded operator. Build a call to that
4188 // operator.
4189
4190 // Convert the arguments.
4191 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4192 if (PerformObjectArgumentInitialization(LHS, Method) ||
4193 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
4194 "passing"))
4195 return ExprError();
4196 } else {
4197 // Convert the arguments.
4198 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
4199 "passing") ||
4200 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
4201 "passing"))
4202 return ExprError();
4203 }
4204
4205 // Determine the result type
4206 QualType ResultTy
4207 = FnDecl->getType()->getAsFunctionType()->getResultType();
4208 ResultTy = ResultTy.getNonReferenceType();
4209
4210 // Build the actual expression node.
4211 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00004212 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004213 UsualUnaryConversions(FnExpr);
4214
4215 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4216 Args, 2, ResultTy,
4217 OpLoc));
4218 } else {
4219 // We matched a built-in operator. Convert the arguments, then
4220 // break out so that we will build the appropriate built-in
4221 // operator node.
4222 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4223 Best->Conversions[0], "passing") ||
4224 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4225 Best->Conversions[1], "passing"))
4226 return ExprError();
4227
4228 break;
4229 }
4230 }
4231
4232 case OR_No_Viable_Function:
Sebastian Redl8593c782009-05-21 11:50:50 +00004233 // For class as left operand for assignment or compound assigment operator
4234 // do not fall through to handling in built-in, but report that no overloaded
4235 // assignment operator found
4236 if (LHS->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4237 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4238 << BinaryOperator::getOpcodeStr(Opc)
4239 << LHS->getSourceRange() << RHS->getSourceRange();
4240 return ExprError();
4241 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004242 // No viable function; fall through to handling this as a
4243 // built-in operator, which will produce an error message for us.
4244 break;
4245
4246 case OR_Ambiguous:
4247 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4248 << BinaryOperator::getOpcodeStr(Opc)
4249 << LHS->getSourceRange() << RHS->getSourceRange();
4250 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4251 return ExprError();
4252
4253 case OR_Deleted:
4254 Diag(OpLoc, diag::err_ovl_deleted_oper)
4255 << Best->Function->isDeleted()
4256 << BinaryOperator::getOpcodeStr(Opc)
4257 << LHS->getSourceRange() << RHS->getSourceRange();
4258 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4259 return ExprError();
4260 }
4261
4262 // Either we found no viable overloaded operator or we matched a
4263 // built-in operator. In either case, try to build a built-in
4264 // operation.
4265 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4266}
4267
Douglas Gregor88a35142008-12-22 05:46:06 +00004268/// BuildCallToMemberFunction - Build a call to a member
4269/// function. MemExpr is the expression that refers to the member
4270/// function (and includes the object parameter), Args/NumArgs are the
4271/// arguments to the function call (not including the object
4272/// parameter). The caller needs to validate that the member
4273/// expression refers to a member function or an overloaded member
4274/// function.
4275Sema::ExprResult
4276Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4277 SourceLocation LParenLoc, Expr **Args,
4278 unsigned NumArgs, SourceLocation *CommaLocs,
4279 SourceLocation RParenLoc) {
4280 // Dig out the member expression. This holds both the object
4281 // argument and the member function we're referring to.
4282 MemberExpr *MemExpr = 0;
4283 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4284 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4285 else
4286 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4287 assert(MemExpr && "Building member call without member expression");
4288
4289 // Extract the object argument.
4290 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004291
Douglas Gregor88a35142008-12-22 05:46:06 +00004292 CXXMethodDecl *Method = 0;
4293 if (OverloadedFunctionDecl *Ovl
4294 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
4295 // Add overload candidates
4296 OverloadCandidateSet CandidateSet;
4297 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4298 FuncEnd = Ovl->function_end();
4299 Func != FuncEnd; ++Func) {
4300 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
4301 Method = cast<CXXMethodDecl>(*Func);
4302 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4303 /*SuppressUserConversions=*/false);
4304 }
4305
4306 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004307 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004308 case OR_Success:
4309 Method = cast<CXXMethodDecl>(Best->Function);
4310 break;
4311
4312 case OR_No_Viable_Function:
4313 Diag(MemExpr->getSourceRange().getBegin(),
4314 diag::err_ovl_no_viable_member_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004315 << Ovl->getDeclName() << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00004316 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4317 // FIXME: Leaking incoming expressions!
4318 return true;
4319
4320 case OR_Ambiguous:
4321 Diag(MemExpr->getSourceRange().getBegin(),
4322 diag::err_ovl_ambiguous_member_call)
4323 << Ovl->getDeclName() << MemExprE->getSourceRange();
4324 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4325 // FIXME: Leaking incoming expressions!
4326 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004327
4328 case OR_Deleted:
4329 Diag(MemExpr->getSourceRange().getBegin(),
4330 diag::err_ovl_deleted_member_call)
4331 << Best->Function->isDeleted()
4332 << Ovl->getDeclName() << MemExprE->getSourceRange();
4333 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4334 // FIXME: Leaking incoming expressions!
4335 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004336 }
4337
4338 FixOverloadedFunctionReference(MemExpr, Method);
4339 } else {
4340 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4341 }
4342
4343 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek8189cde2009-02-07 01:47:29 +00004344 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00004345 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4346 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004347 Method->getResultType().getNonReferenceType(),
4348 RParenLoc));
4349
4350 // Convert the object argument (for a non-static member function call).
4351 if (!Method->isStatic() &&
4352 PerformObjectArgumentInitialization(ObjectArg, Method))
4353 return true;
4354 MemExpr->setBase(ObjectArg);
4355
4356 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00004357 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004358 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4359 RParenLoc))
4360 return true;
4361
Sebastian Redl0eb23302009-01-19 00:08:26 +00004362 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00004363}
4364
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004365/// BuildCallToObjectOfClassType - Build a call to an object of class
4366/// type (C++ [over.call.object]), which can end up invoking an
4367/// overloaded function call operator (@c operator()) or performing a
4368/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00004369Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00004370Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4371 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004372 Expr **Args, unsigned NumArgs,
4373 SourceLocation *CommaLocs,
4374 SourceLocation RParenLoc) {
4375 assert(Object->getType()->isRecordType() && "Requires object type argument");
4376 const RecordType *Record = Object->getType()->getAsRecordType();
4377
4378 // C++ [over.call.object]p1:
4379 // If the primary-expression E in the function call syntax
4380 // evaluates to a class object of type “cv T”, then the set of
4381 // candidate functions includes at least the function call
4382 // operators of T. The function call operators of T are obtained by
4383 // ordinary lookup of the name operator() in the context of
4384 // (E).operator().
4385 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00004386 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004387 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004388 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004389 Oper != OperEnd; ++Oper)
4390 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4391 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004392
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004393 // C++ [over.call.object]p2:
4394 // In addition, for each conversion function declared in T of the
4395 // form
4396 //
4397 // operator conversion-type-id () cv-qualifier;
4398 //
4399 // where cv-qualifier is the same cv-qualification as, or a
4400 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00004401 // denotes the type "pointer to function of (P1,...,Pn) returning
4402 // R", or the type "reference to pointer to function of
4403 // (P1,...,Pn) returning R", or the type "reference to function
4404 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004405 // is also considered as a candidate function. Similarly,
4406 // surrogate call functions are added to the set of candidate
4407 // functions for each conversion function declared in an
4408 // accessible base class provided the function is not hidden
4409 // within T by another intervening declaration.
4410 //
4411 // FIXME: Look in base classes for more conversion operators!
4412 OverloadedFunctionDecl *Conversions
4413 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00004414 for (OverloadedFunctionDecl::function_iterator
4415 Func = Conversions->function_begin(),
4416 FuncEnd = Conversions->function_end();
4417 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004418 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4419
4420 // Strip the reference type (if any) and then the pointer type (if
4421 // any) to get down to what might be a function type.
4422 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4423 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4424 ConvType = ConvPtrType->getPointeeType();
4425
Douglas Gregor72564e72009-02-26 23:50:07 +00004426 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004427 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4428 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004429
4430 // Perform overload resolution.
4431 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004432 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004433 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004434 // Overload resolution succeeded; we'll build the appropriate call
4435 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004436 break;
4437
4438 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00004439 Diag(Object->getSourceRange().getBegin(),
4440 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004441 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00004442 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004443 break;
4444
4445 case OR_Ambiguous:
4446 Diag(Object->getSourceRange().getBegin(),
4447 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00004448 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004449 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4450 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004451
4452 case OR_Deleted:
4453 Diag(Object->getSourceRange().getBegin(),
4454 diag::err_ovl_deleted_object_call)
4455 << Best->Function->isDeleted()
4456 << Object->getType() << Object->getSourceRange();
4457 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4458 break;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004459 }
4460
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004461 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004462 // We had an error; delete all of the subexpressions and return
4463 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004464 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004465 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004466 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004467 return true;
4468 }
4469
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004470 if (Best->Function == 0) {
4471 // Since there is no function declaration, this is one of the
4472 // surrogate candidates. Dig out the conversion function.
4473 CXXConversionDecl *Conv
4474 = cast<CXXConversionDecl>(
4475 Best->Conversions[0].UserDefined.ConversionFunction);
4476
4477 // We selected one of the surrogate functions that converts the
4478 // object parameter to a function pointer. Perform the conversion
4479 // on the object argument, then let ActOnCallExpr finish the job.
4480 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00004481 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004482 Conv->getConversionType().getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004483 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004484 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4485 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4486 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004487 }
4488
4489 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4490 // that calls this method, using Object for the implicit object
4491 // parameter and passing along the remaining arguments.
4492 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor72564e72009-02-26 23:50:07 +00004493 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004494
4495 unsigned NumArgsInProto = Proto->getNumArgs();
4496 unsigned NumArgsToCheck = NumArgs;
4497
4498 // Build the full argument list for the method call (the
4499 // implicit object parameter is placed at the beginning of the
4500 // list).
4501 Expr **MethodArgs;
4502 if (NumArgs < NumArgsInProto) {
4503 NumArgsToCheck = NumArgsInProto;
4504 MethodArgs = new Expr*[NumArgsInProto + 1];
4505 } else {
4506 MethodArgs = new Expr*[NumArgs + 1];
4507 }
4508 MethodArgs[0] = Object;
4509 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4510 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4511
Ted Kremenek8189cde2009-02-07 01:47:29 +00004512 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4513 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004514 UsualUnaryConversions(NewFn);
4515
4516 // Once we've built TheCall, all of the expressions are properly
4517 // owned.
4518 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004519 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor063daf62009-03-13 18:40:31 +00004520 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4521 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004522 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004523 delete [] MethodArgs;
4524
Douglas Gregor518fda12009-01-13 05:10:00 +00004525 // We may have default arguments. If so, we need to allocate more
4526 // slots in the call for them.
4527 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004528 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00004529 else if (NumArgs > NumArgsInProto)
4530 NumArgsToCheck = NumArgsInProto;
4531
Chris Lattner312531a2009-04-12 08:11:20 +00004532 bool IsError = false;
4533
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004534 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00004535 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004536 TheCall->setArg(0, Object);
4537
Chris Lattner312531a2009-04-12 08:11:20 +00004538
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004539 // Check the argument types.
4540 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004541 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00004542 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004543 Arg = Args[i];
Douglas Gregor518fda12009-01-13 05:10:00 +00004544
4545 // Pass the argument.
4546 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner312531a2009-04-12 08:11:20 +00004547 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor518fda12009-01-13 05:10:00 +00004548 } else {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004549 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00004550 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004551
4552 TheCall->setArg(i + 1, Arg);
4553 }
4554
4555 // If this is a variadic call, handle args passed through "...".
4556 if (Proto->isVariadic()) {
4557 // Promote the arguments (C99 6.5.2.2p7).
4558 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4559 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00004560 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004561 TheCall->setArg(i + 1, Arg);
4562 }
4563 }
4564
Chris Lattner312531a2009-04-12 08:11:20 +00004565 if (IsError) return true;
4566
Sebastian Redl0eb23302009-01-19 00:08:26 +00004567 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004568}
4569
Douglas Gregor8ba10742008-11-20 16:27:02 +00004570/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4571/// (if one exists), where @c Base is an expression of class type and
4572/// @c Member is the name of the member we're trying to find.
4573Action::ExprResult
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004574Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004575 SourceLocation MemberLoc,
4576 IdentifierInfo &Member) {
4577 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4578
4579 // C++ [over.ref]p1:
4580 //
4581 // [...] An expression x->m is interpreted as (x.operator->())->m
4582 // for a class object x of type T if T::operator->() exists and if
4583 // the operator is selected as the best match function by the
4584 // overload resolution mechanism (13.3).
4585 // FIXME: look in base classes.
4586 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4587 OverloadCandidateSet CandidateSet;
4588 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004589
4590 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004591 for (llvm::tie(Oper, OperEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004592 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004593 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004594 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004595
Ted Kremenek8189cde2009-02-07 01:47:29 +00004596 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004597
Douglas Gregor8ba10742008-11-20 16:27:02 +00004598 // Perform overload resolution.
4599 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004600 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00004601 case OR_Success:
4602 // Overload resolution succeeded; we'll build the call below.
4603 break;
4604
4605 case OR_No_Viable_Function:
4606 if (CandidateSet.empty())
4607 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00004608 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004609 else
4610 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Chris Lattner4330d652009-02-17 07:29:20 +00004611 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004612 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004613 return true;
4614
4615 case OR_Ambiguous:
4616 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00004617 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004618 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004619 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004620
4621 case OR_Deleted:
4622 Diag(OpLoc, diag::err_ovl_deleted_oper)
4623 << Best->Function->isDeleted()
4624 << "operator->" << BasePtr->getSourceRange();
4625 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4626 return true;
Douglas Gregor8ba10742008-11-20 16:27:02 +00004627 }
4628
4629 // Convert the object parameter.
4630 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004631 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00004632 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004633
4634 // No concerns about early exits now.
4635 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004636
4637 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004638 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4639 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004640 UsualUnaryConversions(FnExpr);
Douglas Gregor063daf62009-03-13 18:40:31 +00004641 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004642 Method->getResultType().getNonReferenceType(),
4643 OpLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004644 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004645 MemberLoc, Member, DeclPtrTy()).release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004646}
4647
Douglas Gregor904eed32008-11-10 20:40:00 +00004648/// FixOverloadedFunctionReference - E is an expression that refers to
4649/// a C++ overloaded function (possibly with some parentheses and
4650/// perhaps a '&' around it). We have resolved the overloaded function
4651/// to the function declaration Fn, so patch up the expression E to
4652/// refer (possibly indirectly) to Fn.
4653void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4654 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4655 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4656 E->setType(PE->getSubExpr()->getType());
4657 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4658 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4659 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00004660 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4661 if (Method->isStatic()) {
4662 // Do nothing: static member functions aren't any different
4663 // from non-member functions.
4664 }
4665 else if (QualifiedDeclRefExpr *DRE
4666 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4667 // We have taken the address of a pointer to member
4668 // function. Perform the computation here so that we get the
4669 // appropriate pointer to member type.
4670 DRE->setDecl(Fn);
4671 DRE->setType(Fn->getType());
4672 QualType ClassType
4673 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4674 E->setType(Context.getMemberPointerType(Fn->getType(),
4675 ClassType.getTypePtr()));
4676 return;
4677 }
4678 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004679 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00004680 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor904eed32008-11-10 20:40:00 +00004681 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00004682 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4683 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4684 "Expected overloaded function or function template");
Douglas Gregor904eed32008-11-10 20:40:00 +00004685 DR->setDecl(Fn);
4686 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004687 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4688 MemExpr->setMemberDecl(Fn);
4689 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00004690 } else {
4691 assert(false && "Invalid reference to overloaded function");
4692 }
4693}
4694
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004695} // end namespace clang