blob: 6217e6d57af343e051618b9f542e112db339caa7 [file] [log] [blame]
Douglas Gregord2baafd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor10f3c502008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000042 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000045 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000050 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000051 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000052 ICC_Conversion
53 };
54 return Category[(int)Kind];
55}
56
57/// GetConversionRank - Retrieve the implicit conversion rank
58/// corresponding to the given implicit conversion kind.
59ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
60 static const ImplicitConversionRank
61 Rank[(int)ICK_Num_Conversion_Kinds] = {
62 ICR_Exact_Match,
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Promotion,
68 ICR_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000069 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000072 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000077 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000078 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000079 ICR_Conversion
80 };
81 return Rank[(int)Kind];
82}
83
84/// GetImplicitConversionName - Return the name of this kind of
85/// implicit conversion.
86const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
87 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
88 "No conversion",
89 "Lvalue-to-rvalue",
90 "Array-to-pointer",
91 "Function-to-pointer",
92 "Qualification",
93 "Integral promotion",
94 "Floating point promotion",
Douglas Gregore819caf2009-02-12 00:15:05 +000095 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000096 "Integral conversion",
97 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +000098 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000099 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000100 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000101 "Pointer conversion",
102 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000103 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000104 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000105 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000106 };
107 return Name[Kind];
108}
109
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113 First = ICK_Identity;
114 Second = ICK_Identity;
115 Third = ICK_Identity;
116 Deprecated = false;
117 ReferenceBinding = false;
118 DirectBinding = false;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +0000119 RRefBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000120 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000121}
122
Douglas Gregord2baafd2008-10-21 16:13:35 +0000123/// getRank - Retrieve the rank of this standard conversion sequence
124/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
125/// implicit conversions.
126ImplicitConversionRank StandardConversionSequence::getRank() const {
127 ImplicitConversionRank Rank = ICR_Exact_Match;
128 if (GetConversionRank(First) > Rank)
129 Rank = GetConversionRank(First);
130 if (GetConversionRank(Second) > Rank)
131 Rank = GetConversionRank(Second);
132 if (GetConversionRank(Third) > Rank)
133 Rank = GetConversionRank(Third);
134 return Rank;
135}
136
137/// isPointerConversionToBool - Determines whether this conversion is
138/// a conversion of a pointer or pointer-to-member to bool. This is
139/// used as part of the ranking of standard conversion sequences
140/// (C++ 13.3.3.2p4).
141bool StandardConversionSequence::isPointerConversionToBool() const
142{
143 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
144 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
145
146 // Note that FromType has not necessarily been transformed by the
147 // array-to-pointer or function-to-pointer implicit conversions, so
148 // check for their presence as well as checking whether FromType is
149 // a pointer.
150 if (ToType->isBooleanType() &&
Douglas Gregor80402cf2008-12-23 00:53:59 +0000151 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000152 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
153 return true;
154
155 return false;
156}
157
Douglas Gregor14046502008-10-23 00:40:37 +0000158/// isPointerConversionToVoidPointer - Determines whether this
159/// conversion is a conversion of a pointer to a void pointer. This is
160/// used as part of the ranking of standard conversion sequences (C++
161/// 13.3.3.2p4).
162bool
163StandardConversionSequence::
164isPointerConversionToVoidPointer(ASTContext& Context) const
165{
166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
176 if (const PointerType* ToPtrType = ToType->getAsPointerType())
177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregord2baafd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
263// FunctionDecl that New cannot be overloaded with.
264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
272// so IsOverload will not be used.
273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl)
288{
289 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
290 // Is this new function an overload of every function in the
291 // overload set?
292 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
293 FuncEnd = Ovl->function_end();
294 for (; Func != FuncEnd; ++Func) {
295 if (!IsOverload(New, *Func, MatchedDecl)) {
296 MatchedDecl = Func;
297 return false;
298 }
299 }
300
301 // This function overloads every function in the overload set.
302 return true;
303 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000304 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
305 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
306
307 // C++ [temp.fct]p2:
308 // A function template can be overloaded with other function templates
309 // and with normal (non-template) functions.
310 if ((OldTemplate == 0) != (NewTemplate == 0))
311 return true;
312
Douglas Gregord2baafd2008-10-21 16:13:35 +0000313 // Is the function New an overload of the function Old?
314 QualType OldQType = Context.getCanonicalType(Old->getType());
315 QualType NewQType = Context.getCanonicalType(New->getType());
316
317 // Compare the signatures (C++ 1.3.10) of the two functions to
318 // determine whether they are overloads. If we find any mismatch
319 // in the signature, they are overloads.
320
321 // If either of these functions is a K&R-style function (no
322 // prototype), then we consider them to have matching signatures.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000323 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
324 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000325 return false;
326
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000327 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
328 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000329
330 // The signature of a function includes the types of its
331 // parameters (C++ 1.3.10), which includes the presence or absence
332 // of the ellipsis; see C++ DR 357).
333 if (OldQType != NewQType &&
334 (OldType->getNumArgs() != NewType->getNumArgs() ||
335 OldType->isVariadic() != NewType->isVariadic() ||
336 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
337 NewType->arg_type_begin())))
338 return true;
339
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000340 // C++ [temp.over.link]p4:
341 // The signature of a function template consists of its function
342 // signature, its return type and its template parameter list. The names
343 // of the template parameters are significant only for establishing the
344 // relationship between the template parameters and the rest of the
345 // signature.
346 //
347 // We check the return type and template parameter lists for function
348 // templates first; the remaining checks follow.
349 if (NewTemplate &&
350 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
351 OldTemplate->getTemplateParameters(),
352 false, false, SourceLocation()) ||
353 OldType->getResultType() != NewType->getResultType()))
354 return true;
355
Douglas Gregord2baafd2008-10-21 16:13:35 +0000356 // If the function is a class member, its signature includes the
357 // cv-qualifiers (if any) on the function itself.
358 //
359 // As part of this, also check whether one of the member functions
360 // is static, in which case they are not overloads (C++
361 // 13.1p2). While not part of the definition of the signature,
362 // this check is important to determine whether these functions
363 // can be overloaded.
364 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
365 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
366 if (OldMethod && NewMethod &&
367 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000368 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000369 return true;
370
371 // The signatures match; this is not an overload.
372 return false;
373 } else {
374 // (C++ 13p1):
375 // Only function declarations can be overloaded; object and type
376 // declarations cannot be overloaded.
377 return false;
378 }
379}
380
Douglas Gregor81c29152008-10-29 00:13:59 +0000381/// TryImplicitConversion - Attempt to perform an implicit conversion
382/// from the given expression (Expr) to the given type (ToType). This
383/// function returns an implicit conversion sequence that can be used
384/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000385///
386/// void f(float f);
387/// void g(int i) { f(i); }
388///
389/// this routine would produce an implicit conversion sequence to
390/// describe the initialization of f from i, which will be a standard
391/// conversion sequence containing an lvalue-to-rvalue conversion (C++
392/// 4.1) followed by a floating-integral conversion (C++ 4.9).
393//
394/// Note that this routine only determines how the conversion can be
395/// performed; it does not actually perform the conversion. As such,
396/// it will not produce any diagnostics if no conversion is available,
397/// but will instead return an implicit conversion sequence of kind
398/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000399///
400/// If @p SuppressUserConversions, then user-defined conversions are
401/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000402/// If @p AllowExplicit, then explicit user-defined conversions are
403/// permitted.
Sebastian Redla55834a2009-04-12 17:16:29 +0000404/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
405/// no matter its actual lvalueness.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000406ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000407Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000408 bool SuppressUserConversions,
Sebastian Redla55834a2009-04-12 17:16:29 +0000409 bool AllowExplicit, bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000410{
411 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000412 if (IsStandardConversion(From, ToType, ICS.Standard))
413 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000414 else if (getLangOptions().CPlusPlus &&
415 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redla55834a2009-04-12 17:16:29 +0000416 !SuppressUserConversions, AllowExplicit,
417 ForceRValue)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000418 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000419 // C++ [over.ics.user]p4:
420 // A conversion of an expression of class type to the same class
421 // type is given Exact Match rank, and a conversion of an
422 // expression of class type to a base class of that type is
423 // given Conversion rank, in spite of the fact that a copy
424 // constructor (i.e., a user-defined conversion function) is
425 // called for those cases.
426 if (CXXConstructorDecl *Constructor
427 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregord9176392009-02-02 22:11:10 +0000428 QualType FromCanon
429 = Context.getCanonicalType(From->getType().getUnqualifiedType());
430 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
431 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000432 // Turn this into a "standard" conversion sequence, so that it
433 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000434 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
435 ICS.Standard.setAsIdentityConversion();
436 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
437 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000438 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000439 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000440 ICS.Standard.Second = ICK_Derived_To_Base;
441 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000442 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000443
444 // C++ [over.best.ics]p4:
445 // However, when considering the argument of a user-defined
446 // conversion function that is a candidate by 13.3.1.3 when
447 // invoked for the copying of the temporary in the second step
448 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
449 // 13.3.1.6 in all cases, only standard conversion sequences and
450 // ellipsis conversion sequences are allowed.
451 if (SuppressUserConversions &&
452 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
453 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000454 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000455 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000456
457 return ICS;
458}
459
460/// IsStandardConversion - Determines whether there is a standard
461/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
462/// expression From to the type ToType. Standard conversion sequences
463/// only consider non-class types; for conversions that involve class
464/// types, use TryImplicitConversion. If a conversion exists, SCS will
465/// contain the standard conversion sequence required to perform this
466/// conversion and this routine will return true. Otherwise, this
467/// routine will return false and the value of SCS is unspecified.
468bool
469Sema::IsStandardConversion(Expr* From, QualType ToType,
470 StandardConversionSequence &SCS)
471{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000472 QualType FromType = From->getType();
473
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000474 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000475 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000476 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000477 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000478 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000479 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000480
Douglas Gregorfcb19192009-02-11 23:02:49 +0000481 // There are no standard conversions for class types in C++, so
482 // abort early. When overloading in C, however, we do permit
483 if (FromType->isRecordType() || ToType->isRecordType()) {
484 if (getLangOptions().CPlusPlus)
485 return false;
486
487 // When we're overloading in C, we allow, as standard conversions,
488 }
489
Douglas Gregord2baafd2008-10-21 16:13:35 +0000490 // The first conversion can be an lvalue-to-rvalue conversion,
491 // array-to-pointer conversion, or function-to-pointer conversion
492 // (C++ 4p1).
493
494 // Lvalue-to-rvalue conversion (C++ 4.1):
495 // An lvalue (3.10) of a non-function, non-array type T can be
496 // converted to an rvalue.
497 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
498 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000499 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000500 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000501 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000502
503 // If T is a non-class type, the type of the rvalue is the
504 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000505 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
506 // just strip the qualifiers because they don't matter.
507
508 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000509 FromType = FromType.getUnqualifiedType();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000510 }
511 // Array-to-pointer conversion (C++ 4.2)
512 else if (FromType->isArrayType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000513 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000514
515 // An lvalue or rvalue of type "array of N T" or "array of unknown
516 // bound of T" can be converted to an rvalue of type "pointer to
517 // T" (C++ 4.2p1).
518 FromType = Context.getArrayDecayedType(FromType);
519
520 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
521 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000522 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000523
524 // For the purpose of ranking in overload resolution
525 // (13.3.3.1.1), this conversion is considered an
526 // array-to-pointer conversion followed by a qualification
527 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000528 SCS.Second = ICK_Identity;
529 SCS.Third = ICK_Qualification;
530 SCS.ToTypePtr = ToType.getAsOpaquePtr();
531 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000532 }
533 }
534 // Function-to-pointer conversion (C++ 4.3).
535 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000536 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000537
538 // An lvalue of function type T can be converted to an rvalue of
539 // type "pointer to T." The result is a pointer to the
540 // function. (C++ 4.3p1).
541 FromType = Context.getPointerType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000542 }
Douglas Gregor45014fd2008-11-10 20:40:00 +0000543 // Address of overloaded function (C++ [over.over]).
544 else if (FunctionDecl *Fn
545 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
546 SCS.First = ICK_Function_To_Pointer;
547
548 // We were able to resolve the address of the overloaded function,
549 // so we can convert to the type of that function.
550 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000551 if (ToType->isLValueReferenceType())
552 FromType = Context.getLValueReferenceType(FromType);
553 else if (ToType->isRValueReferenceType())
554 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000555 else if (ToType->isMemberPointerType()) {
556 // Resolve address only succeeds if both sides are member pointers,
557 // but it doesn't have to be the same class. See DR 247.
558 // Note that this means that the type of &Derived::fn can be
559 // Ret (Base::*)(Args) if the fn overload actually found is from the
560 // base class, even if it was brought into the derived class via a
561 // using declaration. The standard isn't clear on this issue at all.
562 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
563 FromType = Context.getMemberPointerType(FromType,
564 Context.getTypeDeclType(M->getParent()).getTypePtr());
565 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000566 FromType = Context.getPointerType(FromType);
567 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000568 // We don't require any conversions for the first step.
569 else {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000570 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000571 }
572
573 // The second conversion can be an integral promotion, floating
574 // point promotion, integral conversion, floating point conversion,
575 // floating-integral conversion, pointer conversion,
576 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000577 // For overloading in C, this can also be a "compatible-type"
578 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000579 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000580 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000581 // The unqualified versions of the types are the same: there's no
582 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000583 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000584 }
585 // Integral promotion (C++ 4.5).
586 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000587 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000588 FromType = ToType.getUnqualifiedType();
589 }
590 // Floating point promotion (C++ 4.6).
591 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000592 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000593 FromType = ToType.getUnqualifiedType();
594 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000595 // Complex promotion (Clang extension)
596 else if (IsComplexPromotion(FromType, ToType)) {
597 SCS.Second = ICK_Complex_Promotion;
598 FromType = ToType.getUnqualifiedType();
599 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000600 // Integral conversions (C++ 4.7).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000601 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000602 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000603 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000604 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000605 FromType = ToType.getUnqualifiedType();
606 }
607 // Floating point conversions (C++ 4.8).
608 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000609 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000610 FromType = ToType.getUnqualifiedType();
611 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000612 // Complex conversions (C99 6.3.1.6)
613 else if (FromType->isComplexType() && ToType->isComplexType()) {
614 SCS.Second = ICK_Complex_Conversion;
615 FromType = ToType.getUnqualifiedType();
616 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000617 // Floating-integral conversions (C++ 4.9).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000618 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000619 else if ((FromType->isFloatingType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000620 ToType->isIntegralType() && !ToType->isBooleanType() &&
621 !ToType->isEnumeralType()) ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000622 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
623 ToType->isFloatingType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000624 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000625 FromType = ToType.getUnqualifiedType();
626 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000627 // Complex-real conversions (C99 6.3.1.7)
628 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
629 (ToType->isComplexType() && FromType->isArithmeticType())) {
630 SCS.Second = ICK_Complex_Real;
631 FromType = ToType.getUnqualifiedType();
632 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000633 // Pointer conversions (C++ 4.10).
Douglas Gregor6fd35572008-12-19 17:40:08 +0000634 else if (IsPointerConversion(From, FromType, ToType, FromType,
635 IncompatibleObjC)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000636 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000637 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000638 }
Sebastian Redlba387562009-01-25 19:43:20 +0000639 // Pointer to member conversions (4.11).
640 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
641 SCS.Second = ICK_Pointer_Member;
642 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000643 // Boolean conversions (C++ 4.12).
Douglas Gregord2baafd2008-10-21 16:13:35 +0000644 else if (ToType->isBooleanType() &&
645 (FromType->isArithmeticType() ||
646 FromType->isEnumeralType() ||
Douglas Gregor80402cf2008-12-23 00:53:59 +0000647 FromType->isPointerType() ||
Sebastian Redlba387562009-01-25 19:43:20 +0000648 FromType->isBlockPointerType() ||
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000649 FromType->isMemberPointerType() ||
650 FromType->isNullPtrType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000651 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000652 FromType = Context.BoolTy;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000653 }
654 // Compatible conversions (Clang extension for C function overloading)
655 else if (!getLangOptions().CPlusPlus &&
656 Context.typesAreCompatible(ToType, FromType)) {
657 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000658 } else {
659 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000660 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000661 }
662
Douglas Gregor81c29152008-10-29 00:13:59 +0000663 QualType CanonFrom;
664 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000665 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000666 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000667 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000668 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000669 CanonFrom = Context.getCanonicalType(FromType);
670 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000671 } else {
672 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000673 SCS.Third = ICK_Identity;
674
675 // C++ [over.best.ics]p6:
676 // [...] Any difference in top-level cv-qualification is
677 // subsumed by the initialization itself and does not constitute
678 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000679 CanonFrom = Context.getCanonicalType(FromType);
680 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000681 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000682 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
683 FromType = ToType;
684 CanonFrom = CanonTo;
685 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000686 }
687
688 // If we have not converted the argument type to the parameter type,
689 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000690 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000691 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000692
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000693 SCS.ToTypePtr = FromType.getAsOpaquePtr();
694 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000695}
696
697/// IsIntegralPromotion - Determines whether the conversion from the
698/// expression From (whose potentially-adjusted type is FromType) to
699/// ToType is an integral promotion (C++ 4.5). If so, returns true and
700/// sets PromotedType to the promoted type.
701bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
702{
703 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000704 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000705 if (!To) {
706 return false;
707 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000708
709 // An rvalue of type char, signed char, unsigned char, short int, or
710 // unsigned short int can be converted to an rvalue of type int if
711 // int can represent all the values of the source type; otherwise,
712 // the source rvalue can be converted to an rvalue of type unsigned
713 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000714 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000715 if (// We can promote any signed, promotable integer type to an int
716 (FromType->isSignedIntegerType() ||
717 // We can promote any unsigned integer type whose size is
718 // less than int to an int.
719 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000720 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000721 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000722 }
723
Douglas Gregord2baafd2008-10-21 16:13:35 +0000724 return To->getKind() == BuiltinType::UInt;
725 }
726
727 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
728 // can be converted to an rvalue of the first of the following types
729 // that can represent all the values of its underlying type: int,
730 // unsigned int, long, or unsigned long (C++ 4.5p2).
731 if ((FromType->isEnumeralType() || FromType->isWideCharType())
732 && ToType->isIntegerType()) {
733 // Determine whether the type we're converting from is signed or
734 // unsigned.
735 bool FromIsSigned;
736 uint64_t FromSize = Context.getTypeSize(FromType);
737 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
738 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
739 FromIsSigned = UnderlyingType->isSignedIntegerType();
740 } else {
741 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
742 FromIsSigned = true;
743 }
744
745 // The types we'll try to promote to, in the appropriate
746 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000747 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000748 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000749 Context.LongTy, Context.UnsignedLongTy ,
750 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000751 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000752 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000753 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
754 if (FromSize < ToSize ||
755 (FromSize == ToSize &&
756 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
757 // We found the type that we can promote to. If this is the
758 // type we wanted, we have a promotion. Otherwise, no
759 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000760 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000761 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
762 }
763 }
764 }
765
766 // An rvalue for an integral bit-field (9.6) can be converted to an
767 // rvalue of type int if int can represent all the values of the
768 // bit-field; otherwise, it can be converted to unsigned int if
769 // unsigned int can represent all the values of the bit-field. If
770 // the bit-field is larger yet, no integral promotion applies to
771 // it. If the bit-field has an enumerated type, it is treated as any
772 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stumpe127ae32009-05-16 07:39:55 +0000773 // FIXME: We should delay checking of bit-fields until we actually perform the
774 // conversion.
Douglas Gregor531434b2009-05-02 02:18:30 +0000775 using llvm::APSInt;
776 if (From)
777 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000778 APSInt BitWidth;
Douglas Gregor531434b2009-05-02 02:18:30 +0000779 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
780 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
781 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
782 ToSize = Context.getTypeSize(ToType);
Douglas Gregor82d44772008-12-20 23:49:58 +0000783
784 // Are we promoting to an int from a bitfield that fits in an int?
785 if (BitWidth < ToSize ||
786 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
787 return To->getKind() == BuiltinType::Int;
788 }
789
790 // Are we promoting to an unsigned int from an unsigned bitfield
791 // that fits into an unsigned int?
792 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
793 return To->getKind() == BuiltinType::UInt;
794 }
795
796 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000797 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000798 }
Douglas Gregor531434b2009-05-02 02:18:30 +0000799
Douglas Gregord2baafd2008-10-21 16:13:35 +0000800 // An rvalue of type bool can be converted to an rvalue of type int,
801 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000802 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000803 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000804 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000805
806 return false;
807}
808
809/// IsFloatingPointPromotion - Determines whether the conversion from
810/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
811/// returns true and sets PromotedType to the promoted type.
812bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
813{
814 /// An rvalue of type float can be converted to an rvalue of type
815 /// double. (C++ 4.6p1).
816 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000817 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000818 if (FromBuiltin->getKind() == BuiltinType::Float &&
819 ToBuiltin->getKind() == BuiltinType::Double)
820 return true;
821
Douglas Gregore819caf2009-02-12 00:15:05 +0000822 // C99 6.3.1.5p1:
823 // When a float is promoted to double or long double, or a
824 // double is promoted to long double [...].
825 if (!getLangOptions().CPlusPlus &&
826 (FromBuiltin->getKind() == BuiltinType::Float ||
827 FromBuiltin->getKind() == BuiltinType::Double) &&
828 (ToBuiltin->getKind() == BuiltinType::LongDouble))
829 return true;
830 }
831
Douglas Gregord2baafd2008-10-21 16:13:35 +0000832 return false;
833}
834
Douglas Gregore819caf2009-02-12 00:15:05 +0000835/// \brief Determine if a conversion is a complex promotion.
836///
837/// A complex promotion is defined as a complex -> complex conversion
838/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000839/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000840bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
841 const ComplexType *FromComplex = FromType->getAsComplexType();
842 if (!FromComplex)
843 return false;
844
845 const ComplexType *ToComplex = ToType->getAsComplexType();
846 if (!ToComplex)
847 return false;
848
849 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000850 ToComplex->getElementType()) ||
851 IsIntegralPromotion(0, FromComplex->getElementType(),
852 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000853}
854
Douglas Gregor24a90a52008-11-26 23:31:11 +0000855/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
856/// the pointer type FromPtr to a pointer to type ToPointee, with the
857/// same type qualifiers as FromPtr has on its pointee type. ToType,
858/// if non-empty, will be a pointer to ToType that may or may not have
859/// the right set of qualifiers on its pointee.
860static QualType
861BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
862 QualType ToPointee, QualType ToType,
863 ASTContext &Context) {
864 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
865 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
866 unsigned Quals = CanonFromPointee.getCVRQualifiers();
867
868 // Exact qualifier match -> return the pointer type we're converting to.
869 if (CanonToPointee.getCVRQualifiers() == Quals) {
870 // ToType is exactly what we need. Return it.
871 if (ToType.getTypePtr())
872 return ToType;
873
874 // Build a pointer to ToPointee. It has the right qualifiers
875 // already.
876 return Context.getPointerType(ToPointee);
877 }
878
879 // Just build a canonical type that has the right qualifiers.
880 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
881}
882
Douglas Gregord2baafd2008-10-21 16:13:35 +0000883/// IsPointerConversion - Determines whether the conversion of the
884/// expression From, which has the (possibly adjusted) type FromType,
885/// can be converted to the type ToType via a pointer conversion (C++
886/// 4.10). If so, returns true and places the converted type (that
887/// might differ from ToType in its cv-qualifiers at some level) into
888/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000889///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000890/// This routine also supports conversions to and from block pointers
891/// and conversions with Objective-C's 'id', 'id<protocols...>', and
892/// pointers to interfaces. FIXME: Once we've determined the
893/// appropriate overloading rules for Objective-C, we may want to
894/// split the Objective-C checks into a different routine; however,
895/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000896/// conversions, so for now they live here. IncompatibleObjC will be
897/// set if the conversion is an allowed Objective-C conversion that
898/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000899bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000900 QualType& ConvertedType,
901 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000902{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000903 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000904 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
905 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000906
Douglas Gregorf1d75712008-12-22 20:51:52 +0000907 // Conversion from a null pointer constant to any Objective-C pointer type.
908 if (Context.isObjCObjectPointerType(ToType) &&
909 From->isNullPointerConstant(Context)) {
910 ConvertedType = ToType;
911 return true;
912 }
913
Douglas Gregor9036ef72008-11-27 00:15:41 +0000914 // Blocks: Block pointers can be converted to void*.
915 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
916 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
917 ConvertedType = ToType;
918 return true;
919 }
920 // Blocks: A null pointer constant can be converted to a block
921 // pointer type.
922 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
923 ConvertedType = ToType;
924 return true;
925 }
926
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000927 // If the left-hand-side is nullptr_t, the right side can be a null
928 // pointer constant.
929 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
930 ConvertedType = ToType;
931 return true;
932 }
933
Douglas Gregord2baafd2008-10-21 16:13:35 +0000934 const PointerType* ToTypePtr = ToType->getAsPointerType();
935 if (!ToTypePtr)
936 return false;
937
938 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
939 if (From->isNullPointerConstant(Context)) {
940 ConvertedType = ToType;
941 return true;
942 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000943
Douglas Gregor24a90a52008-11-26 23:31:11 +0000944 // Beyond this point, both types need to be pointers.
945 const PointerType *FromTypePtr = FromType->getAsPointerType();
946 if (!FromTypePtr)
947 return false;
948
949 QualType FromPointeeType = FromTypePtr->getPointeeType();
950 QualType ToPointeeType = ToTypePtr->getPointeeType();
951
Douglas Gregord2baafd2008-10-21 16:13:35 +0000952 // An rvalue of type "pointer to cv T," where T is an object type,
953 // can be converted to an rvalue of type "pointer to cv void" (C++
954 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000955 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000956 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
957 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000958 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000959 return true;
960 }
961
Douglas Gregorfcb19192009-02-11 23:02:49 +0000962 // When we're overloading in C, we allow a special kind of pointer
963 // conversion for compatible-but-not-identical pointee types.
964 if (!getLangOptions().CPlusPlus &&
965 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
966 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
967 ToPointeeType,
968 ToType, Context);
969 return true;
970 }
971
Douglas Gregor14046502008-10-23 00:40:37 +0000972 // C++ [conv.ptr]p3:
973 //
974 // An rvalue of type "pointer to cv D," where D is a class type,
975 // can be converted to an rvalue of type "pointer to cv B," where
976 // B is a base class (clause 10) of D. If B is an inaccessible
977 // (clause 11) or ambiguous (10.2) base class of D, a program that
978 // necessitates this conversion is ill-formed. The result of the
979 // conversion is a pointer to the base class sub-object of the
980 // derived class object. The null pointer value is converted to
981 // the null pointer value of the destination type.
982 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000983 // Note that we do not check for ambiguity or inaccessibility
984 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000985 if (getLangOptions().CPlusPlus &&
986 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000987 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000988 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
989 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000990 ToType, Context);
991 return true;
992 }
Douglas Gregor14046502008-10-23 00:40:37 +0000993
Douglas Gregor932778b2008-12-19 19:13:09 +0000994 return false;
995}
996
997/// isObjCPointerConversion - Determines whether this is an
998/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
999/// with the same arguments and return values.
1000bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1001 QualType& ConvertedType,
1002 bool &IncompatibleObjC) {
1003 if (!getLangOptions().ObjC1)
1004 return false;
1005
1006 // Conversions with Objective-C's id<...>.
1007 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
1008 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
1009 ConvertedType = ToType;
1010 return true;
1011 }
1012
Douglas Gregor80402cf2008-12-23 00:53:59 +00001013 // Beyond this point, both types need to be pointers or block pointers.
1014 QualType ToPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +00001015 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +00001016 if (ToTypePtr)
1017 ToPointeeType = ToTypePtr->getPointeeType();
1018 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
1019 ToPointeeType = ToBlockPtr->getPointeeType();
1020 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001021 return false;
1022
Douglas Gregor80402cf2008-12-23 00:53:59 +00001023 QualType FromPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +00001024 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +00001025 if (FromTypePtr)
1026 FromPointeeType = FromTypePtr->getPointeeType();
1027 else if (const BlockPointerType *FromBlockPtr
1028 = FromType->getAsBlockPointerType())
1029 FromPointeeType = FromBlockPtr->getPointeeType();
1030 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001031 return false;
1032
Douglas Gregor24a90a52008-11-26 23:31:11 +00001033 // Objective C++: We're able to convert from a pointer to an
1034 // interface to a pointer to a different interface.
1035 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
1036 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1037 if (FromIface && ToIface &&
1038 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor80402cf2008-12-23 00:53:59 +00001039 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001040 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001041 ToType, Context);
1042 return true;
1043 }
1044
Douglas Gregor6fd35572008-12-19 17:40:08 +00001045 if (FromIface && ToIface &&
1046 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1047 // Okay: this is some kind of implicit downcast of Objective-C
1048 // interfaces, which is permitted. However, we're going to
1049 // complain about it.
1050 IncompatibleObjC = true;
Douglas Gregor80402cf2008-12-23 00:53:59 +00001051 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor6fd35572008-12-19 17:40:08 +00001052 ToPointeeType,
1053 ToType, Context);
1054 return true;
1055 }
1056
Douglas Gregor24a90a52008-11-26 23:31:11 +00001057 // Objective C++: We're able to convert between "id" and a pointer
1058 // to any interface (in both directions).
Steve Naroff17c03822009-02-12 17:52:19 +00001059 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1060 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001061 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1062 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001063 ToType, Context);
1064 return true;
1065 }
Douglas Gregor14046502008-10-23 00:40:37 +00001066
Douglas Gregord0c653a2008-12-18 23:43:31 +00001067 // Objective C++: Allow conversions between the Objective-C "id" and
1068 // "Class", in either direction.
Steve Naroff17c03822009-02-12 17:52:19 +00001069 if ((Context.isObjCIdStructType(FromPointeeType) &&
1070 Context.isObjCClassStructType(ToPointeeType)) ||
1071 (Context.isObjCClassStructType(FromPointeeType) &&
1072 Context.isObjCIdStructType(ToPointeeType))) {
Douglas Gregord0c653a2008-12-18 23:43:31 +00001073 ConvertedType = ToType;
1074 return true;
1075 }
1076
Douglas Gregor932778b2008-12-19 19:13:09 +00001077 // If we have pointers to pointers, recursively check whether this
1078 // is an Objective-C conversion.
1079 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1080 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1081 IncompatibleObjC)) {
1082 // We always complain about this conversion.
1083 IncompatibleObjC = true;
1084 ConvertedType = ToType;
1085 return true;
1086 }
1087
Douglas Gregor80402cf2008-12-23 00:53:59 +00001088 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001089 // differences in the argument and result types are in Objective-C
1090 // pointer conversions. If so, we permit the conversion (but
1091 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001092 const FunctionProtoType *FromFunctionType
1093 = FromPointeeType->getAsFunctionProtoType();
1094 const FunctionProtoType *ToFunctionType
1095 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001096 if (FromFunctionType && ToFunctionType) {
1097 // If the function types are exactly the same, this isn't an
1098 // Objective-C pointer conversion.
1099 if (Context.getCanonicalType(FromPointeeType)
1100 == Context.getCanonicalType(ToPointeeType))
1101 return false;
1102
1103 // Perform the quick checks that will tell us whether these
1104 // function types are obviously different.
1105 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1106 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1107 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1108 return false;
1109
1110 bool HasObjCConversion = false;
1111 if (Context.getCanonicalType(FromFunctionType->getResultType())
1112 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1113 // Okay, the types match exactly. Nothing to do.
1114 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1115 ToFunctionType->getResultType(),
1116 ConvertedType, IncompatibleObjC)) {
1117 // Okay, we have an Objective-C pointer conversion.
1118 HasObjCConversion = true;
1119 } else {
1120 // Function types are too different. Abort.
1121 return false;
1122 }
1123
1124 // Check argument types.
1125 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1126 ArgIdx != NumArgs; ++ArgIdx) {
1127 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1128 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1129 if (Context.getCanonicalType(FromArgType)
1130 == Context.getCanonicalType(ToArgType)) {
1131 // Okay, the types match exactly. Nothing to do.
1132 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1133 ConvertedType, IncompatibleObjC)) {
1134 // Okay, we have an Objective-C pointer conversion.
1135 HasObjCConversion = true;
1136 } else {
1137 // Argument types are too different. Abort.
1138 return false;
1139 }
1140 }
1141
1142 if (HasObjCConversion) {
1143 // We had an Objective-C conversion. Allow this pointer
1144 // conversion, but complain about it.
1145 ConvertedType = ToType;
1146 IncompatibleObjC = true;
1147 return true;
1148 }
1149 }
1150
Sebastian Redlba387562009-01-25 19:43:20 +00001151 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001152}
1153
Douglas Gregorbb461502008-10-24 04:54:22 +00001154/// CheckPointerConversion - Check the pointer conversion from the
1155/// expression From to the type ToType. This routine checks for
1156/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1157/// conversions for which IsPointerConversion has already returned
1158/// true. It returns true and produces a diagnostic if there was an
1159/// error, or returns false otherwise.
1160bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1161 QualType FromType = From->getType();
1162
1163 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1164 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001165 QualType FromPointeeType = FromPtrType->getPointeeType(),
1166 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001167
1168 // Objective-C++ conversions are always okay.
Mike Stumpe127ae32009-05-16 07:39:55 +00001169 // FIXME: We should have a different class of conversions for the
1170 // Objective-C++ implicit conversions.
Steve Naroff17c03822009-02-12 17:52:19 +00001171 if (Context.isObjCIdStructType(FromPointeeType) ||
1172 Context.isObjCIdStructType(ToPointeeType) ||
1173 Context.isObjCClassStructType(FromPointeeType) ||
1174 Context.isObjCClassStructType(ToPointeeType))
Douglas Gregord0c653a2008-12-18 23:43:31 +00001175 return false;
1176
Douglas Gregorbb461502008-10-24 04:54:22 +00001177 if (FromPointeeType->isRecordType() &&
1178 ToPointeeType->isRecordType()) {
1179 // We must have a derived-to-base conversion. Check an
1180 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001181 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1182 From->getExprLoc(),
1183 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001184 }
1185 }
1186
1187 return false;
1188}
1189
Sebastian Redlba387562009-01-25 19:43:20 +00001190/// IsMemberPointerConversion - Determines whether the conversion of the
1191/// expression From, which has the (possibly adjusted) type FromType, can be
1192/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1193/// If so, returns true and places the converted type (that might differ from
1194/// ToType in its cv-qualifiers at some level) into ConvertedType.
1195bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1196 QualType ToType, QualType &ConvertedType)
1197{
1198 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1199 if (!ToTypePtr)
1200 return false;
1201
1202 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1203 if (From->isNullPointerConstant(Context)) {
1204 ConvertedType = ToType;
1205 return true;
1206 }
1207
1208 // Otherwise, both types have to be member pointers.
1209 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1210 if (!FromTypePtr)
1211 return false;
1212
1213 // A pointer to member of B can be converted to a pointer to member of D,
1214 // where D is derived from B (C++ 4.11p2).
1215 QualType FromClass(FromTypePtr->getClass(), 0);
1216 QualType ToClass(ToTypePtr->getClass(), 0);
1217 // FIXME: What happens when these are dependent? Is this function even called?
1218
1219 if (IsDerivedFrom(ToClass, FromClass)) {
1220 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1221 ToClass.getTypePtr());
1222 return true;
1223 }
1224
1225 return false;
1226}
1227
1228/// CheckMemberPointerConversion - Check the member pointer conversion from the
1229/// expression From to the type ToType. This routine checks for ambiguous or
1230/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1231/// for which IsMemberPointerConversion has already returned true. It returns
1232/// true and produces a diagnostic if there was an error, or returns false
1233/// otherwise.
1234bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1235 QualType FromType = From->getType();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001236 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1237 if (!FromPtrType)
1238 return false;
Sebastian Redlba387562009-01-25 19:43:20 +00001239
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001240 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1241 assert(ToPtrType && "No member pointer cast has a target type "
1242 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001243
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001244 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1245 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001246
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001247 // FIXME: What about dependent types?
1248 assert(FromClass->isRecordType() && "Pointer into non-class.");
1249 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001250
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001251 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1252 /*DetectVirtual=*/true);
1253 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1254 assert(DerivationOkay &&
1255 "Should not have been called if derivation isn't OK.");
1256 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001257
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001258 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1259 getUnqualifiedType())) {
1260 // Derivation is ambiguous. Redo the check to find the exact paths.
1261 Paths.clear();
1262 Paths.setRecordingPaths(true);
1263 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1264 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1265 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001266
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001267 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1268 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1269 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1270 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001271 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001272
Douglas Gregor2e047592009-02-28 01:32:25 +00001273 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001274 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1275 << FromClass << ToClass << QualType(VBase, 0)
1276 << From->getSourceRange();
1277 return true;
1278 }
1279
Sebastian Redlba387562009-01-25 19:43:20 +00001280 return false;
1281}
1282
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001283/// IsQualificationConversion - Determines whether the conversion from
1284/// an rvalue of type FromType to ToType is a qualification conversion
1285/// (C++ 4.4).
1286bool
1287Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1288{
1289 FromType = Context.getCanonicalType(FromType);
1290 ToType = Context.getCanonicalType(ToType);
1291
1292 // If FromType and ToType are the same type, this is not a
1293 // qualification conversion.
1294 if (FromType == ToType)
1295 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001296
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001297 // (C++ 4.4p4):
1298 // A conversion can add cv-qualifiers at levels other than the first
1299 // in multi-level pointers, subject to the following rules: [...]
1300 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001301 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001302 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001303 // Within each iteration of the loop, we check the qualifiers to
1304 // determine if this still looks like a qualification
1305 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001306 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001307 // until there are no more pointers or pointers-to-members left to
1308 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001309 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001310
1311 // -- for every j > 0, if const is in cv 1,j then const is in cv
1312 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001313 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001314 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001315
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001316 // -- if the cv 1,j and cv 2,j are different, then const is in
1317 // every cv for 0 < k < j.
1318 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001319 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001320 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001321
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001322 // Keep track of whether all prior cv-qualifiers in the "to" type
1323 // include const.
1324 PreviousToQualsIncludeConst
1325 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001326 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001327
1328 // We are left with FromType and ToType being the pointee types
1329 // after unwrapping the original FromType and ToType the same number
1330 // of types. If we unwrapped any pointers, and if FromType and
1331 // ToType have the same unqualified type (since we checked
1332 // qualifiers above), then this is a qualification conversion.
1333 return UnwrappedAnyPointer &&
1334 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1335}
1336
Douglas Gregorb206cc42009-01-30 23:27:23 +00001337/// Determines whether there is a user-defined conversion sequence
1338/// (C++ [over.ics.user]) that converts expression From to the type
1339/// ToType. If such a conversion exists, User will contain the
1340/// user-defined conversion sequence that performs such a conversion
1341/// and this routine will return true. Otherwise, this routine returns
1342/// false and User is unspecified.
1343///
1344/// \param AllowConversionFunctions true if the conversion should
1345/// consider conversion functions at all. If false, only constructors
1346/// will be considered.
1347///
1348/// \param AllowExplicit true if the conversion should consider C++0x
1349/// "explicit" conversion functions as well as non-explicit conversion
1350/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001351///
1352/// \param ForceRValue true if the expression should be treated as an rvalue
1353/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001354bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001355 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001356 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001357 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001358{
1359 OverloadCandidateSet CandidateSet;
Douglas Gregor2e047592009-02-28 01:32:25 +00001360 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1361 if (CXXRecordDecl *ToRecordDecl
1362 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1363 // C++ [over.match.ctor]p1:
1364 // When objects of class type are direct-initialized (8.5), or
1365 // copy-initialized from an expression of the same or a
1366 // derived class type (8.5), overload resolution selects the
1367 // constructor. [...] For copy-initialization, the candidate
1368 // functions are all the converting constructors (12.3.1) of
1369 // that class. The argument list is the expression-list within
1370 // the parentheses of the initializer.
1371 DeclarationName ConstructorName
1372 = Context.DeclarationNames.getCXXConstructorName(
1373 Context.getCanonicalType(ToType).getUnqualifiedType());
1374 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001375 for (llvm::tie(Con, ConEnd)
1376 = ToRecordDecl->lookup(Context, ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001377 Con != ConEnd; ++Con) {
1378 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1379 if (Constructor->isConvertingConstructor())
1380 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00001381 /*SuppressUserConversions=*/true, ForceRValue);
Douglas Gregor2e047592009-02-28 01:32:25 +00001382 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001383 }
1384 }
1385
Douglas Gregorb206cc42009-01-30 23:27:23 +00001386 if (!AllowConversionFunctions) {
1387 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-02-28 01:32:25 +00001388 } else if (const RecordType *FromRecordType
1389 = From->getType()->getAsRecordType()) {
1390 if (CXXRecordDecl *FromRecordDecl
1391 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1392 // Add all of the conversion functions as candidates.
1393 // FIXME: Look for conversions in base classes!
1394 OverloadedFunctionDecl *Conversions
1395 = FromRecordDecl->getConversionFunctions();
1396 for (OverloadedFunctionDecl::function_iterator Func
1397 = Conversions->function_begin();
1398 Func != Conversions->function_end(); ++Func) {
1399 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1400 if (AllowExplicit || !Conv->isExplicit())
1401 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1402 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001403 }
1404 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001405
1406 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001407 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001408 case OR_Success:
1409 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001410 if (CXXConstructorDecl *Constructor
1411 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1412 // C++ [over.ics.user]p1:
1413 // If the user-defined conversion is specified by a
1414 // constructor (12.3.1), the initial standard conversion
1415 // sequence converts the source type to the type required by
1416 // the argument of the constructor.
1417 //
1418 // FIXME: What about ellipsis conversions?
1419 QualType ThisType = Constructor->getThisType(Context);
1420 User.Before = Best->Conversions[0].Standard;
1421 User.ConversionFunction = Constructor;
1422 User.After.setAsIdentityConversion();
1423 User.After.FromTypePtr
1424 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1425 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1426 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001427 } else if (CXXConversionDecl *Conversion
1428 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1429 // C++ [over.ics.user]p1:
1430 //
1431 // [...] If the user-defined conversion is specified by a
1432 // conversion function (12.3.2), the initial standard
1433 // conversion sequence converts the source type to the
1434 // implicit object parameter of the conversion function.
1435 User.Before = Best->Conversions[0].Standard;
1436 User.ConversionFunction = Conversion;
1437
1438 // C++ [over.ics.user]p2:
1439 // The second standard conversion sequence converts the
1440 // result of the user-defined conversion to the target type
1441 // for the sequence. Since an implicit conversion sequence
1442 // is an initialization, the special rules for
1443 // initialization by user-defined conversion apply when
1444 // selecting the best user-defined conversion for a
1445 // user-defined conversion sequence (see 13.3.3 and
1446 // 13.3.3.1).
1447 User.After = Best->FinalConversion;
1448 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001449 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001450 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001451 return false;
1452 }
1453
1454 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001455 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001456 // No conversion here! We're done.
1457 return false;
1458
1459 case OR_Ambiguous:
1460 // FIXME: See C++ [over.best.ics]p10 for the handling of
1461 // ambiguous conversion sequences.
1462 return false;
1463 }
1464
1465 return false;
1466}
1467
Douglas Gregord2baafd2008-10-21 16:13:35 +00001468/// CompareImplicitConversionSequences - Compare two implicit
1469/// conversion sequences to determine whether one is better than the
1470/// other or if they are indistinguishable (C++ 13.3.3.2).
1471ImplicitConversionSequence::CompareKind
1472Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1473 const ImplicitConversionSequence& ICS2)
1474{
1475 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1476 // conversion sequences (as defined in 13.3.3.1)
1477 // -- a standard conversion sequence (13.3.3.1.1) is a better
1478 // conversion sequence than a user-defined conversion sequence or
1479 // an ellipsis conversion sequence, and
1480 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1481 // conversion sequence than an ellipsis conversion sequence
1482 // (13.3.3.1.3).
1483 //
1484 if (ICS1.ConversionKind < ICS2.ConversionKind)
1485 return ImplicitConversionSequence::Better;
1486 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1487 return ImplicitConversionSequence::Worse;
1488
1489 // Two implicit conversion sequences of the same form are
1490 // indistinguishable conversion sequences unless one of the
1491 // following rules apply: (C++ 13.3.3.2p3):
1492 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1493 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1494 else if (ICS1.ConversionKind ==
1495 ImplicitConversionSequence::UserDefinedConversion) {
1496 // User-defined conversion sequence U1 is a better conversion
1497 // sequence than another user-defined conversion sequence U2 if
1498 // they contain the same user-defined conversion function or
1499 // constructor and if the second standard conversion sequence of
1500 // U1 is better than the second standard conversion sequence of
1501 // U2 (C++ 13.3.3.2p3).
1502 if (ICS1.UserDefined.ConversionFunction ==
1503 ICS2.UserDefined.ConversionFunction)
1504 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1505 ICS2.UserDefined.After);
1506 }
1507
1508 return ImplicitConversionSequence::Indistinguishable;
1509}
1510
1511/// CompareStandardConversionSequences - Compare two standard
1512/// conversion sequences to determine whether one is better than the
1513/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1514ImplicitConversionSequence::CompareKind
1515Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1516 const StandardConversionSequence& SCS2)
1517{
1518 // Standard conversion sequence S1 is a better conversion sequence
1519 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1520
1521 // -- S1 is a proper subsequence of S2 (comparing the conversion
1522 // sequences in the canonical form defined by 13.3.3.1.1,
1523 // excluding any Lvalue Transformation; the identity conversion
1524 // sequence is considered to be a subsequence of any
1525 // non-identity conversion sequence) or, if not that,
1526 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1527 // Neither is a proper subsequence of the other. Do nothing.
1528 ;
1529 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1530 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1531 (SCS1.Second == ICK_Identity &&
1532 SCS1.Third == ICK_Identity))
1533 // SCS1 is a proper subsequence of SCS2.
1534 return ImplicitConversionSequence::Better;
1535 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1536 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1537 (SCS2.Second == ICK_Identity &&
1538 SCS2.Third == ICK_Identity))
1539 // SCS2 is a proper subsequence of SCS1.
1540 return ImplicitConversionSequence::Worse;
1541
1542 // -- the rank of S1 is better than the rank of S2 (by the rules
1543 // defined below), or, if not that,
1544 ImplicitConversionRank Rank1 = SCS1.getRank();
1545 ImplicitConversionRank Rank2 = SCS2.getRank();
1546 if (Rank1 < Rank2)
1547 return ImplicitConversionSequence::Better;
1548 else if (Rank2 < Rank1)
1549 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001550
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001551 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1552 // are indistinguishable unless one of the following rules
1553 // applies:
1554
1555 // A conversion that is not a conversion of a pointer, or
1556 // pointer to member, to bool is better than another conversion
1557 // that is such a conversion.
1558 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1559 return SCS2.isPointerConversionToBool()
1560 ? ImplicitConversionSequence::Better
1561 : ImplicitConversionSequence::Worse;
1562
Douglas Gregor14046502008-10-23 00:40:37 +00001563 // C++ [over.ics.rank]p4b2:
1564 //
1565 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001566 // conversion of B* to A* is better than conversion of B* to
1567 // void*, and conversion of A* to void* is better than conversion
1568 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001569 bool SCS1ConvertsToVoid
1570 = SCS1.isPointerConversionToVoidPointer(Context);
1571 bool SCS2ConvertsToVoid
1572 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001573 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1574 // Exactly one of the conversion sequences is a conversion to
1575 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001576 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1577 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001578 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1579 // Neither conversion sequence converts to a void pointer; compare
1580 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001581 if (ImplicitConversionSequence::CompareKind DerivedCK
1582 = CompareDerivedToBaseConversions(SCS1, SCS2))
1583 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001584 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1585 // Both conversion sequences are conversions to void
1586 // pointers. Compare the source types to determine if there's an
1587 // inheritance relationship in their sources.
1588 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1589 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1590
1591 // Adjust the types we're converting from via the array-to-pointer
1592 // conversion, if we need to.
1593 if (SCS1.First == ICK_Array_To_Pointer)
1594 FromType1 = Context.getArrayDecayedType(FromType1);
1595 if (SCS2.First == ICK_Array_To_Pointer)
1596 FromType2 = Context.getArrayDecayedType(FromType2);
1597
1598 QualType FromPointee1
1599 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1600 QualType FromPointee2
1601 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1602
1603 if (IsDerivedFrom(FromPointee2, FromPointee1))
1604 return ImplicitConversionSequence::Better;
1605 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1606 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001607
1608 // Objective-C++: If one interface is more specific than the
1609 // other, it is the better one.
1610 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1611 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1612 if (FromIface1 && FromIface1) {
1613 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1614 return ImplicitConversionSequence::Better;
1615 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1616 return ImplicitConversionSequence::Worse;
1617 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001618 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001619
1620 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1621 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001622 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001623 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001624 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001625
Douglas Gregor0e343382008-10-29 14:50:44 +00001626 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001627 // C++0x [over.ics.rank]p3b4:
1628 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1629 // implicit object parameter of a non-static member function declared
1630 // without a ref-qualifier, and S1 binds an rvalue reference to an
1631 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001632 // FIXME: We don't know if we're dealing with the implicit object parameter,
1633 // or if the member function in this case has a ref qualifier.
1634 // (Of course, we don't have ref qualifiers yet.)
1635 if (SCS1.RRefBinding != SCS2.RRefBinding)
1636 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1637 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001638
1639 // C++ [over.ics.rank]p3b4:
1640 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1641 // which the references refer are the same type except for
1642 // top-level cv-qualifiers, and the type to which the reference
1643 // initialized by S2 refers is more cv-qualified than the type
1644 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001645 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1646 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001647 T1 = Context.getCanonicalType(T1);
1648 T2 = Context.getCanonicalType(T2);
1649 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1650 if (T2.isMoreQualifiedThan(T1))
1651 return ImplicitConversionSequence::Better;
1652 else if (T1.isMoreQualifiedThan(T2))
1653 return ImplicitConversionSequence::Worse;
1654 }
1655 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001656
1657 return ImplicitConversionSequence::Indistinguishable;
1658}
1659
1660/// CompareQualificationConversions - Compares two standard conversion
1661/// sequences to determine whether they can be ranked based on their
1662/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1663ImplicitConversionSequence::CompareKind
1664Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1665 const StandardConversionSequence& SCS2)
1666{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001667 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001668 // -- S1 and S2 differ only in their qualification conversion and
1669 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1670 // cv-qualification signature of type T1 is a proper subset of
1671 // the cv-qualification signature of type T2, and S1 is not the
1672 // deprecated string literal array-to-pointer conversion (4.2).
1673 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1674 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1675 return ImplicitConversionSequence::Indistinguishable;
1676
1677 // FIXME: the example in the standard doesn't use a qualification
1678 // conversion (!)
1679 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1680 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1681 T1 = Context.getCanonicalType(T1);
1682 T2 = Context.getCanonicalType(T2);
1683
1684 // If the types are the same, we won't learn anything by unwrapped
1685 // them.
1686 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1687 return ImplicitConversionSequence::Indistinguishable;
1688
1689 ImplicitConversionSequence::CompareKind Result
1690 = ImplicitConversionSequence::Indistinguishable;
1691 while (UnwrapSimilarPointerTypes(T1, T2)) {
1692 // Within each iteration of the loop, we check the qualifiers to
1693 // determine if this still looks like a qualification
1694 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001695 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001696 // until there are no more pointers or pointers-to-members left
1697 // to unwrap. This essentially mimics what
1698 // IsQualificationConversion does, but here we're checking for a
1699 // strict subset of qualifiers.
1700 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1701 // The qualifiers are the same, so this doesn't tell us anything
1702 // about how the sequences rank.
1703 ;
1704 else if (T2.isMoreQualifiedThan(T1)) {
1705 // T1 has fewer qualifiers, so it could be the better sequence.
1706 if (Result == ImplicitConversionSequence::Worse)
1707 // Neither has qualifiers that are a subset of the other's
1708 // qualifiers.
1709 return ImplicitConversionSequence::Indistinguishable;
1710
1711 Result = ImplicitConversionSequence::Better;
1712 } else if (T1.isMoreQualifiedThan(T2)) {
1713 // T2 has fewer qualifiers, so it could be the better sequence.
1714 if (Result == ImplicitConversionSequence::Better)
1715 // Neither has qualifiers that are a subset of the other's
1716 // qualifiers.
1717 return ImplicitConversionSequence::Indistinguishable;
1718
1719 Result = ImplicitConversionSequence::Worse;
1720 } else {
1721 // Qualifiers are disjoint.
1722 return ImplicitConversionSequence::Indistinguishable;
1723 }
1724
1725 // If the types after this point are equivalent, we're done.
1726 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1727 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001728 }
1729
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001730 // Check that the winning standard conversion sequence isn't using
1731 // the deprecated string literal array to pointer conversion.
1732 switch (Result) {
1733 case ImplicitConversionSequence::Better:
1734 if (SCS1.Deprecated)
1735 Result = ImplicitConversionSequence::Indistinguishable;
1736 break;
1737
1738 case ImplicitConversionSequence::Indistinguishable:
1739 break;
1740
1741 case ImplicitConversionSequence::Worse:
1742 if (SCS2.Deprecated)
1743 Result = ImplicitConversionSequence::Indistinguishable;
1744 break;
1745 }
1746
1747 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001748}
1749
Douglas Gregor14046502008-10-23 00:40:37 +00001750/// CompareDerivedToBaseConversions - Compares two standard conversion
1751/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001752/// various kinds of derived-to-base conversions (C++
1753/// [over.ics.rank]p4b3). As part of these checks, we also look at
1754/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001755ImplicitConversionSequence::CompareKind
1756Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1757 const StandardConversionSequence& SCS2) {
1758 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1759 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1760 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1761 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1762
1763 // Adjust the types we're converting from via the array-to-pointer
1764 // conversion, if we need to.
1765 if (SCS1.First == ICK_Array_To_Pointer)
1766 FromType1 = Context.getArrayDecayedType(FromType1);
1767 if (SCS2.First == ICK_Array_To_Pointer)
1768 FromType2 = Context.getArrayDecayedType(FromType2);
1769
1770 // Canonicalize all of the types.
1771 FromType1 = Context.getCanonicalType(FromType1);
1772 ToType1 = Context.getCanonicalType(ToType1);
1773 FromType2 = Context.getCanonicalType(FromType2);
1774 ToType2 = Context.getCanonicalType(ToType2);
1775
Douglas Gregor0e343382008-10-29 14:50:44 +00001776 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001777 //
1778 // If class B is derived directly or indirectly from class A and
1779 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001780 //
1781 // For Objective-C, we let A, B, and C also be Objective-C
1782 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001783
1784 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001785 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001786 SCS2.Second == ICK_Pointer_Conversion &&
1787 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1788 FromType1->isPointerType() && FromType2->isPointerType() &&
1789 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001790 QualType FromPointee1
1791 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1792 QualType ToPointee1
1793 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1794 QualType FromPointee2
1795 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1796 QualType ToPointee2
1797 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001798
1799 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1800 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1801 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1802 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1803
Douglas Gregor0e343382008-10-29 14:50:44 +00001804 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001805 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1806 if (IsDerivedFrom(ToPointee1, ToPointee2))
1807 return ImplicitConversionSequence::Better;
1808 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1809 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001810
1811 if (ToIface1 && ToIface2) {
1812 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1813 return ImplicitConversionSequence::Better;
1814 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1815 return ImplicitConversionSequence::Worse;
1816 }
Douglas Gregor14046502008-10-23 00:40:37 +00001817 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001818
1819 // -- conversion of B* to A* is better than conversion of C* to A*,
1820 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1821 if (IsDerivedFrom(FromPointee2, FromPointee1))
1822 return ImplicitConversionSequence::Better;
1823 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1824 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001825
1826 if (FromIface1 && FromIface2) {
1827 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1828 return ImplicitConversionSequence::Better;
1829 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1830 return ImplicitConversionSequence::Worse;
1831 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001832 }
Douglas Gregor14046502008-10-23 00:40:37 +00001833 }
1834
Douglas Gregor0e343382008-10-29 14:50:44 +00001835 // Compare based on reference bindings.
1836 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1837 SCS1.Second == ICK_Derived_To_Base) {
1838 // -- binding of an expression of type C to a reference of type
1839 // B& is better than binding an expression of type C to a
1840 // reference of type A&,
1841 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1842 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1843 if (IsDerivedFrom(ToType1, ToType2))
1844 return ImplicitConversionSequence::Better;
1845 else if (IsDerivedFrom(ToType2, ToType1))
1846 return ImplicitConversionSequence::Worse;
1847 }
1848
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001849 // -- binding of an expression of type B to a reference of type
1850 // A& is better than binding an expression of type C to a
1851 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001852 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1853 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1854 if (IsDerivedFrom(FromType2, FromType1))
1855 return ImplicitConversionSequence::Better;
1856 else if (IsDerivedFrom(FromType1, FromType2))
1857 return ImplicitConversionSequence::Worse;
1858 }
1859 }
1860
1861
1862 // FIXME: conversion of A::* to B::* is better than conversion of
1863 // A::* to C::*,
1864
1865 // FIXME: conversion of B::* to C::* is better than conversion of
1866 // A::* to C::*, and
1867
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001868 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1869 SCS1.Second == ICK_Derived_To_Base) {
1870 // -- conversion of C to B is better than conversion of C to A,
1871 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1872 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1873 if (IsDerivedFrom(ToType1, ToType2))
1874 return ImplicitConversionSequence::Better;
1875 else if (IsDerivedFrom(ToType2, ToType1))
1876 return ImplicitConversionSequence::Worse;
1877 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001878
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001879 // -- conversion of B to A is better than conversion of C to A.
1880 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1881 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1882 if (IsDerivedFrom(FromType2, FromType1))
1883 return ImplicitConversionSequence::Better;
1884 else if (IsDerivedFrom(FromType1, FromType2))
1885 return ImplicitConversionSequence::Worse;
1886 }
1887 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001888
Douglas Gregor14046502008-10-23 00:40:37 +00001889 return ImplicitConversionSequence::Indistinguishable;
1890}
1891
Douglas Gregor81c29152008-10-29 00:13:59 +00001892/// TryCopyInitialization - Try to copy-initialize a value of type
1893/// ToType from the expression From. Return the implicit conversion
1894/// sequence required to pass this argument, which may be a bad
1895/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001896/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001897/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1898/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001899ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001900Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001901 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001902 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001903 ImplicitConversionSequence ICS;
Sebastian Redla55834a2009-04-12 17:16:29 +00001904 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1905 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001906 return ICS;
1907 } else {
Sebastian Redla55834a2009-04-12 17:16:29 +00001908 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1909 ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001910 }
1911}
1912
Sebastian Redla55834a2009-04-12 17:16:29 +00001913/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1914/// the expression @p From. Returns true (and emits a diagnostic) if there was
1915/// an error, returns false if the initialization succeeded. Elidable should
1916/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1917/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001918bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001919 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001920 if (!getLangOptions().CPlusPlus) {
1921 // In C, argument passing is the same as performing an assignment.
1922 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001923
Douglas Gregor81c29152008-10-29 00:13:59 +00001924 AssignConvertType ConvTy =
1925 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001926 if (ConvTy != Compatible &&
1927 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1928 ConvTy = Compatible;
1929
Douglas Gregor81c29152008-10-29 00:13:59 +00001930 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1931 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001932 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001933
Chris Lattner271d4c22008-11-24 05:29:24 +00001934 if (ToType->isReferenceType())
1935 return CheckReferenceInit(From, ToType);
1936
Sebastian Redla55834a2009-04-12 17:16:29 +00001937 if (!PerformImplicitConversion(From, ToType, Flavor,
1938 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001939 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001940
Chris Lattner271d4c22008-11-24 05:29:24 +00001941 return Diag(From->getSourceRange().getBegin(),
1942 diag::err_typecheck_convert_incompatible)
1943 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001944}
1945
Douglas Gregor5ed15042008-11-18 23:14:02 +00001946/// TryObjectArgumentInitialization - Try to initialize the object
1947/// parameter of the given member function (@c Method) from the
1948/// expression @p From.
1949ImplicitConversionSequence
1950Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1951 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1952 unsigned MethodQuals = Method->getTypeQualifiers();
1953 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1954
1955 // Set up the conversion sequence as a "bad" conversion, to allow us
1956 // to exit early.
1957 ImplicitConversionSequence ICS;
1958 ICS.Standard.setAsIdentityConversion();
1959 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1960
1961 // We need to have an object of class type.
1962 QualType FromType = From->getType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001963 if (const PointerType *PT = FromType->getAsPointerType())
1964 FromType = PT->getPointeeType();
1965
1966 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00001967
1968 // The implicit object parmeter is has the type "reference to cv X",
1969 // where X is the class of which the function is a member
1970 // (C++ [over.match.funcs]p4). However, when finding an implicit
1971 // conversion sequence for the argument, we are not allowed to
1972 // create temporaries or perform user-defined conversions
1973 // (C++ [over.match.funcs]p5). We perform a simplified version of
1974 // reference binding here, that allows class rvalues to bind to
1975 // non-constant references.
1976
1977 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1978 // with the implicit object parameter (C++ [over.match.funcs]p5).
1979 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1980 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1981 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1982 return ICS;
1983
1984 // Check that we have either the same type or a derived type. It
1985 // affects the conversion rank.
1986 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1987 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1988 ICS.Standard.Second = ICK_Identity;
1989 else if (IsDerivedFrom(FromType, ClassType))
1990 ICS.Standard.Second = ICK_Derived_To_Base;
1991 else
1992 return ICS;
1993
1994 // Success. Mark this as a reference binding.
1995 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1996 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1997 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1998 ICS.Standard.ReferenceBinding = true;
1999 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00002000 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002001 return ICS;
2002}
2003
2004/// PerformObjectArgumentInitialization - Perform initialization of
2005/// the implicit object parameter for the given Method with the given
2006/// expression.
2007bool
2008Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002009 QualType FromRecordType, DestType;
2010 QualType ImplicitParamRecordType =
2011 Method->getThisType(Context)->getAsPointerType()->getPointeeType();
2012
2013 if (const PointerType *PT = From->getType()->getAsPointerType()) {
2014 FromRecordType = PT->getPointeeType();
2015 DestType = Method->getThisType(Context);
2016 } else {
2017 FromRecordType = From->getType();
2018 DestType = ImplicitParamRecordType;
2019 }
2020
Douglas Gregor5ed15042008-11-18 23:14:02 +00002021 ImplicitConversionSequence ICS
2022 = TryObjectArgumentInitialization(From, Method);
2023 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2024 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002025 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002026 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2027
Douglas Gregor5ed15042008-11-18 23:14:02 +00002028 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002029 CheckDerivedToBaseConversion(FromRecordType,
2030 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002031 From->getSourceRange().getBegin(),
2032 From->getSourceRange()))
2033 return true;
2034
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002035 ImpCastExprToType(From, DestType, /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002036 return false;
2037}
2038
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002039/// TryContextuallyConvertToBool - Attempt to contextually convert the
2040/// expression From to bool (C++0x [conv]p3).
2041ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2042 return TryImplicitConversion(From, Context.BoolTy, false, true);
2043}
2044
2045/// PerformContextuallyConvertToBool - Perform a contextual conversion
2046/// of the expression From to bool (C++0x [conv]p3).
2047bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2048 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2049 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2050 return false;
2051
2052 return Diag(From->getSourceRange().getBegin(),
2053 diag::err_typecheck_bool_condition)
2054 << From->getType() << From->getSourceRange();
2055}
2056
Douglas Gregord2baafd2008-10-21 16:13:35 +00002057/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002058/// candidate functions, using the given function call arguments. If
2059/// @p SuppressUserConversions, then don't allow user-defined
2060/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002061/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2062/// hacky way to implement the overloading rules for elidable copy
2063/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002064void
2065Sema::AddOverloadCandidate(FunctionDecl *Function,
2066 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002067 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002068 bool SuppressUserConversions,
2069 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002070{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002071 const FunctionProtoType* Proto
2072 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002073 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002074 assert(!isa<CXXConversionDecl>(Function) &&
2075 "Use AddConversionCandidate for conversion functions");
Douglas Gregord2baafd2008-10-21 16:13:35 +00002076
Douglas Gregor3257fb52008-12-22 05:46:06 +00002077 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002078 if (!isa<CXXConstructorDecl>(Method)) {
2079 // If we get here, it's because we're calling a member function
2080 // that is named without a member access expression (e.g.,
2081 // "this->f") that was either written explicitly or created
2082 // implicitly. This can happen with a qualified call to a member
2083 // function, e.g., X::f(). We use a NULL object as the implied
2084 // object argument (C++ [over.call.func]p3).
2085 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2086 SuppressUserConversions, ForceRValue);
2087 return;
2088 }
2089 // We treat a constructor like a non-member function, since its object
2090 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002091 }
2092
2093
Douglas Gregord2baafd2008-10-21 16:13:35 +00002094 // Add this candidate
2095 CandidateSet.push_back(OverloadCandidate());
2096 OverloadCandidate& Candidate = CandidateSet.back();
2097 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002098 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002099 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002100 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002101
2102 unsigned NumArgsInProto = Proto->getNumArgs();
2103
2104 // (C++ 13.3.2p2): A candidate function having fewer than m
2105 // parameters is viable only if it has an ellipsis in its parameter
2106 // list (8.3.5).
2107 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2108 Candidate.Viable = false;
2109 return;
2110 }
2111
2112 // (C++ 13.3.2p2): A candidate function having more than m parameters
2113 // is viable only if the (m+1)st parameter has a default argument
2114 // (8.3.6). For the purposes of overload resolution, the
2115 // parameter list is truncated on the right, so that there are
2116 // exactly m parameters.
2117 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2118 if (NumArgs < MinRequiredArgs) {
2119 // Not enough arguments.
2120 Candidate.Viable = false;
2121 return;
2122 }
2123
2124 // Determine the implicit conversion sequences for each of the
2125 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002126 Candidate.Conversions.resize(NumArgs);
2127 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2128 if (ArgIdx < NumArgsInProto) {
2129 // (C++ 13.3.2p3): for F to be a viable function, there shall
2130 // exist for each argument an implicit conversion sequence
2131 // (13.3.3.1) that converts that argument to the corresponding
2132 // parameter of F.
2133 QualType ParamType = Proto->getArgType(ArgIdx);
2134 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002135 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002136 SuppressUserConversions, ForceRValue);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002137 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002138 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002139 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002140 break;
2141 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002142 } else {
2143 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2144 // argument for which there is no corresponding parameter is
2145 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2146 Candidate.Conversions[ArgIdx].ConversionKind
2147 = ImplicitConversionSequence::EllipsisConversion;
2148 }
2149 }
2150}
2151
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002152/// \brief Add all of the function declarations in the given function set to
2153/// the overload canddiate set.
2154void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2155 Expr **Args, unsigned NumArgs,
2156 OverloadCandidateSet& CandidateSet,
2157 bool SuppressUserConversions) {
2158 for (FunctionSet::const_iterator F = Functions.begin(),
2159 FEnd = Functions.end();
2160 F != FEnd; ++F)
2161 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2162 SuppressUserConversions);
2163}
2164
Douglas Gregor5ed15042008-11-18 23:14:02 +00002165/// AddMethodCandidate - Adds the given C++ member function to the set
2166/// of candidate functions, using the given function call arguments
2167/// and the object argument (@c Object). For example, in a call
2168/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2169/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2170/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002171/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2172/// a slightly hacky way to implement the overloading rules for elidable copy
2173/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002174void
2175Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2176 Expr **Args, unsigned NumArgs,
2177 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002178 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002179{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002180 const FunctionProtoType* Proto
2181 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002182 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002183 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002184 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002185 assert(!isa<CXXConstructorDecl>(Method) &&
2186 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002187
2188 // Add this candidate
2189 CandidateSet.push_back(OverloadCandidate());
2190 OverloadCandidate& Candidate = CandidateSet.back();
2191 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002192 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002193 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002194
2195 unsigned NumArgsInProto = Proto->getNumArgs();
2196
2197 // (C++ 13.3.2p2): A candidate function having fewer than m
2198 // parameters is viable only if it has an ellipsis in its parameter
2199 // list (8.3.5).
2200 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2201 Candidate.Viable = false;
2202 return;
2203 }
2204
2205 // (C++ 13.3.2p2): A candidate function having more than m parameters
2206 // is viable only if the (m+1)st parameter has a default argument
2207 // (8.3.6). For the purposes of overload resolution, the
2208 // parameter list is truncated on the right, so that there are
2209 // exactly m parameters.
2210 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2211 if (NumArgs < MinRequiredArgs) {
2212 // Not enough arguments.
2213 Candidate.Viable = false;
2214 return;
2215 }
2216
2217 Candidate.Viable = true;
2218 Candidate.Conversions.resize(NumArgs + 1);
2219
Douglas Gregor3257fb52008-12-22 05:46:06 +00002220 if (Method->isStatic() || !Object)
2221 // The implicit object argument is ignored.
2222 Candidate.IgnoreObjectArgument = true;
2223 else {
2224 // Determine the implicit conversion sequence for the object
2225 // parameter.
2226 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2227 if (Candidate.Conversions[0].ConversionKind
2228 == ImplicitConversionSequence::BadConversion) {
2229 Candidate.Viable = false;
2230 return;
2231 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002232 }
2233
2234 // Determine the implicit conversion sequences for each of the
2235 // arguments.
2236 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2237 if (ArgIdx < NumArgsInProto) {
2238 // (C++ 13.3.2p3): for F to be a viable function, there shall
2239 // exist for each argument an implicit conversion sequence
2240 // (13.3.3.1) that converts that argument to the corresponding
2241 // parameter of F.
2242 QualType ParamType = Proto->getArgType(ArgIdx);
2243 Candidate.Conversions[ArgIdx + 1]
2244 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002245 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002246 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2247 == ImplicitConversionSequence::BadConversion) {
2248 Candidate.Viable = false;
2249 break;
2250 }
2251 } else {
2252 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2253 // argument for which there is no corresponding parameter is
2254 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2255 Candidate.Conversions[ArgIdx + 1].ConversionKind
2256 = ImplicitConversionSequence::EllipsisConversion;
2257 }
2258 }
2259}
2260
Douglas Gregor60714f92008-11-07 22:36:19 +00002261/// AddConversionCandidate - Add a C++ conversion function as a
2262/// candidate in the candidate set (C++ [over.match.conv],
2263/// C++ [over.match.copy]). From is the expression we're converting from,
2264/// and ToType is the type that we're eventually trying to convert to
2265/// (which may or may not be the same type as the type that the
2266/// conversion function produces).
2267void
2268Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2269 Expr *From, QualType ToType,
2270 OverloadCandidateSet& CandidateSet) {
2271 // Add this candidate
2272 CandidateSet.push_back(OverloadCandidate());
2273 OverloadCandidate& Candidate = CandidateSet.back();
2274 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002275 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002276 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002277 Candidate.FinalConversion.setAsIdentityConversion();
2278 Candidate.FinalConversion.FromTypePtr
2279 = Conversion->getConversionType().getAsOpaquePtr();
2280 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2281
Douglas Gregor5ed15042008-11-18 23:14:02 +00002282 // Determine the implicit conversion sequence for the implicit
2283 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002284 Candidate.Viable = true;
2285 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002286 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002287
Douglas Gregor60714f92008-11-07 22:36:19 +00002288 if (Candidate.Conversions[0].ConversionKind
2289 == ImplicitConversionSequence::BadConversion) {
2290 Candidate.Viable = false;
2291 return;
2292 }
2293
2294 // To determine what the conversion from the result of calling the
2295 // conversion function to the type we're eventually trying to
2296 // convert to (ToType), we need to synthesize a call to the
2297 // conversion function and attempt copy initialization from it. This
2298 // makes sure that we get the right semantics with respect to
2299 // lvalues/rvalues and the type. Fortunately, we can allocate this
2300 // call on the stack and we don't need its arguments to be
2301 // well-formed.
2302 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2303 SourceLocation());
2304 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregor70d26122008-11-12 17:17:38 +00002305 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002306
2307 // Note that it is safe to allocate CallExpr on the stack here because
2308 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2309 // allocator).
2310 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002311 Conversion->getConversionType().getNonReferenceType(),
2312 SourceLocation());
2313 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2314 switch (ICS.ConversionKind) {
2315 case ImplicitConversionSequence::StandardConversion:
2316 Candidate.FinalConversion = ICS.Standard;
2317 break;
2318
2319 case ImplicitConversionSequence::BadConversion:
2320 Candidate.Viable = false;
2321 break;
2322
2323 default:
2324 assert(false &&
2325 "Can only end up with a standard conversion sequence or failure");
2326 }
2327}
2328
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002329/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2330/// converts the given @c Object to a function pointer via the
2331/// conversion function @c Conversion, and then attempts to call it
2332/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2333/// the type of function that we'll eventually be calling.
2334void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002335 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002336 Expr *Object, Expr **Args, unsigned NumArgs,
2337 OverloadCandidateSet& CandidateSet) {
2338 CandidateSet.push_back(OverloadCandidate());
2339 OverloadCandidate& Candidate = CandidateSet.back();
2340 Candidate.Function = 0;
2341 Candidate.Surrogate = Conversion;
2342 Candidate.Viable = true;
2343 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002344 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002345 Candidate.Conversions.resize(NumArgs + 1);
2346
2347 // Determine the implicit conversion sequence for the implicit
2348 // object parameter.
2349 ImplicitConversionSequence ObjectInit
2350 = TryObjectArgumentInitialization(Object, Conversion);
2351 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2352 Candidate.Viable = false;
2353 return;
2354 }
2355
2356 // The first conversion is actually a user-defined conversion whose
2357 // first conversion is ObjectInit's standard conversion (which is
2358 // effectively a reference binding). Record it as such.
2359 Candidate.Conversions[0].ConversionKind
2360 = ImplicitConversionSequence::UserDefinedConversion;
2361 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2362 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2363 Candidate.Conversions[0].UserDefined.After
2364 = Candidate.Conversions[0].UserDefined.Before;
2365 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2366
2367 // Find the
2368 unsigned NumArgsInProto = Proto->getNumArgs();
2369
2370 // (C++ 13.3.2p2): A candidate function having fewer than m
2371 // parameters is viable only if it has an ellipsis in its parameter
2372 // list (8.3.5).
2373 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2374 Candidate.Viable = false;
2375 return;
2376 }
2377
2378 // Function types don't have any default arguments, so just check if
2379 // we have enough arguments.
2380 if (NumArgs < NumArgsInProto) {
2381 // Not enough arguments.
2382 Candidate.Viable = false;
2383 return;
2384 }
2385
2386 // Determine the implicit conversion sequences for each of the
2387 // arguments.
2388 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2389 if (ArgIdx < NumArgsInProto) {
2390 // (C++ 13.3.2p3): for F to be a viable function, there shall
2391 // exist for each argument an implicit conversion sequence
2392 // (13.3.3.1) that converts that argument to the corresponding
2393 // parameter of F.
2394 QualType ParamType = Proto->getArgType(ArgIdx);
2395 Candidate.Conversions[ArgIdx + 1]
2396 = TryCopyInitialization(Args[ArgIdx], ParamType,
2397 /*SuppressUserConversions=*/false);
2398 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2399 == ImplicitConversionSequence::BadConversion) {
2400 Candidate.Viable = false;
2401 break;
2402 }
2403 } else {
2404 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2405 // argument for which there is no corresponding parameter is
2406 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2407 Candidate.Conversions[ArgIdx + 1].ConversionKind
2408 = ImplicitConversionSequence::EllipsisConversion;
2409 }
2410 }
2411}
2412
Mike Stumpe127ae32009-05-16 07:39:55 +00002413// FIXME: This will eventually be removed, once we've migrated all of the
2414// operator overloading logic over to the scheme used by binary operators, which
2415// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002416void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002417 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002418 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002419 OverloadCandidateSet& CandidateSet,
2420 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002421
2422 FunctionSet Functions;
2423
2424 QualType T1 = Args[0]->getType();
2425 QualType T2;
2426 if (NumArgs > 1)
2427 T2 = Args[1]->getType();
2428
2429 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002430 if (S)
2431 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002432 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2433 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2434 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2435 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2436}
2437
2438/// \brief Add overload candidates for overloaded operators that are
2439/// member functions.
2440///
2441/// Add the overloaded operator candidates that are member functions
2442/// for the operator Op that was used in an operator expression such
2443/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2444/// CandidateSet will store the added overload candidates. (C++
2445/// [over.match.oper]).
2446void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2447 SourceLocation OpLoc,
2448 Expr **Args, unsigned NumArgs,
2449 OverloadCandidateSet& CandidateSet,
2450 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002451 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2452
2453 // C++ [over.match.oper]p3:
2454 // For a unary operator @ with an operand of a type whose
2455 // cv-unqualified version is T1, and for a binary operator @ with
2456 // a left operand of a type whose cv-unqualified version is T1 and
2457 // a right operand of a type whose cv-unqualified version is T2,
2458 // three sets of candidate functions, designated member
2459 // candidates, non-member candidates and built-in candidates, are
2460 // constructed as follows:
2461 QualType T1 = Args[0]->getType();
2462 QualType T2;
2463 if (NumArgs > 1)
2464 T2 = Args[1]->getType();
2465
2466 // -- If T1 is a class type, the set of member candidates is the
2467 // result of the qualified lookup of T1::operator@
2468 // (13.3.1.1.1); otherwise, the set of member candidates is
2469 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002470 // FIXME: Lookup in base classes, too!
Douglas Gregor5ed15042008-11-18 23:14:02 +00002471 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002472 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002473 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002474 Oper != OperEnd; ++Oper)
2475 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2476 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002477 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002478 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002479}
2480
Douglas Gregor70d26122008-11-12 17:17:38 +00002481/// AddBuiltinCandidate - Add a candidate for a built-in
2482/// operator. ResultTy and ParamTys are the result and parameter types
2483/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002484/// arguments being passed to the candidate. IsAssignmentOperator
2485/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002486/// operator. NumContextualBoolArguments is the number of arguments
2487/// (at the beginning of the argument list) that will be contextually
2488/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002489void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2490 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002491 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002492 bool IsAssignmentOperator,
2493 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002494 // Add this candidate
2495 CandidateSet.push_back(OverloadCandidate());
2496 OverloadCandidate& Candidate = CandidateSet.back();
2497 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002498 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002499 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002500 Candidate.BuiltinTypes.ResultTy = ResultTy;
2501 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2502 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2503
2504 // Determine the implicit conversion sequences for each of the
2505 // arguments.
2506 Candidate.Viable = true;
2507 Candidate.Conversions.resize(NumArgs);
2508 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002509 // C++ [over.match.oper]p4:
2510 // For the built-in assignment operators, conversions of the
2511 // left operand are restricted as follows:
2512 // -- no temporaries are introduced to hold the left operand, and
2513 // -- no user-defined conversions are applied to the left
2514 // operand to achieve a type match with the left-most
2515 // parameter of a built-in candidate.
2516 //
2517 // We block these conversions by turning off user-defined
2518 // conversions, since that is the only way that initialization of
2519 // a reference to a non-class type can occur from something that
2520 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002521 if (ArgIdx < NumContextualBoolArguments) {
2522 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2523 "Contextual conversion to bool requires bool type");
2524 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2525 } else {
2526 Candidate.Conversions[ArgIdx]
2527 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2528 ArgIdx == 0 && IsAssignmentOperator);
2529 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002530 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002531 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002532 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002533 break;
2534 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002535 }
2536}
2537
2538/// BuiltinCandidateTypeSet - A set of types that will be used for the
2539/// candidate operator functions for built-in operators (C++
2540/// [over.built]). The types are separated into pointer types and
2541/// enumeration types.
2542class BuiltinCandidateTypeSet {
2543 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002544 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002545
2546 /// PointerTypes - The set of pointer types that will be used in the
2547 /// built-in candidates.
2548 TypeSet PointerTypes;
2549
Sebastian Redl674d1b72009-04-19 21:53:20 +00002550 /// MemberPointerTypes - The set of member pointer types that will be
2551 /// used in the built-in candidates.
2552 TypeSet MemberPointerTypes;
2553
Douglas Gregor70d26122008-11-12 17:17:38 +00002554 /// EnumerationTypes - The set of enumeration types that will be
2555 /// used in the built-in candidates.
2556 TypeSet EnumerationTypes;
2557
2558 /// Context - The AST context in which we will build the type sets.
2559 ASTContext &Context;
2560
Sebastian Redl674d1b72009-04-19 21:53:20 +00002561 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2562 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002563
2564public:
2565 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002566 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002567
2568 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2569
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002570 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2571 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002572
2573 /// pointer_begin - First pointer type found;
2574 iterator pointer_begin() { return PointerTypes.begin(); }
2575
Sebastian Redl674d1b72009-04-19 21:53:20 +00002576 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002577 iterator pointer_end() { return PointerTypes.end(); }
2578
Sebastian Redl674d1b72009-04-19 21:53:20 +00002579 /// member_pointer_begin - First member pointer type found;
2580 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2581
2582 /// member_pointer_end - Past the last member pointer type found;
2583 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2584
Douglas Gregor70d26122008-11-12 17:17:38 +00002585 /// enumeration_begin - First enumeration type found;
2586 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2587
Sebastian Redl674d1b72009-04-19 21:53:20 +00002588 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002589 iterator enumeration_end() { return EnumerationTypes.end(); }
2590};
2591
Sebastian Redl674d1b72009-04-19 21:53:20 +00002592/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002593/// the set of pointer types along with any more-qualified variants of
2594/// that type. For example, if @p Ty is "int const *", this routine
2595/// will add "int const *", "int const volatile *", "int const
2596/// restrict *", and "int const volatile restrict *" to the set of
2597/// pointer types. Returns true if the add of @p Ty itself succeeded,
2598/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002599bool
2600BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002601 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002602 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002603 return false;
2604
2605 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2606 QualType PointeeTy = PointerTy->getPointeeType();
2607 // FIXME: Optimize this so that we don't keep trying to add the same types.
2608
Mike Stumpe127ae32009-05-16 07:39:55 +00002609 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2610 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002611 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002612 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002613 (Context.getPointerType(PointeeTy.withConst()));
2614 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002615 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002616 (Context.getPointerType(PointeeTy.withVolatile()));
2617 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002618 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002619 (Context.getPointerType(PointeeTy.withRestrict()));
2620 }
2621
2622 return true;
2623}
2624
Sebastian Redl674d1b72009-04-19 21:53:20 +00002625/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2626/// to the set of pointer types along with any more-qualified variants of
2627/// that type. For example, if @p Ty is "int const *", this routine
2628/// will add "int const *", "int const volatile *", "int const
2629/// restrict *", and "int const volatile restrict *" to the set of
2630/// pointer types. Returns true if the add of @p Ty itself succeeded,
2631/// false otherwise.
2632bool
2633BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2634 QualType Ty) {
2635 // Insert this type.
2636 if (!MemberPointerTypes.insert(Ty))
2637 return false;
2638
2639 if (const MemberPointerType *PointerTy = Ty->getAsMemberPointerType()) {
2640 QualType PointeeTy = PointerTy->getPointeeType();
2641 const Type *ClassTy = PointerTy->getClass();
2642 // FIXME: Optimize this so that we don't keep trying to add the same types.
2643
2644 if (!PointeeTy.isConstQualified())
2645 AddMemberPointerWithMoreQualifiedTypeVariants
2646 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2647 if (!PointeeTy.isVolatileQualified())
2648 AddMemberPointerWithMoreQualifiedTypeVariants
2649 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2650 if (!PointeeTy.isRestrictQualified())
2651 AddMemberPointerWithMoreQualifiedTypeVariants
2652 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2653 }
2654
2655 return true;
2656}
2657
Douglas Gregor70d26122008-11-12 17:17:38 +00002658/// AddTypesConvertedFrom - Add each of the types to which the type @p
2659/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002660/// primarily interested in pointer types and enumeration types. We also
2661/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002662/// AllowUserConversions is true if we should look at the conversion
2663/// functions of a class type, and AllowExplicitConversions if we
2664/// should also include the explicit conversion functions of a class
2665/// type.
2666void
2667BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2668 bool AllowUserConversions,
2669 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002670 // Only deal with canonical types.
2671 Ty = Context.getCanonicalType(Ty);
2672
2673 // Look through reference types; they aren't part of the type of an
2674 // expression for the purposes of conversions.
2675 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2676 Ty = RefTy->getPointeeType();
2677
2678 // We don't care about qualifiers on the type.
2679 Ty = Ty.getUnqualifiedType();
2680
2681 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2682 QualType PointeeTy = PointerTy->getPointeeType();
2683
2684 // Insert our type, and its more-qualified variants, into the set
2685 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002686 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002687 return;
2688
2689 // Add 'cv void*' to our set of types.
2690 if (!Ty->isVoidType()) {
2691 QualType QualVoid
2692 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002693 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002694 }
2695
2696 // If this is a pointer to a class type, add pointers to its bases
2697 // (with the same level of cv-qualification as the original
2698 // derived class, of course).
2699 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2700 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2701 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2702 Base != ClassDecl->bases_end(); ++Base) {
2703 QualType BaseTy = Context.getCanonicalType(Base->getType());
2704 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2705
2706 // Add the pointer type, recursively, so that we get all of
2707 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002708 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002709 }
2710 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002711 } else if (Ty->isMemberPointerType()) {
2712 // Member pointers are far easier, since the pointee can't be converted.
2713 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2714 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002715 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002716 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002717 } else if (AllowUserConversions) {
2718 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2719 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2720 // FIXME: Visit conversion functions in the base classes, too.
2721 OverloadedFunctionDecl *Conversions
2722 = ClassDecl->getConversionFunctions();
2723 for (OverloadedFunctionDecl::function_iterator Func
2724 = Conversions->function_begin();
2725 Func != Conversions->function_end(); ++Func) {
2726 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002727 if (AllowExplicitConversions || !Conv->isExplicit())
2728 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002729 }
2730 }
2731 }
2732}
2733
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002734/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2735/// operator overloads to the candidate set (C++ [over.built]), based
2736/// on the operator @p Op and the arguments given. For example, if the
2737/// operator is a binary '+', this routine might add "int
2738/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002739void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002740Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2741 Expr **Args, unsigned NumArgs,
2742 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002743 // The set of "promoted arithmetic types", which are the arithmetic
2744 // types are that preserved by promotion (C++ [over.built]p2). Note
2745 // that the first few of these types are the promoted integral
2746 // types; these types need to be first.
2747 // FIXME: What about complex?
2748 const unsigned FirstIntegralType = 0;
2749 const unsigned LastIntegralType = 13;
2750 const unsigned FirstPromotedIntegralType = 7,
2751 LastPromotedIntegralType = 13;
2752 const unsigned FirstPromotedArithmeticType = 7,
2753 LastPromotedArithmeticType = 16;
2754 const unsigned NumArithmeticTypes = 16;
2755 QualType ArithmeticTypes[NumArithmeticTypes] = {
2756 Context.BoolTy, Context.CharTy, Context.WCharTy,
2757 Context.SignedCharTy, Context.ShortTy,
2758 Context.UnsignedCharTy, Context.UnsignedShortTy,
2759 Context.IntTy, Context.LongTy, Context.LongLongTy,
2760 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2761 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2762 };
2763
2764 // Find all of the types that the arguments can convert to, but only
2765 // if the operator we're looking at has built-in operator candidates
2766 // that make use of these types.
2767 BuiltinCandidateTypeSet CandidateTypes(Context);
2768 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2769 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002770 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002771 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002772 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00002773 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002774 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002775 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2776 true,
2777 (Op == OO_Exclaim ||
2778 Op == OO_AmpAmp ||
2779 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002780 }
2781
2782 bool isComparison = false;
2783 switch (Op) {
2784 case OO_None:
2785 case NUM_OVERLOADED_OPERATORS:
2786 assert(false && "Expected an overloaded operator");
2787 break;
2788
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002789 case OO_Star: // '*' is either unary or binary
2790 if (NumArgs == 1)
2791 goto UnaryStar;
2792 else
2793 goto BinaryStar;
2794 break;
2795
2796 case OO_Plus: // '+' is either unary or binary
2797 if (NumArgs == 1)
2798 goto UnaryPlus;
2799 else
2800 goto BinaryPlus;
2801 break;
2802
2803 case OO_Minus: // '-' is either unary or binary
2804 if (NumArgs == 1)
2805 goto UnaryMinus;
2806 else
2807 goto BinaryMinus;
2808 break;
2809
2810 case OO_Amp: // '&' is either unary or binary
2811 if (NumArgs == 1)
2812 goto UnaryAmp;
2813 else
2814 goto BinaryAmp;
2815
2816 case OO_PlusPlus:
2817 case OO_MinusMinus:
2818 // C++ [over.built]p3:
2819 //
2820 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2821 // is either volatile or empty, there exist candidate operator
2822 // functions of the form
2823 //
2824 // VQ T& operator++(VQ T&);
2825 // T operator++(VQ T&, int);
2826 //
2827 // C++ [over.built]p4:
2828 //
2829 // For every pair (T, VQ), where T is an arithmetic type other
2830 // than bool, and VQ is either volatile or empty, there exist
2831 // candidate operator functions of the form
2832 //
2833 // VQ T& operator--(VQ T&);
2834 // T operator--(VQ T&, int);
2835 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2836 Arith < NumArithmeticTypes; ++Arith) {
2837 QualType ArithTy = ArithmeticTypes[Arith];
2838 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00002839 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002840
2841 // Non-volatile version.
2842 if (NumArgs == 1)
2843 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2844 else
2845 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2846
2847 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00002848 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002849 if (NumArgs == 1)
2850 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2851 else
2852 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2853 }
2854
2855 // C++ [over.built]p5:
2856 //
2857 // For every pair (T, VQ), where T is a cv-qualified or
2858 // cv-unqualified object type, and VQ is either volatile or
2859 // empty, there exist candidate operator functions of the form
2860 //
2861 // T*VQ& operator++(T*VQ&);
2862 // T*VQ& operator--(T*VQ&);
2863 // T* operator++(T*VQ&, int);
2864 // T* operator--(T*VQ&, int);
2865 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2866 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2867 // Skip pointer types that aren't pointers to object types.
Douglas Gregor26ea1222009-03-24 20:32:41 +00002868 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002869 continue;
2870
2871 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002872 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002873 };
2874
2875 // Without volatile
2876 if (NumArgs == 1)
2877 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2878 else
2879 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2880
2881 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2882 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00002883 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002884 if (NumArgs == 1)
2885 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2886 else
2887 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2888 }
2889 }
2890 break;
2891
2892 UnaryStar:
2893 // C++ [over.built]p6:
2894 // For every cv-qualified or cv-unqualified object type T, there
2895 // exist candidate operator functions of the form
2896 //
2897 // T& operator*(T*);
2898 //
2899 // C++ [over.built]p7:
2900 // For every function type T, there exist candidate operator
2901 // functions of the form
2902 // T& operator*(T*);
2903 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2904 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2905 QualType ParamTy = *Ptr;
2906 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00002907 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002908 &ParamTy, Args, 1, CandidateSet);
2909 }
2910 break;
2911
2912 UnaryPlus:
2913 // C++ [over.built]p8:
2914 // For every type T, there exist candidate operator functions of
2915 // the form
2916 //
2917 // T* operator+(T*);
2918 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2919 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2920 QualType ParamTy = *Ptr;
2921 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2922 }
2923
2924 // Fall through
2925
2926 UnaryMinus:
2927 // C++ [over.built]p9:
2928 // For every promoted arithmetic type T, there exist candidate
2929 // operator functions of the form
2930 //
2931 // T operator+(T);
2932 // T operator-(T);
2933 for (unsigned Arith = FirstPromotedArithmeticType;
2934 Arith < LastPromotedArithmeticType; ++Arith) {
2935 QualType ArithTy = ArithmeticTypes[Arith];
2936 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2937 }
2938 break;
2939
2940 case OO_Tilde:
2941 // C++ [over.built]p10:
2942 // For every promoted integral type T, there exist candidate
2943 // operator functions of the form
2944 //
2945 // T operator~(T);
2946 for (unsigned Int = FirstPromotedIntegralType;
2947 Int < LastPromotedIntegralType; ++Int) {
2948 QualType IntTy = ArithmeticTypes[Int];
2949 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2950 }
2951 break;
2952
Douglas Gregor70d26122008-11-12 17:17:38 +00002953 case OO_New:
2954 case OO_Delete:
2955 case OO_Array_New:
2956 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00002957 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002958 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00002959 break;
2960
2961 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002962 UnaryAmp:
2963 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00002964 // C++ [over.match.oper]p3:
2965 // -- For the operator ',', the unary operator '&', or the
2966 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00002967 break;
2968
2969 case OO_Less:
2970 case OO_Greater:
2971 case OO_LessEqual:
2972 case OO_GreaterEqual:
2973 case OO_EqualEqual:
2974 case OO_ExclaimEqual:
2975 // C++ [over.built]p15:
2976 //
2977 // For every pointer or enumeration type T, there exist
2978 // candidate operator functions of the form
2979 //
2980 // bool operator<(T, T);
2981 // bool operator>(T, T);
2982 // bool operator<=(T, T);
2983 // bool operator>=(T, T);
2984 // bool operator==(T, T);
2985 // bool operator!=(T, T);
2986 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2987 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2988 QualType ParamTypes[2] = { *Ptr, *Ptr };
2989 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2990 }
2991 for (BuiltinCandidateTypeSet::iterator Enum
2992 = CandidateTypes.enumeration_begin();
2993 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2994 QualType ParamTypes[2] = { *Enum, *Enum };
2995 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2996 }
2997
2998 // Fall through.
2999 isComparison = true;
3000
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003001 BinaryPlus:
3002 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003003 if (!isComparison) {
3004 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3005
3006 // C++ [over.built]p13:
3007 //
3008 // For every cv-qualified or cv-unqualified object type T
3009 // there exist candidate operator functions of the form
3010 //
3011 // T* operator+(T*, ptrdiff_t);
3012 // T& operator[](T*, ptrdiff_t); [BELOW]
3013 // T* operator-(T*, ptrdiff_t);
3014 // T* operator+(ptrdiff_t, T*);
3015 // T& operator[](ptrdiff_t, T*); [BELOW]
3016 //
3017 // C++ [over.built]p14:
3018 //
3019 // For every T, where T is a pointer to object type, there
3020 // exist candidate operator functions of the form
3021 //
3022 // ptrdiff_t operator-(T, T);
3023 for (BuiltinCandidateTypeSet::iterator Ptr
3024 = CandidateTypes.pointer_begin();
3025 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3026 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3027
3028 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3029 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3030
3031 if (Op == OO_Plus) {
3032 // T* operator+(ptrdiff_t, T*);
3033 ParamTypes[0] = ParamTypes[1];
3034 ParamTypes[1] = *Ptr;
3035 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3036 } else {
3037 // ptrdiff_t operator-(T, T);
3038 ParamTypes[1] = *Ptr;
3039 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3040 Args, 2, CandidateSet);
3041 }
3042 }
3043 }
3044 // Fall through
3045
Douglas Gregor70d26122008-11-12 17:17:38 +00003046 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003047 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003048 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003049 // C++ [over.built]p12:
3050 //
3051 // For every pair of promoted arithmetic types L and R, there
3052 // exist candidate operator functions of the form
3053 //
3054 // LR operator*(L, R);
3055 // LR operator/(L, R);
3056 // LR operator+(L, R);
3057 // LR operator-(L, R);
3058 // bool operator<(L, R);
3059 // bool operator>(L, R);
3060 // bool operator<=(L, R);
3061 // bool operator>=(L, R);
3062 // bool operator==(L, R);
3063 // bool operator!=(L, R);
3064 //
3065 // where LR is the result of the usual arithmetic conversions
3066 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003067 //
3068 // C++ [over.built]p24:
3069 //
3070 // For every pair of promoted arithmetic types L and R, there exist
3071 // candidate operator functions of the form
3072 //
3073 // LR operator?(bool, L, R);
3074 //
3075 // where LR is the result of the usual arithmetic conversions
3076 // between types L and R.
3077 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003078 for (unsigned Left = FirstPromotedArithmeticType;
3079 Left < LastPromotedArithmeticType; ++Left) {
3080 for (unsigned Right = FirstPromotedArithmeticType;
3081 Right < LastPromotedArithmeticType; ++Right) {
3082 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3083 QualType Result
3084 = isComparison? Context.BoolTy
3085 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3086 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3087 }
3088 }
3089 break;
3090
3091 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003092 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003093 case OO_Caret:
3094 case OO_Pipe:
3095 case OO_LessLess:
3096 case OO_GreaterGreater:
3097 // C++ [over.built]p17:
3098 //
3099 // For every pair of promoted integral types L and R, there
3100 // exist candidate operator functions of the form
3101 //
3102 // LR operator%(L, R);
3103 // LR operator&(L, R);
3104 // LR operator^(L, R);
3105 // LR operator|(L, R);
3106 // L operator<<(L, R);
3107 // L operator>>(L, R);
3108 //
3109 // where LR is the result of the usual arithmetic conversions
3110 // between types L and R.
3111 for (unsigned Left = FirstPromotedIntegralType;
3112 Left < LastPromotedIntegralType; ++Left) {
3113 for (unsigned Right = FirstPromotedIntegralType;
3114 Right < LastPromotedIntegralType; ++Right) {
3115 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3116 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3117 ? LandR[0]
3118 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3119 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3120 }
3121 }
3122 break;
3123
3124 case OO_Equal:
3125 // C++ [over.built]p20:
3126 //
3127 // For every pair (T, VQ), where T is an enumeration or
3128 // (FIXME:) pointer to member type and VQ is either volatile or
3129 // empty, there exist candidate operator functions of the form
3130 //
3131 // VQ T& operator=(VQ T&, T);
3132 for (BuiltinCandidateTypeSet::iterator Enum
3133 = CandidateTypes.enumeration_begin();
3134 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3135 QualType ParamTypes[2];
3136
3137 // T& operator=(T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003138 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregor70d26122008-11-12 17:17:38 +00003139 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003140 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003141 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003142
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003143 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3144 // volatile T& operator=(volatile T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003145 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003146 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003147 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003148 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003149 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003150 }
3151 // Fall through.
3152
3153 case OO_PlusEqual:
3154 case OO_MinusEqual:
3155 // C++ [over.built]p19:
3156 //
3157 // For every pair (T, VQ), where T is any type and VQ is either
3158 // volatile or empty, there exist candidate operator functions
3159 // of the form
3160 //
3161 // T*VQ& operator=(T*VQ&, T*);
3162 //
3163 // C++ [over.built]p21:
3164 //
3165 // For every pair (T, VQ), where T is a cv-qualified or
3166 // cv-unqualified object type and VQ is either volatile or
3167 // empty, there exist candidate operator functions of the form
3168 //
3169 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3170 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3171 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3172 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3173 QualType ParamTypes[2];
3174 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3175
3176 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003177 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003178 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3179 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003180
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003181 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3182 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003183 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003184 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3185 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003186 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003187 }
3188 // Fall through.
3189
3190 case OO_StarEqual:
3191 case OO_SlashEqual:
3192 // C++ [over.built]p18:
3193 //
3194 // For every triple (L, VQ, R), where L is an arithmetic type,
3195 // VQ is either volatile or empty, and R is a promoted
3196 // arithmetic type, there exist candidate operator functions of
3197 // the form
3198 //
3199 // VQ L& operator=(VQ L&, R);
3200 // VQ L& operator*=(VQ L&, R);
3201 // VQ L& operator/=(VQ L&, R);
3202 // VQ L& operator+=(VQ L&, R);
3203 // VQ L& operator-=(VQ L&, R);
3204 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3205 for (unsigned Right = FirstPromotedArithmeticType;
3206 Right < LastPromotedArithmeticType; ++Right) {
3207 QualType ParamTypes[2];
3208 ParamTypes[1] = ArithmeticTypes[Right];
3209
3210 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003211 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003212 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3213 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003214
3215 // Add this built-in operator as a candidate (VQ is 'volatile').
3216 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003217 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003218 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3219 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003220 }
3221 }
3222 break;
3223
3224 case OO_PercentEqual:
3225 case OO_LessLessEqual:
3226 case OO_GreaterGreaterEqual:
3227 case OO_AmpEqual:
3228 case OO_CaretEqual:
3229 case OO_PipeEqual:
3230 // C++ [over.built]p22:
3231 //
3232 // For every triple (L, VQ, R), where L is an integral type, VQ
3233 // is either volatile or empty, and R is a promoted integral
3234 // type, there exist candidate operator functions of the form
3235 //
3236 // VQ L& operator%=(VQ L&, R);
3237 // VQ L& operator<<=(VQ L&, R);
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 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3243 for (unsigned Right = FirstPromotedIntegralType;
3244 Right < LastPromotedIntegralType; ++Right) {
3245 QualType ParamTypes[2];
3246 ParamTypes[1] = ArithmeticTypes[Right];
3247
3248 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003249 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003250 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3251
3252 // Add this built-in operator as a candidate (VQ is 'volatile').
3253 ParamTypes[0] = ArithmeticTypes[Left];
3254 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003255 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003256 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3257 }
3258 }
3259 break;
3260
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003261 case OO_Exclaim: {
3262 // C++ [over.operator]p23:
3263 //
3264 // There also exist candidate operator functions of the form
3265 //
3266 // bool operator!(bool);
3267 // bool operator&&(bool, bool); [BELOW]
3268 // bool operator||(bool, bool); [BELOW]
3269 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003270 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3271 /*IsAssignmentOperator=*/false,
3272 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003273 break;
3274 }
3275
Douglas Gregor70d26122008-11-12 17:17:38 +00003276 case OO_AmpAmp:
3277 case OO_PipePipe: {
3278 // C++ [over.operator]p23:
3279 //
3280 // There also exist candidate operator functions of the form
3281 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003282 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003283 // bool operator&&(bool, bool);
3284 // bool operator||(bool, bool);
3285 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003286 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3287 /*IsAssignmentOperator=*/false,
3288 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003289 break;
3290 }
3291
3292 case OO_Subscript:
3293 // C++ [over.built]p13:
3294 //
3295 // For every cv-qualified or cv-unqualified object type T there
3296 // exist candidate operator functions of the form
3297 //
3298 // T* operator+(T*, ptrdiff_t); [ABOVE]
3299 // T& operator[](T*, ptrdiff_t);
3300 // T* operator-(T*, ptrdiff_t); [ABOVE]
3301 // T* operator+(ptrdiff_t, T*); [ABOVE]
3302 // T& operator[](ptrdiff_t, T*);
3303 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3304 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3305 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3306 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003307 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003308
3309 // T& operator[](T*, ptrdiff_t)
3310 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3311
3312 // T& operator[](ptrdiff_t, T*);
3313 ParamTypes[0] = ParamTypes[1];
3314 ParamTypes[1] = *Ptr;
3315 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3316 }
3317 break;
3318
3319 case OO_ArrowStar:
3320 // FIXME: No support for pointer-to-members yet.
3321 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003322
3323 case OO_Conditional:
3324 // Note that we don't consider the first argument, since it has been
3325 // contextually converted to bool long ago. The candidates below are
3326 // therefore added as binary.
3327 //
3328 // C++ [over.built]p24:
3329 // For every type T, where T is a pointer or pointer-to-member type,
3330 // there exist candidate operator functions of the form
3331 //
3332 // T operator?(bool, T, T);
3333 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003334 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3335 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3336 QualType ParamTypes[2] = { *Ptr, *Ptr };
3337 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3338 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003339 for (BuiltinCandidateTypeSet::iterator Ptr =
3340 CandidateTypes.member_pointer_begin(),
3341 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3342 QualType ParamTypes[2] = { *Ptr, *Ptr };
3343 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3344 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003345 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003346 }
3347}
3348
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003349/// \brief Add function candidates found via argument-dependent lookup
3350/// to the set of overloading candidates.
3351///
3352/// This routine performs argument-dependent name lookup based on the
3353/// given function name (which may also be an operator name) and adds
3354/// all of the overload candidates found by ADL to the overload
3355/// candidate set (C++ [basic.lookup.argdep]).
3356void
3357Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3358 Expr **Args, unsigned NumArgs,
3359 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003360 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003361
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003362 // Record all of the function candidates that we've already
3363 // added to the overload set, so that we don't add those same
3364 // candidates a second time.
3365 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3366 CandEnd = CandidateSet.end();
3367 Cand != CandEnd; ++Cand)
3368 if (Cand->Function)
3369 Functions.insert(Cand->Function);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003370
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003371 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003372
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003373 // Erase all of the candidates we already knew about.
3374 // FIXME: This is suboptimal. Is there a better way?
3375 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3376 CandEnd = CandidateSet.end();
3377 Cand != CandEnd; ++Cand)
3378 if (Cand->Function)
3379 Functions.erase(Cand->Function);
3380
3381 // For each of the ADL candidates we found, add it to the overload
3382 // set.
3383 for (FunctionSet::iterator Func = Functions.begin(),
3384 FuncEnd = Functions.end();
3385 Func != FuncEnd; ++Func)
3386 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003387}
3388
Douglas Gregord2baafd2008-10-21 16:13:35 +00003389/// isBetterOverloadCandidate - Determines whether the first overload
3390/// candidate is a better candidate than the second (C++ 13.3.3p1).
3391bool
3392Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3393 const OverloadCandidate& Cand2)
3394{
3395 // Define viable functions to be better candidates than non-viable
3396 // functions.
3397 if (!Cand2.Viable)
3398 return Cand1.Viable;
3399 else if (!Cand1.Viable)
3400 return false;
3401
Douglas Gregor3257fb52008-12-22 05:46:06 +00003402 // C++ [over.match.best]p1:
3403 //
3404 // -- if F is a static member function, ICS1(F) is defined such
3405 // that ICS1(F) is neither better nor worse than ICS1(G) for
3406 // any function G, and, symmetrically, ICS1(G) is neither
3407 // better nor worse than ICS1(F).
3408 unsigned StartArg = 0;
3409 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3410 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003411
3412 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3413 // function than another viable function F2 if for all arguments i,
3414 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3415 // then...
3416 unsigned NumArgs = Cand1.Conversions.size();
3417 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3418 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003419 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003420 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3421 Cand2.Conversions[ArgIdx])) {
3422 case ImplicitConversionSequence::Better:
3423 // Cand1 has a better conversion sequence.
3424 HasBetterConversion = true;
3425 break;
3426
3427 case ImplicitConversionSequence::Worse:
3428 // Cand1 can't be better than Cand2.
3429 return false;
3430
3431 case ImplicitConversionSequence::Indistinguishable:
3432 // Do nothing.
3433 break;
3434 }
3435 }
3436
3437 if (HasBetterConversion)
3438 return true;
3439
Douglas Gregor70d26122008-11-12 17:17:38 +00003440 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3441 // implemented, but they require template support.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003442
Douglas Gregor60714f92008-11-07 22:36:19 +00003443 // C++ [over.match.best]p1b4:
3444 //
3445 // -- the context is an initialization by user-defined conversion
3446 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3447 // from the return type of F1 to the destination type (i.e.,
3448 // the type of the entity being initialized) is a better
3449 // conversion sequence than the standard conversion sequence
3450 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003451 if (Cand1.Function && Cand2.Function &&
3452 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003453 isa<CXXConversionDecl>(Cand2.Function)) {
3454 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3455 Cand2.FinalConversion)) {
3456 case ImplicitConversionSequence::Better:
3457 // Cand1 has a better conversion sequence.
3458 return true;
3459
3460 case ImplicitConversionSequence::Worse:
3461 // Cand1 can't be better than Cand2.
3462 return false;
3463
3464 case ImplicitConversionSequence::Indistinguishable:
3465 // Do nothing
3466 break;
3467 }
3468 }
3469
Douglas Gregord2baafd2008-10-21 16:13:35 +00003470 return false;
3471}
3472
Douglas Gregor98189262009-06-19 23:52:42 +00003473/// \brief Computes the best viable function (C++ 13.3.3)
3474/// within an overload candidate set.
3475///
3476/// \param CandidateSet the set of candidate functions.
3477///
3478/// \param Loc the location of the function name (or operator symbol) for
3479/// which overload resolution occurs.
3480///
3481/// \param Best f overload resolution was successful or found a deleted
3482/// function, Best points to the candidate function found.
3483///
3484/// \returns The result of overload resolution.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003485Sema::OverloadingResult
3486Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003487 SourceLocation Loc,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003488 OverloadCandidateSet::iterator& Best)
3489{
3490 // Find the best viable function.
3491 Best = CandidateSet.end();
3492 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3493 Cand != CandidateSet.end(); ++Cand) {
3494 if (Cand->Viable) {
3495 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3496 Best = Cand;
3497 }
3498 }
3499
3500 // If we didn't find any viable functions, abort.
3501 if (Best == CandidateSet.end())
3502 return OR_No_Viable_Function;
3503
3504 // Make sure that this function is better than every other viable
3505 // function. If not, we have an ambiguity.
3506 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3507 Cand != CandidateSet.end(); ++Cand) {
3508 if (Cand->Viable &&
3509 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003510 !isBetterOverloadCandidate(*Best, *Cand)) {
3511 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003512 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003513 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003514 }
3515
3516 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003517 if (Best->Function &&
3518 (Best->Function->isDeleted() ||
Douglas Gregor98da6ae2009-06-18 16:11:24 +00003519 Best->Function->getAttr<UnavailableAttr>(Context)))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003520 return OR_Deleted;
3521
Douglas Gregor98189262009-06-19 23:52:42 +00003522 // C++ [basic.def.odr]p2:
3523 // An overloaded function is used if it is selected by overload resolution
3524 // when referred to from a potentially-evaluated expression. [Note: this
3525 // covers calls to named functions (5.2.2), operator overloading
3526 // (clause 13), user-defined conversions (12.3.2), allocation function for
3527 // placement new (5.3.4), as well as non-default initialization (8.5).
3528 if (Best->Function)
3529 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003530 return OR_Success;
3531}
3532
3533/// PrintOverloadCandidates - When overload resolution fails, prints
3534/// diagnostic messages containing the candidates in the candidate
3535/// set. If OnlyViable is true, only viable candidates will be printed.
3536void
3537Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3538 bool OnlyViable)
3539{
3540 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3541 LastCand = CandidateSet.end();
3542 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003543 if (Cand->Viable || !OnlyViable) {
3544 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003545 if (Cand->Function->isDeleted() ||
Douglas Gregor98da6ae2009-06-18 16:11:24 +00003546 Cand->Function->getAttr<UnavailableAttr>(Context)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003547 // Deleted or "unavailable" function.
3548 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3549 << Cand->Function->isDeleted();
3550 } else {
3551 // Normal function
3552 // FIXME: Give a better reason!
3553 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3554 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003555 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003556 // Desugar the type of the surrogate down to a function type,
3557 // retaining as many typedefs as possible while still showing
3558 // the function type (and, therefore, its parameter types).
3559 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003560 bool isLValueReference = false;
3561 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003562 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003563 if (const LValueReferenceType *FnTypeRef =
3564 FnType->getAsLValueReferenceType()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003565 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003566 isLValueReference = true;
3567 } else if (const RValueReferenceType *FnTypeRef =
3568 FnType->getAsRValueReferenceType()) {
3569 FnType = FnTypeRef->getPointeeType();
3570 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003571 }
3572 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3573 FnType = FnTypePtr->getPointeeType();
3574 isPointer = true;
3575 }
3576 // Desugar down to a function type.
3577 FnType = QualType(FnType->getAsFunctionType(), 0);
3578 // Reconstruct the pointer/reference as appropriate.
3579 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003580 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3581 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003582
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003583 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003584 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003585 } else {
3586 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003587 // FIXME: Do we want the error message to point at the operator?
3588 // (built-ins won't have a location)
Douglas Gregor70d26122008-11-12 17:17:38 +00003589 QualType FnType
3590 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3591 Cand->BuiltinTypes.ParamTypes,
3592 Cand->Conversions.size(),
3593 false, 0);
3594
Chris Lattner4bfd2232008-11-24 06:25:27 +00003595 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003596 }
3597 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003598 }
3599}
3600
Douglas Gregor45014fd2008-11-10 20:40:00 +00003601/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3602/// an overloaded function (C++ [over.over]), where @p From is an
3603/// expression with overloaded function type and @p ToType is the type
3604/// we're trying to resolve to. For example:
3605///
3606/// @code
3607/// int f(double);
3608/// int f(int);
3609///
3610/// int (*pfd)(double) = f; // selects f(double)
3611/// @endcode
3612///
3613/// This routine returns the resulting FunctionDecl if it could be
3614/// resolved, and NULL otherwise. When @p Complain is true, this
3615/// routine will emit diagnostics if there is an error.
3616FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003617Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003618 bool Complain) {
3619 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003620 bool IsMember = false;
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003621 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003622 FunctionType = ToTypePtr->getPointeeType();
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003623 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3624 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003625 else if (const MemberPointerType *MemTypePtr =
3626 ToType->getAsMemberPointerType()) {
3627 FunctionType = MemTypePtr->getPointeeType();
3628 IsMember = true;
3629 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003630
3631 // We only look at pointers or references to functions.
3632 if (!FunctionType->isFunctionType())
3633 return 0;
3634
3635 // Find the actual overloaded function declaration.
3636 OverloadedFunctionDecl *Ovl = 0;
3637
3638 // C++ [over.over]p1:
3639 // [...] [Note: any redundant set of parentheses surrounding the
3640 // overloaded function name is ignored (5.1). ]
3641 Expr *OvlExpr = From->IgnoreParens();
3642
3643 // C++ [over.over]p1:
3644 // [...] The overloaded function name can be preceded by the &
3645 // operator.
3646 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3647 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3648 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3649 }
3650
3651 // Try to dig out the overloaded function.
3652 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3653 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3654
3655 // If there's no overloaded function declaration, we're done.
3656 if (!Ovl)
3657 return 0;
3658
3659 // Look through all of the overloaded functions, searching for one
3660 // whose type matches exactly.
3661 // FIXME: When templates or using declarations come along, we'll actually
3662 // have to deal with duplicates, partial ordering, etc. For now, we
3663 // can just do a simple search.
3664 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3665 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3666 Fun != Ovl->function_end(); ++Fun) {
3667 // C++ [over.over]p3:
3668 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003669 // targets of type "pointer-to-function" or "reference-to-function."
3670 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003671 // type "pointer-to-member-function."
3672 // Note that according to DR 247, the containing class does not matter.
3673 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3674 // Skip non-static functions when converting to pointer, and static
3675 // when converting to member pointer.
3676 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003677 continue;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003678 } else if (IsMember)
3679 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003680
3681 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3682 return *Fun;
3683 }
3684
3685 return 0;
3686}
3687
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003688/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003689/// (which eventually refers to the declaration Func) and the call
3690/// arguments Args/NumArgs, attempt to resolve the function call down
3691/// to a specific function. If overload resolution succeeds, returns
3692/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003693/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003694/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003695FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003696 DeclarationName UnqualifiedName,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003697 SourceLocation LParenLoc,
3698 Expr **Args, unsigned NumArgs,
3699 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003700 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003701 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003702 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003703
3704 // Add the functions denoted by Callee to the set of candidate
3705 // functions. While we're doing so, track whether argument-dependent
3706 // lookup still applies, per:
3707 //
3708 // C++0x [basic.lookup.argdep]p3:
3709 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3710 // and let Y be the lookup set produced by argument dependent
3711 // lookup (defined as follows). If X contains
3712 //
3713 // -- a declaration of a class member, or
3714 //
3715 // -- a block-scope function declaration that is not a
3716 // using-declaration, or
3717 //
3718 // -- a declaration that is neither a function or a function
3719 // template
3720 //
3721 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003722 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003723 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3724 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3725 FuncEnd = Ovl->function_end();
3726 Func != FuncEnd; ++Func) {
3727 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3728
3729 if ((*Func)->getDeclContext()->isRecord() ||
3730 (*Func)->getDeclContext()->isFunctionOrMethod())
3731 ArgumentDependentLookup = false;
3732 }
3733 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3734 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3735
3736 if (Func->getDeclContext()->isRecord() ||
3737 Func->getDeclContext()->isFunctionOrMethod())
3738 ArgumentDependentLookup = false;
3739 }
3740
3741 if (Callee)
3742 UnqualifiedName = Callee->getDeclName();
3743
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003744 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003745 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003746 CandidateSet);
3747
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003748 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00003749 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003750 case OR_Success:
3751 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003752
3753 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00003754 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003755 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00003756 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003757 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3758 break;
3759
3760 case OR_Ambiguous:
3761 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003762 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003763 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3764 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00003765
3766 case OR_Deleted:
3767 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3768 << Best->Function->isDeleted()
3769 << UnqualifiedName
3770 << Fn->getSourceRange();
3771 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3772 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003773 }
3774
3775 // Overload resolution failed. Destroy all of the subexpressions and
3776 // return NULL.
3777 Fn->Destroy(Context);
3778 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3779 Args[Arg]->Destroy(Context);
3780 return 0;
3781}
3782
Douglas Gregorc78182d2009-03-13 23:49:33 +00003783/// \brief Create a unary operation that may resolve to an overloaded
3784/// operator.
3785///
3786/// \param OpLoc The location of the operator itself (e.g., '*').
3787///
3788/// \param OpcIn The UnaryOperator::Opcode that describes this
3789/// operator.
3790///
3791/// \param Functions The set of non-member functions that will be
3792/// considered by overload resolution. The caller needs to build this
3793/// set based on the context using, e.g.,
3794/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3795/// set should not contain any member functions; those will be added
3796/// by CreateOverloadedUnaryOp().
3797///
3798/// \param input The input argument.
3799Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3800 unsigned OpcIn,
3801 FunctionSet &Functions,
3802 ExprArg input) {
3803 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3804 Expr *Input = (Expr *)input.get();
3805
3806 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3807 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3808 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3809
3810 Expr *Args[2] = { Input, 0 };
3811 unsigned NumArgs = 1;
3812
3813 // For post-increment and post-decrement, add the implicit '0' as
3814 // the second argument, so that we know this is a post-increment or
3815 // post-decrement.
3816 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3817 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3818 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3819 SourceLocation());
3820 NumArgs = 2;
3821 }
3822
3823 if (Input->isTypeDependent()) {
3824 OverloadedFunctionDecl *Overloads
3825 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3826 for (FunctionSet::iterator Func = Functions.begin(),
3827 FuncEnd = Functions.end();
3828 Func != FuncEnd; ++Func)
3829 Overloads->addOverload(*Func);
3830
3831 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3832 OpLoc, false, false);
3833
3834 input.release();
3835 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3836 &Args[0], NumArgs,
3837 Context.DependentTy,
3838 OpLoc));
3839 }
3840
3841 // Build an empty overload set.
3842 OverloadCandidateSet CandidateSet;
3843
3844 // Add the candidates from the given function set.
3845 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3846
3847 // Add operator candidates that are member functions.
3848 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3849
3850 // Add builtin operator candidates.
3851 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3852
3853 // Perform overload resolution.
3854 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00003855 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00003856 case OR_Success: {
3857 // We found a built-in operator or an overloaded operator.
3858 FunctionDecl *FnDecl = Best->Function;
3859
3860 if (FnDecl) {
3861 // We matched an overloaded operator. Build a call to that
3862 // operator.
3863
3864 // Convert the arguments.
3865 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3866 if (PerformObjectArgumentInitialization(Input, Method))
3867 return ExprError();
3868 } else {
3869 // Convert the arguments.
3870 if (PerformCopyInitialization(Input,
3871 FnDecl->getParamDecl(0)->getType(),
3872 "passing"))
3873 return ExprError();
3874 }
3875
3876 // Determine the result type
3877 QualType ResultTy
3878 = FnDecl->getType()->getAsFunctionType()->getResultType();
3879 ResultTy = ResultTy.getNonReferenceType();
3880
3881 // Build the actual expression node.
3882 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3883 SourceLocation());
3884 UsualUnaryConversions(FnExpr);
3885
3886 input.release();
3887 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3888 &Input, 1, ResultTy,
3889 OpLoc));
3890 } else {
3891 // We matched a built-in operator. Convert the arguments, then
3892 // break out so that we will build the appropriate built-in
3893 // operator node.
3894 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3895 Best->Conversions[0], "passing"))
3896 return ExprError();
3897
3898 break;
3899 }
3900 }
3901
3902 case OR_No_Viable_Function:
3903 // No viable function; fall through to handling this as a
3904 // built-in operator, which will produce an error message for us.
3905 break;
3906
3907 case OR_Ambiguous:
3908 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3909 << UnaryOperator::getOpcodeStr(Opc)
3910 << Input->getSourceRange();
3911 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3912 return ExprError();
3913
3914 case OR_Deleted:
3915 Diag(OpLoc, diag::err_ovl_deleted_oper)
3916 << Best->Function->isDeleted()
3917 << UnaryOperator::getOpcodeStr(Opc)
3918 << Input->getSourceRange();
3919 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3920 return ExprError();
3921 }
3922
3923 // Either we found no viable overloaded operator or we matched a
3924 // built-in operator. In either case, fall through to trying to
3925 // build a built-in operation.
3926 input.release();
3927 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
3928}
3929
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003930/// \brief Create a binary operation that may resolve to an overloaded
3931/// operator.
3932///
3933/// \param OpLoc The location of the operator itself (e.g., '+').
3934///
3935/// \param OpcIn The BinaryOperator::Opcode that describes this
3936/// operator.
3937///
3938/// \param Functions The set of non-member functions that will be
3939/// considered by overload resolution. The caller needs to build this
3940/// set based on the context using, e.g.,
3941/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3942/// set should not contain any member functions; those will be added
3943/// by CreateOverloadedBinOp().
3944///
3945/// \param LHS Left-hand argument.
3946/// \param RHS Right-hand argument.
3947Sema::OwningExprResult
3948Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
3949 unsigned OpcIn,
3950 FunctionSet &Functions,
3951 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003952 Expr *Args[2] = { LHS, RHS };
3953
3954 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
3955 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
3956 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3957
3958 // If either side is type-dependent, create an appropriate dependent
3959 // expression.
3960 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
3961 // .* cannot be overloaded.
3962 if (Opc == BinaryOperator::PtrMemD)
3963 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
3964 Context.DependentTy, OpLoc));
3965
3966 OverloadedFunctionDecl *Overloads
3967 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3968 for (FunctionSet::iterator Func = Functions.begin(),
3969 FuncEnd = Functions.end();
3970 Func != FuncEnd; ++Func)
3971 Overloads->addOverload(*Func);
3972
3973 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3974 OpLoc, false, false);
3975
3976 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3977 Args, 2,
3978 Context.DependentTy,
3979 OpLoc));
3980 }
3981
3982 // If this is the .* operator, which is not overloadable, just
3983 // create a built-in binary operator.
3984 if (Opc == BinaryOperator::PtrMemD)
3985 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3986
3987 // If this is one of the assignment operators, we only perform
3988 // overload resolution if the left-hand side is a class or
3989 // enumeration type (C++ [expr.ass]p3).
3990 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3991 !LHS->getType()->isOverloadableType())
3992 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3993
Douglas Gregorc78182d2009-03-13 23:49:33 +00003994 // Build an empty overload set.
3995 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003996
3997 // Add the candidates from the given function set.
3998 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
3999
4000 // Add operator candidates that are member functions.
4001 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4002
4003 // Add builtin operator candidates.
4004 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4005
4006 // Perform overload resolution.
4007 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004008 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004009 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004010 // We found a built-in operator or an overloaded operator.
4011 FunctionDecl *FnDecl = Best->Function;
4012
4013 if (FnDecl) {
4014 // We matched an overloaded operator. Build a call to that
4015 // operator.
4016
4017 // Convert the arguments.
4018 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4019 if (PerformObjectArgumentInitialization(LHS, Method) ||
4020 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
4021 "passing"))
4022 return ExprError();
4023 } else {
4024 // Convert the arguments.
4025 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
4026 "passing") ||
4027 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
4028 "passing"))
4029 return ExprError();
4030 }
4031
4032 // Determine the result type
4033 QualType ResultTy
4034 = FnDecl->getType()->getAsFunctionType()->getResultType();
4035 ResultTy = ResultTy.getNonReferenceType();
4036
4037 // Build the actual expression node.
4038 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4039 SourceLocation());
4040 UsualUnaryConversions(FnExpr);
4041
4042 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4043 Args, 2, ResultTy,
4044 OpLoc));
4045 } else {
4046 // We matched a built-in operator. Convert the arguments, then
4047 // break out so that we will build the appropriate built-in
4048 // operator node.
4049 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4050 Best->Conversions[0], "passing") ||
4051 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4052 Best->Conversions[1], "passing"))
4053 return ExprError();
4054
4055 break;
4056 }
4057 }
4058
4059 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004060 // For class as left operand for assignment or compound assigment operator
4061 // do not fall through to handling in built-in, but report that no overloaded
4062 // assignment operator found
4063 if (LHS->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4064 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4065 << BinaryOperator::getOpcodeStr(Opc)
4066 << LHS->getSourceRange() << RHS->getSourceRange();
4067 return ExprError();
4068 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004069 // No viable function; fall through to handling this as a
4070 // built-in operator, which will produce an error message for us.
4071 break;
4072
4073 case OR_Ambiguous:
4074 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4075 << BinaryOperator::getOpcodeStr(Opc)
4076 << LHS->getSourceRange() << RHS->getSourceRange();
4077 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4078 return ExprError();
4079
4080 case OR_Deleted:
4081 Diag(OpLoc, diag::err_ovl_deleted_oper)
4082 << Best->Function->isDeleted()
4083 << BinaryOperator::getOpcodeStr(Opc)
4084 << LHS->getSourceRange() << RHS->getSourceRange();
4085 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4086 return ExprError();
4087 }
4088
4089 // Either we found no viable overloaded operator or we matched a
4090 // built-in operator. In either case, try to build a built-in
4091 // operation.
4092 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4093}
4094
Douglas Gregor3257fb52008-12-22 05:46:06 +00004095/// BuildCallToMemberFunction - Build a call to a member
4096/// function. MemExpr is the expression that refers to the member
4097/// function (and includes the object parameter), Args/NumArgs are the
4098/// arguments to the function call (not including the object
4099/// parameter). The caller needs to validate that the member
4100/// expression refers to a member function or an overloaded member
4101/// function.
4102Sema::ExprResult
4103Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4104 SourceLocation LParenLoc, Expr **Args,
4105 unsigned NumArgs, SourceLocation *CommaLocs,
4106 SourceLocation RParenLoc) {
4107 // Dig out the member expression. This holds both the object
4108 // argument and the member function we're referring to.
4109 MemberExpr *MemExpr = 0;
4110 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4111 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4112 else
4113 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4114 assert(MemExpr && "Building member call without member expression");
4115
4116 // Extract the object argument.
4117 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004118
Douglas Gregor3257fb52008-12-22 05:46:06 +00004119 CXXMethodDecl *Method = 0;
4120 if (OverloadedFunctionDecl *Ovl
4121 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
4122 // Add overload candidates
4123 OverloadCandidateSet CandidateSet;
4124 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4125 FuncEnd = Ovl->function_end();
4126 Func != FuncEnd; ++Func) {
4127 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
4128 Method = cast<CXXMethodDecl>(*Func);
4129 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4130 /*SuppressUserConversions=*/false);
4131 }
4132
4133 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004134 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004135 case OR_Success:
4136 Method = cast<CXXMethodDecl>(Best->Function);
4137 break;
4138
4139 case OR_No_Viable_Function:
4140 Diag(MemExpr->getSourceRange().getBegin(),
4141 diag::err_ovl_no_viable_member_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004142 << Ovl->getDeclName() << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004143 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4144 // FIXME: Leaking incoming expressions!
4145 return true;
4146
4147 case OR_Ambiguous:
4148 Diag(MemExpr->getSourceRange().getBegin(),
4149 diag::err_ovl_ambiguous_member_call)
4150 << Ovl->getDeclName() << MemExprE->getSourceRange();
4151 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4152 // FIXME: Leaking incoming expressions!
4153 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004154
4155 case OR_Deleted:
4156 Diag(MemExpr->getSourceRange().getBegin(),
4157 diag::err_ovl_deleted_member_call)
4158 << Best->Function->isDeleted()
4159 << Ovl->getDeclName() << MemExprE->getSourceRange();
4160 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4161 // FIXME: Leaking incoming expressions!
4162 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004163 }
4164
4165 FixOverloadedFunctionReference(MemExpr, Method);
4166 } else {
4167 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4168 }
4169
4170 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004171 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004172 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4173 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004174 Method->getResultType().getNonReferenceType(),
4175 RParenLoc));
4176
4177 // Convert the object argument (for a non-static member function call).
4178 if (!Method->isStatic() &&
4179 PerformObjectArgumentInitialization(ObjectArg, Method))
4180 return true;
4181 MemExpr->setBase(ObjectArg);
4182
4183 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004184 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004185 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4186 RParenLoc))
4187 return true;
4188
Sebastian Redl8b769972009-01-19 00:08:26 +00004189 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004190}
4191
Douglas Gregor10f3c502008-11-19 21:05:33 +00004192/// BuildCallToObjectOfClassType - Build a call to an object of class
4193/// type (C++ [over.call.object]), which can end up invoking an
4194/// overloaded function call operator (@c operator()) or performing a
4195/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004196Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004197Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4198 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004199 Expr **Args, unsigned NumArgs,
4200 SourceLocation *CommaLocs,
4201 SourceLocation RParenLoc) {
4202 assert(Object->getType()->isRecordType() && "Requires object type argument");
4203 const RecordType *Record = Object->getType()->getAsRecordType();
4204
4205 // C++ [over.call.object]p1:
4206 // If the primary-expression E in the function call syntax
4207 // evaluates to a class object of type “cv T”, then the set of
4208 // candidate functions includes at least the function call
4209 // operators of T. The function call operators of T are obtained by
4210 // ordinary lookup of the name operator() in the context of
4211 // (E).operator().
4212 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004213 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004214 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004215 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004216 Oper != OperEnd; ++Oper)
4217 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4218 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004219
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004220 // C++ [over.call.object]p2:
4221 // In addition, for each conversion function declared in T of the
4222 // form
4223 //
4224 // operator conversion-type-id () cv-qualifier;
4225 //
4226 // where cv-qualifier is the same cv-qualification as, or a
4227 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004228 // denotes the type "pointer to function of (P1,...,Pn) returning
4229 // R", or the type "reference to pointer to function of
4230 // (P1,...,Pn) returning R", or the type "reference to function
4231 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004232 // is also considered as a candidate function. Similarly,
4233 // surrogate call functions are added to the set of candidate
4234 // functions for each conversion function declared in an
4235 // accessible base class provided the function is not hidden
4236 // within T by another intervening declaration.
4237 //
4238 // FIXME: Look in base classes for more conversion operators!
4239 OverloadedFunctionDecl *Conversions
4240 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004241 for (OverloadedFunctionDecl::function_iterator
4242 Func = Conversions->function_begin(),
4243 FuncEnd = Conversions->function_end();
4244 Func != FuncEnd; ++Func) {
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004245 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4246
4247 // Strip the reference type (if any) and then the pointer type (if
4248 // any) to get down to what might be a function type.
4249 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4250 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4251 ConvType = ConvPtrType->getPointeeType();
4252
Douglas Gregor4fa58902009-02-26 23:50:07 +00004253 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004254 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4255 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004256
4257 // Perform overload resolution.
4258 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004259 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004260 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004261 // Overload resolution succeeded; we'll build the appropriate call
4262 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004263 break;
4264
4265 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004266 Diag(Object->getSourceRange().getBegin(),
4267 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004268 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004269 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004270 break;
4271
4272 case OR_Ambiguous:
4273 Diag(Object->getSourceRange().getBegin(),
4274 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004275 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004276 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4277 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004278
4279 case OR_Deleted:
4280 Diag(Object->getSourceRange().getBegin(),
4281 diag::err_ovl_deleted_object_call)
4282 << Best->Function->isDeleted()
4283 << Object->getType() << Object->getSourceRange();
4284 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4285 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004286 }
4287
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004288 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004289 // We had an error; delete all of the subexpressions and return
4290 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004291 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004292 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004293 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004294 return true;
4295 }
4296
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004297 if (Best->Function == 0) {
4298 // Since there is no function declaration, this is one of the
4299 // surrogate candidates. Dig out the conversion function.
4300 CXXConversionDecl *Conv
4301 = cast<CXXConversionDecl>(
4302 Best->Conversions[0].UserDefined.ConversionFunction);
4303
4304 // We selected one of the surrogate functions that converts the
4305 // object parameter to a function pointer. Perform the conversion
4306 // on the object argument, then let ActOnCallExpr finish the job.
4307 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004308 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004309 Conv->getConversionType().getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +00004310 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004311 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4312 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4313 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004314 }
4315
4316 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4317 // that calls this method, using Object for the implicit object
4318 // parameter and passing along the remaining arguments.
4319 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004320 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004321
4322 unsigned NumArgsInProto = Proto->getNumArgs();
4323 unsigned NumArgsToCheck = NumArgs;
4324
4325 // Build the full argument list for the method call (the
4326 // implicit object parameter is placed at the beginning of the
4327 // list).
4328 Expr **MethodArgs;
4329 if (NumArgs < NumArgsInProto) {
4330 NumArgsToCheck = NumArgsInProto;
4331 MethodArgs = new Expr*[NumArgsInProto + 1];
4332 } else {
4333 MethodArgs = new Expr*[NumArgs + 1];
4334 }
4335 MethodArgs[0] = Object;
4336 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4337 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4338
Ted Kremenek0c97e042009-02-07 01:47:29 +00004339 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4340 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004341 UsualUnaryConversions(NewFn);
4342
4343 // Once we've built TheCall, all of the expressions are properly
4344 // owned.
4345 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004346 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004347 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4348 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004349 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004350 delete [] MethodArgs;
4351
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004352 // We may have default arguments. If so, we need to allocate more
4353 // slots in the call for them.
4354 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004355 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004356 else if (NumArgs > NumArgsInProto)
4357 NumArgsToCheck = NumArgsInProto;
4358
Chris Lattner81f00ed2009-04-12 08:11:20 +00004359 bool IsError = false;
4360
Douglas Gregor10f3c502008-11-19 21:05:33 +00004361 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004362 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004363 TheCall->setArg(0, Object);
4364
Chris Lattner81f00ed2009-04-12 08:11:20 +00004365
Douglas Gregor10f3c502008-11-19 21:05:33 +00004366 // Check the argument types.
4367 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004368 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004369 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004370 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004371
4372 // Pass the argument.
4373 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004374 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004375 } else {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004376 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004377 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004378
4379 TheCall->setArg(i + 1, Arg);
4380 }
4381
4382 // If this is a variadic call, handle args passed through "...".
4383 if (Proto->isVariadic()) {
4384 // Promote the arguments (C99 6.5.2.2p7).
4385 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4386 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004387 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004388 TheCall->setArg(i + 1, Arg);
4389 }
4390 }
4391
Chris Lattner81f00ed2009-04-12 08:11:20 +00004392 if (IsError) return true;
4393
Sebastian Redl8b769972009-01-19 00:08:26 +00004394 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004395}
4396
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004397/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4398/// (if one exists), where @c Base is an expression of class type and
4399/// @c Member is the name of the member we're trying to find.
4400Action::ExprResult
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004401Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004402 SourceLocation MemberLoc,
4403 IdentifierInfo &Member) {
4404 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4405
4406 // C++ [over.ref]p1:
4407 //
4408 // [...] An expression x->m is interpreted as (x.operator->())->m
4409 // for a class object x of type T if T::operator->() exists and if
4410 // the operator is selected as the best match function by the
4411 // overload resolution mechanism (13.3).
4412 // FIXME: look in base classes.
4413 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4414 OverloadCandidateSet CandidateSet;
4415 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004416
4417 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004418 for (llvm::tie(Oper, OperEnd)
4419 = BaseRecord->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004420 Oper != OperEnd; ++Oper)
4421 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004422 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004423
Ted Kremenek0c97e042009-02-07 01:47:29 +00004424 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004425
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004426 // Perform overload resolution.
4427 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004428 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004429 case OR_Success:
4430 // Overload resolution succeeded; we'll build the call below.
4431 break;
4432
4433 case OR_No_Viable_Function:
4434 if (CandidateSet.empty())
4435 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004436 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004437 else
4438 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Chris Lattner4a526112009-02-17 07:29:20 +00004439 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004440 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004441 return true;
4442
4443 case OR_Ambiguous:
4444 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004445 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004446 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004447 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004448
4449 case OR_Deleted:
4450 Diag(OpLoc, diag::err_ovl_deleted_oper)
4451 << Best->Function->isDeleted()
4452 << "operator->" << BasePtr->getSourceRange();
4453 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4454 return true;
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004455 }
4456
4457 // Convert the object parameter.
4458 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004459 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004460 return true;
Douglas Gregor9c690e92008-11-21 03:04:22 +00004461
4462 // No concerns about early exits now.
4463 BasePtr.take();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004464
4465 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004466 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4467 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004468 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004469 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004470 Method->getResultType().getNonReferenceType(),
4471 OpLoc);
Sebastian Redl8b769972009-01-19 00:08:26 +00004472 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
Chris Lattner5261d0c2009-03-28 19:18:32 +00004473 MemberLoc, Member, DeclPtrTy()).release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004474}
4475
Douglas Gregor45014fd2008-11-10 20:40:00 +00004476/// FixOverloadedFunctionReference - E is an expression that refers to
4477/// a C++ overloaded function (possibly with some parentheses and
4478/// perhaps a '&' around it). We have resolved the overloaded function
4479/// to the function declaration Fn, so patch up the expression E to
4480/// refer (possibly indirectly) to Fn.
4481void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4482 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4483 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4484 E->setType(PE->getSubExpr()->getType());
4485 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4486 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4487 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004488 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4489 if (Method->isStatic()) {
4490 // Do nothing: static member functions aren't any different
4491 // from non-member functions.
4492 }
4493 else if (QualifiedDeclRefExpr *DRE
4494 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4495 // We have taken the address of a pointer to member
4496 // function. Perform the computation here so that we get the
4497 // appropriate pointer to member type.
4498 DRE->setDecl(Fn);
4499 DRE->setType(Fn->getType());
4500 QualType ClassType
4501 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4502 E->setType(Context.getMemberPointerType(Fn->getType(),
4503 ClassType.getTypePtr()));
4504 return;
4505 }
4506 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004507 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004508 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004509 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4510 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4511 "Expected overloaded function");
4512 DR->setDecl(Fn);
4513 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004514 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4515 MemExpr->setMemberDecl(Fn);
4516 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004517 } else {
4518 assert(false && "Invalid reference to overloaded function");
4519 }
4520}
4521
Douglas Gregord2baafd2008-10-21 16:13:35 +00004522} // end namespace clang