blob: f21b38a649e7ae924e347e1185f7f2ce49a1ce26 [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)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor14046502008-10-23 00:40:37 +0000177 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;
Douglas Gregorb60eb752009-06-25 22:08:12 +0000303 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
304 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
305 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000306 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
307 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
308
309 // C++ [temp.fct]p2:
310 // A function template can be overloaded with other function templates
311 // and with normal (non-template) functions.
312 if ((OldTemplate == 0) != (NewTemplate == 0))
313 return true;
314
Douglas Gregord2baafd2008-10-21 16:13:35 +0000315 // Is the function New an overload of the function Old?
316 QualType OldQType = Context.getCanonicalType(Old->getType());
317 QualType NewQType = Context.getCanonicalType(New->getType());
318
319 // Compare the signatures (C++ 1.3.10) of the two functions to
320 // determine whether they are overloads. If we find any mismatch
321 // in the signature, they are overloads.
322
323 // If either of these functions is a K&R-style function (no
324 // prototype), then we consider them to have matching signatures.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000325 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
326 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000327 return false;
328
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000329 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
330 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000331
332 // The signature of a function includes the types of its
333 // parameters (C++ 1.3.10), which includes the presence or absence
334 // of the ellipsis; see C++ DR 357).
335 if (OldQType != NewQType &&
336 (OldType->getNumArgs() != NewType->getNumArgs() ||
337 OldType->isVariadic() != NewType->isVariadic() ||
338 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
339 NewType->arg_type_begin())))
340 return true;
341
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000342 // C++ [temp.over.link]p4:
343 // The signature of a function template consists of its function
344 // signature, its return type and its template parameter list. The names
345 // of the template parameters are significant only for establishing the
346 // relationship between the template parameters and the rest of the
347 // signature.
348 //
349 // We check the return type and template parameter lists for function
350 // templates first; the remaining checks follow.
351 if (NewTemplate &&
352 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
353 OldTemplate->getTemplateParameters(),
354 false, false, SourceLocation()) ||
355 OldType->getResultType() != NewType->getResultType()))
356 return true;
357
Douglas Gregord2baafd2008-10-21 16:13:35 +0000358 // If the function is a class member, its signature includes the
359 // cv-qualifiers (if any) on the function itself.
360 //
361 // As part of this, also check whether one of the member functions
362 // is static, in which case they are not overloads (C++
363 // 13.1p2). While not part of the definition of the signature,
364 // this check is important to determine whether these functions
365 // can be overloaded.
366 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
367 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
368 if (OldMethod && NewMethod &&
369 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000370 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000371 return true;
372
373 // The signatures match; this is not an overload.
374 return false;
375 } else {
376 // (C++ 13p1):
377 // Only function declarations can be overloaded; object and type
378 // declarations cannot be overloaded.
379 return false;
380 }
381}
382
Douglas Gregor81c29152008-10-29 00:13:59 +0000383/// TryImplicitConversion - Attempt to perform an implicit conversion
384/// from the given expression (Expr) to the given type (ToType). This
385/// function returns an implicit conversion sequence that can be used
386/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000387///
388/// void f(float f);
389/// void g(int i) { f(i); }
390///
391/// this routine would produce an implicit conversion sequence to
392/// describe the initialization of f from i, which will be a standard
393/// conversion sequence containing an lvalue-to-rvalue conversion (C++
394/// 4.1) followed by a floating-integral conversion (C++ 4.9).
395//
396/// Note that this routine only determines how the conversion can be
397/// performed; it does not actually perform the conversion. As such,
398/// it will not produce any diagnostics if no conversion is available,
399/// but will instead return an implicit conversion sequence of kind
400/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000401///
402/// If @p SuppressUserConversions, then user-defined conversions are
403/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000404/// If @p AllowExplicit, then explicit user-defined conversions are
405/// permitted.
Sebastian Redla55834a2009-04-12 17:16:29 +0000406/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
407/// no matter its actual lvalueness.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000408ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000409Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000410 bool SuppressUserConversions,
Sebastian Redla55834a2009-04-12 17:16:29 +0000411 bool AllowExplicit, bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000412{
413 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000414 if (IsStandardConversion(From, ToType, ICS.Standard))
415 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000416 else if (getLangOptions().CPlusPlus &&
417 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redla55834a2009-04-12 17:16:29 +0000418 !SuppressUserConversions, AllowExplicit,
419 ForceRValue)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000420 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000421 // C++ [over.ics.user]p4:
422 // A conversion of an expression of class type to the same class
423 // type is given Exact Match rank, and a conversion of an
424 // expression of class type to a base class of that type is
425 // given Conversion rank, in spite of the fact that a copy
426 // constructor (i.e., a user-defined conversion function) is
427 // called for those cases.
428 if (CXXConstructorDecl *Constructor
429 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregord9176392009-02-02 22:11:10 +0000430 QualType FromCanon
431 = Context.getCanonicalType(From->getType().getUnqualifiedType());
432 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
433 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000434 // Turn this into a "standard" conversion sequence, so that it
435 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000436 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
437 ICS.Standard.setAsIdentityConversion();
438 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
439 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000440 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000441 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000442 ICS.Standard.Second = ICK_Derived_To_Base;
443 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000444 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000445
446 // C++ [over.best.ics]p4:
447 // However, when considering the argument of a user-defined
448 // conversion function that is a candidate by 13.3.1.3 when
449 // invoked for the copying of the temporary in the second step
450 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
451 // 13.3.1.6 in all cases, only standard conversion sequences and
452 // ellipsis conversion sequences are allowed.
453 if (SuppressUserConversions &&
454 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
455 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000456 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000457 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000458
459 return ICS;
460}
461
462/// IsStandardConversion - Determines whether there is a standard
463/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
464/// expression From to the type ToType. Standard conversion sequences
465/// only consider non-class types; for conversions that involve class
466/// types, use TryImplicitConversion. If a conversion exists, SCS will
467/// contain the standard conversion sequence required to perform this
468/// conversion and this routine will return true. Otherwise, this
469/// routine will return false and the value of SCS is unspecified.
470bool
471Sema::IsStandardConversion(Expr* From, QualType ToType,
472 StandardConversionSequence &SCS)
473{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000474 QualType FromType = From->getType();
475
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000476 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000477 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000478 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000479 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000480 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000481 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000482
Douglas Gregorfcb19192009-02-11 23:02:49 +0000483 // There are no standard conversions for class types in C++, so
484 // abort early. When overloading in C, however, we do permit
485 if (FromType->isRecordType() || ToType->isRecordType()) {
486 if (getLangOptions().CPlusPlus)
487 return false;
488
489 // When we're overloading in C, we allow, as standard conversions,
490 }
491
Douglas Gregord2baafd2008-10-21 16:13:35 +0000492 // The first conversion can be an lvalue-to-rvalue conversion,
493 // array-to-pointer conversion, or function-to-pointer conversion
494 // (C++ 4p1).
495
496 // Lvalue-to-rvalue conversion (C++ 4.1):
497 // An lvalue (3.10) of a non-function, non-array type T can be
498 // converted to an rvalue.
499 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
500 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000501 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000502 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000503 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000504
505 // If T is a non-class type, the type of the rvalue is the
506 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000507 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
508 // just strip the qualifiers because they don't matter.
509
510 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000511 FromType = FromType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000512 } else if (FromType->isArrayType()) {
513 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000514 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000515
516 // An lvalue or rvalue of type "array of N T" or "array of unknown
517 // bound of T" can be converted to an rvalue of type "pointer to
518 // T" (C++ 4.2p1).
519 FromType = Context.getArrayDecayedType(FromType);
520
521 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
522 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000523 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000524
525 // For the purpose of ranking in overload resolution
526 // (13.3.3.1.1), this conversion is considered an
527 // array-to-pointer conversion followed by a qualification
528 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000529 SCS.Second = ICK_Identity;
530 SCS.Third = ICK_Qualification;
531 SCS.ToTypePtr = ToType.getAsOpaquePtr();
532 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000533 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000534 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
535 // Function-to-pointer conversion (C++ 4.3).
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);
Mike Stump90fc78e2009-08-04 21:02:39 +0000542 } else if (FunctionDecl *Fn
Douglas Gregor45014fd2008-11-10 20:40:00 +0000543 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000544 // Address of overloaded function (C++ [over.over]).
Douglas Gregor45014fd2008-11-10 20:40:00 +0000545 SCS.First = ICK_Function_To_Pointer;
546
547 // We were able to resolve the address of the overloaded function,
548 // so we can convert to the type of that function.
549 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000550 if (ToType->isLValueReferenceType())
551 FromType = Context.getLValueReferenceType(FromType);
552 else if (ToType->isRValueReferenceType())
553 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000554 else if (ToType->isMemberPointerType()) {
555 // Resolve address only succeeds if both sides are member pointers,
556 // but it doesn't have to be the same class. See DR 247.
557 // Note that this means that the type of &Derived::fn can be
558 // Ret (Base::*)(Args) if the fn overload actually found is from the
559 // base class, even if it was brought into the derived class via a
560 // using declaration. The standard isn't clear on this issue at all.
561 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
562 FromType = Context.getMemberPointerType(FromType,
563 Context.getTypeDeclType(M->getParent()).getTypePtr());
564 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000565 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000566 } else {
567 // We don't require any conversions for the first step.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000568 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000569 }
570
571 // The second conversion can be an integral promotion, floating
572 // point promotion, integral conversion, floating point conversion,
573 // floating-integral conversion, pointer conversion,
574 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000575 // For overloading in C, this can also be a "compatible-type"
576 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000577 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000578 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000579 // The unqualified versions of the types are the same: there's no
580 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000581 SCS.Second = ICK_Identity;
Mike Stump90fc78e2009-08-04 21:02:39 +0000582 } else if (IsIntegralPromotion(From, FromType, ToType)) {
583 // Integral promotion (C++ 4.5).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000584 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000585 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000586 } else if (IsFloatingPointPromotion(FromType, ToType)) {
587 // Floating point promotion (C++ 4.6).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000588 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000589 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000590 } else if (IsComplexPromotion(FromType, ToType)) {
591 // Complex promotion (Clang extension)
Douglas Gregore819caf2009-02-12 00:15:05 +0000592 SCS.Second = ICK_Complex_Promotion;
593 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000594 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000595 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000596 // Integral conversions (C++ 4.7).
597 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000598 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000599 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000600 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
601 // Floating point conversions (C++ 4.8).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000602 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000603 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000604 } else if (FromType->isComplexType() && ToType->isComplexType()) {
605 // Complex conversions (C99 6.3.1.6)
Douglas Gregore819caf2009-02-12 00:15:05 +0000606 SCS.Second = ICK_Complex_Conversion;
607 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000608 } else if ((FromType->isFloatingType() &&
609 ToType->isIntegralType() && (!ToType->isBooleanType() &&
610 !ToType->isEnumeralType())) ||
611 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
612 ToType->isFloatingType())) {
613 // Floating-integral conversions (C++ 4.9).
614 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000615 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000616 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000617 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
618 (ToType->isComplexType() && FromType->isArithmeticType())) {
619 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregore819caf2009-02-12 00:15:05 +0000620 SCS.Second = ICK_Complex_Real;
621 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000622 } else if (IsPointerConversion(From, FromType, ToType, FromType,
623 IncompatibleObjC)) {
624 // Pointer conversions (C++ 4.10).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000625 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000626 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump90fc78e2009-08-04 21:02:39 +0000627 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
628 // Pointer to member conversions (4.11).
Sebastian Redlba387562009-01-25 19:43:20 +0000629 SCS.Second = ICK_Pointer_Member;
Mike Stump90fc78e2009-08-04 21:02:39 +0000630 } else if (ToType->isBooleanType() &&
631 (FromType->isArithmeticType() ||
632 FromType->isEnumeralType() ||
633 FromType->isPointerType() ||
634 FromType->isBlockPointerType() ||
635 FromType->isMemberPointerType() ||
636 FromType->isNullPtrType())) {
637 // Boolean conversions (C++ 4.12).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000638 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000639 FromType = Context.BoolTy;
Mike Stump90fc78e2009-08-04 21:02:39 +0000640 } else if (!getLangOptions().CPlusPlus &&
641 Context.typesAreCompatible(ToType, FromType)) {
642 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000643 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000644 } else {
645 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000646 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000647 }
648
Douglas Gregor81c29152008-10-29 00:13:59 +0000649 QualType CanonFrom;
650 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000651 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000652 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000653 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000654 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000655 CanonFrom = Context.getCanonicalType(FromType);
656 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000657 } else {
658 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000659 SCS.Third = ICK_Identity;
660
661 // C++ [over.best.ics]p6:
662 // [...] Any difference in top-level cv-qualification is
663 // subsumed by the initialization itself and does not constitute
664 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000665 CanonFrom = Context.getCanonicalType(FromType);
666 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000667 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000668 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
669 FromType = ToType;
670 CanonFrom = CanonTo;
671 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000672 }
673
674 // If we have not converted the argument type to the parameter type,
675 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000676 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000677 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000678
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000679 SCS.ToTypePtr = FromType.getAsOpaquePtr();
680 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000681}
682
683/// IsIntegralPromotion - Determines whether the conversion from the
684/// expression From (whose potentially-adjusted type is FromType) to
685/// ToType is an integral promotion (C++ 4.5). If so, returns true and
686/// sets PromotedType to the promoted type.
687bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
688{
689 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000690 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000691 if (!To) {
692 return false;
693 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000694
695 // An rvalue of type char, signed char, unsigned char, short int, or
696 // unsigned short int can be converted to an rvalue of type int if
697 // int can represent all the values of the source type; otherwise,
698 // the source rvalue can be converted to an rvalue of type unsigned
699 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000700 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000701 if (// We can promote any signed, promotable integer type to an int
702 (FromType->isSignedIntegerType() ||
703 // We can promote any unsigned integer type whose size is
704 // less than int to an int.
705 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000706 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000707 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000708 }
709
Douglas Gregord2baafd2008-10-21 16:13:35 +0000710 return To->getKind() == BuiltinType::UInt;
711 }
712
713 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
714 // can be converted to an rvalue of the first of the following types
715 // that can represent all the values of its underlying type: int,
716 // unsigned int, long, or unsigned long (C++ 4.5p2).
717 if ((FromType->isEnumeralType() || FromType->isWideCharType())
718 && ToType->isIntegerType()) {
719 // Determine whether the type we're converting from is signed or
720 // unsigned.
721 bool FromIsSigned;
722 uint64_t FromSize = Context.getTypeSize(FromType);
723 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
724 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
725 FromIsSigned = UnderlyingType->isSignedIntegerType();
726 } else {
727 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
728 FromIsSigned = true;
729 }
730
731 // The types we'll try to promote to, in the appropriate
732 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000733 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000734 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000735 Context.LongTy, Context.UnsignedLongTy ,
736 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000737 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000738 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000739 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
740 if (FromSize < ToSize ||
741 (FromSize == ToSize &&
742 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
743 // We found the type that we can promote to. If this is the
744 // type we wanted, we have a promotion. Otherwise, no
745 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000746 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000747 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
748 }
749 }
750 }
751
752 // An rvalue for an integral bit-field (9.6) can be converted to an
753 // rvalue of type int if int can represent all the values of the
754 // bit-field; otherwise, it can be converted to unsigned int if
755 // unsigned int can represent all the values of the bit-field. If
756 // the bit-field is larger yet, no integral promotion applies to
757 // it. If the bit-field has an enumerated type, it is treated as any
758 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stumpe127ae32009-05-16 07:39:55 +0000759 // FIXME: We should delay checking of bit-fields until we actually perform the
760 // conversion.
Douglas Gregor531434b2009-05-02 02:18:30 +0000761 using llvm::APSInt;
762 if (From)
763 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000764 APSInt BitWidth;
Douglas Gregor531434b2009-05-02 02:18:30 +0000765 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
766 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
767 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
768 ToSize = Context.getTypeSize(ToType);
Douglas Gregor82d44772008-12-20 23:49:58 +0000769
770 // Are we promoting to an int from a bitfield that fits in an int?
771 if (BitWidth < ToSize ||
772 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
773 return To->getKind() == BuiltinType::Int;
774 }
775
776 // Are we promoting to an unsigned int from an unsigned bitfield
777 // that fits into an unsigned int?
778 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
779 return To->getKind() == BuiltinType::UInt;
780 }
781
782 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000783 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000784 }
Douglas Gregor531434b2009-05-02 02:18:30 +0000785
Douglas Gregord2baafd2008-10-21 16:13:35 +0000786 // An rvalue of type bool can be converted to an rvalue of type int,
787 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000788 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000789 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000790 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000791
792 return false;
793}
794
795/// IsFloatingPointPromotion - Determines whether the conversion from
796/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
797/// returns true and sets PromotedType to the promoted type.
798bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
799{
800 /// An rvalue of type float can be converted to an rvalue of type
801 /// double. (C++ 4.6p1).
802 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000803 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000804 if (FromBuiltin->getKind() == BuiltinType::Float &&
805 ToBuiltin->getKind() == BuiltinType::Double)
806 return true;
807
Douglas Gregore819caf2009-02-12 00:15:05 +0000808 // C99 6.3.1.5p1:
809 // When a float is promoted to double or long double, or a
810 // double is promoted to long double [...].
811 if (!getLangOptions().CPlusPlus &&
812 (FromBuiltin->getKind() == BuiltinType::Float ||
813 FromBuiltin->getKind() == BuiltinType::Double) &&
814 (ToBuiltin->getKind() == BuiltinType::LongDouble))
815 return true;
816 }
817
Douglas Gregord2baafd2008-10-21 16:13:35 +0000818 return false;
819}
820
Douglas Gregore819caf2009-02-12 00:15:05 +0000821/// \brief Determine if a conversion is a complex promotion.
822///
823/// A complex promotion is defined as a complex -> complex conversion
824/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000825/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000826bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
827 const ComplexType *FromComplex = FromType->getAsComplexType();
828 if (!FromComplex)
829 return false;
830
831 const ComplexType *ToComplex = ToType->getAsComplexType();
832 if (!ToComplex)
833 return false;
834
835 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000836 ToComplex->getElementType()) ||
837 IsIntegralPromotion(0, FromComplex->getElementType(),
838 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000839}
840
Douglas Gregor24a90a52008-11-26 23:31:11 +0000841/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
842/// the pointer type FromPtr to a pointer to type ToPointee, with the
843/// same type qualifiers as FromPtr has on its pointee type. ToType,
844/// if non-empty, will be a pointer to ToType that may or may not have
845/// the right set of qualifiers on its pointee.
846static QualType
847BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
848 QualType ToPointee, QualType ToType,
849 ASTContext &Context) {
850 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
851 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
852 unsigned Quals = CanonFromPointee.getCVRQualifiers();
853
854 // Exact qualifier match -> return the pointer type we're converting to.
855 if (CanonToPointee.getCVRQualifiers() == Quals) {
856 // ToType is exactly what we need. Return it.
857 if (ToType.getTypePtr())
858 return ToType;
859
860 // Build a pointer to ToPointee. It has the right qualifiers
861 // already.
862 return Context.getPointerType(ToPointee);
863 }
864
865 // Just build a canonical type that has the right qualifiers.
866 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
867}
868
Douglas Gregord2baafd2008-10-21 16:13:35 +0000869/// IsPointerConversion - Determines whether the conversion of the
870/// expression From, which has the (possibly adjusted) type FromType,
871/// can be converted to the type ToType via a pointer conversion (C++
872/// 4.10). If so, returns true and places the converted type (that
873/// might differ from ToType in its cv-qualifiers at some level) into
874/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000875///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000876/// This routine also supports conversions to and from block pointers
877/// and conversions with Objective-C's 'id', 'id<protocols...>', and
878/// pointers to interfaces. FIXME: Once we've determined the
879/// appropriate overloading rules for Objective-C, we may want to
880/// split the Objective-C checks into a different routine; however,
881/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000882/// conversions, so for now they live here. IncompatibleObjC will be
883/// set if the conversion is an allowed Objective-C conversion that
884/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000885bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000886 QualType& ConvertedType,
887 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000888{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000889 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000890 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
891 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000892
Douglas Gregorf1d75712008-12-22 20:51:52 +0000893 // Conversion from a null pointer constant to any Objective-C pointer type.
Steve Naroffad75bd22009-07-16 15:41:00 +0000894 if (ToType->isObjCObjectPointerType() &&
Douglas Gregorf1d75712008-12-22 20:51:52 +0000895 From->isNullPointerConstant(Context)) {
896 ConvertedType = ToType;
897 return true;
898 }
899
Douglas Gregor9036ef72008-11-27 00:15:41 +0000900 // Blocks: Block pointers can be converted to void*.
901 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000902 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor9036ef72008-11-27 00:15:41 +0000903 ConvertedType = ToType;
904 return true;
905 }
906 // Blocks: A null pointer constant can be converted to a block
907 // pointer type.
908 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
909 ConvertedType = ToType;
910 return true;
911 }
912
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000913 // If the left-hand-side is nullptr_t, the right side can be a null
914 // pointer constant.
915 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
916 ConvertedType = ToType;
917 return true;
918 }
919
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000920 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000921 if (!ToTypePtr)
922 return false;
923
924 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
925 if (From->isNullPointerConstant(Context)) {
926 ConvertedType = ToType;
927 return true;
928 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000929
Douglas Gregor24a90a52008-11-26 23:31:11 +0000930 // Beyond this point, both types need to be pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000931 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor24a90a52008-11-26 23:31:11 +0000932 if (!FromTypePtr)
933 return false;
934
935 QualType FromPointeeType = FromTypePtr->getPointeeType();
936 QualType ToPointeeType = ToTypePtr->getPointeeType();
937
Douglas Gregord2baafd2008-10-21 16:13:35 +0000938 // An rvalue of type "pointer to cv T," where T is an object type,
939 // can be converted to an rvalue of type "pointer to cv void" (C++
940 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000941 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000942 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
943 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000944 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000945 return true;
946 }
947
Douglas Gregorfcb19192009-02-11 23:02:49 +0000948 // When we're overloading in C, we allow a special kind of pointer
949 // conversion for compatible-but-not-identical pointee types.
950 if (!getLangOptions().CPlusPlus &&
951 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
952 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
953 ToPointeeType,
954 ToType, Context);
955 return true;
956 }
957
Douglas Gregor14046502008-10-23 00:40:37 +0000958 // C++ [conv.ptr]p3:
959 //
960 // An rvalue of type "pointer to cv D," where D is a class type,
961 // can be converted to an rvalue of type "pointer to cv B," where
962 // B is a base class (clause 10) of D. If B is an inaccessible
963 // (clause 11) or ambiguous (10.2) base class of D, a program that
964 // necessitates this conversion is ill-formed. The result of the
965 // conversion is a pointer to the base class sub-object of the
966 // derived class object. The null pointer value is converted to
967 // the null pointer value of the destination type.
968 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000969 // Note that we do not check for ambiguity or inaccessibility
970 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000971 if (getLangOptions().CPlusPlus &&
972 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000973 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000974 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
975 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000976 ToType, Context);
977 return true;
978 }
Douglas Gregor14046502008-10-23 00:40:37 +0000979
Douglas Gregor932778b2008-12-19 19:13:09 +0000980 return false;
981}
982
983/// isObjCPointerConversion - Determines whether this is an
984/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
985/// with the same arguments and return values.
986bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
987 QualType& ConvertedType,
988 bool &IncompatibleObjC) {
989 if (!getLangOptions().ObjC1)
990 return false;
991
Steve Naroff329ec222009-07-10 23:34:53 +0000992 // First, we handle all conversions on ObjC object pointer types.
993 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
994 const ObjCObjectPointerType *FromObjCPtr =
995 FromType->getAsObjCObjectPointerType();
Douglas Gregor932778b2008-12-19 19:13:09 +0000996
Steve Naroff329ec222009-07-10 23:34:53 +0000997 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff7bffd372009-07-15 18:40:39 +0000998 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff329ec222009-07-10 23:34:53 +0000999 // pointer to any interface (in both directions).
Steve Naroff7bffd372009-07-15 18:40:39 +00001000 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00001001 ConvertedType = ToType;
1002 return true;
1003 }
1004 // Conversions with Objective-C's id<...>.
1005 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1006 ToObjCPtr->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00001007 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1008 /*compare=*/false)) {
Steve Naroff329ec222009-07-10 23:34:53 +00001009 ConvertedType = ToType;
1010 return true;
1011 }
1012 // Objective C++: We're able to convert from a pointer to an
1013 // interface to a pointer to a different interface.
1014 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1015 ConvertedType = ToType;
1016 return true;
1017 }
1018
1019 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1020 // Okay: this is some kind of implicit downcast of Objective-C
1021 // interfaces, which is permitted. However, we're going to
1022 // complain about it.
1023 IncompatibleObjC = true;
1024 ConvertedType = FromType;
1025 return true;
1026 }
1027 }
1028 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor80402cf2008-12-23 00:53:59 +00001029 QualType ToPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001030 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001031 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001032 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001033 ToPointeeType = ToBlockPtr->getPointeeType();
1034 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001035 return false;
1036
Douglas Gregor80402cf2008-12-23 00:53:59 +00001037 QualType FromPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001038 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001039 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001040 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001041 FromPointeeType = FromBlockPtr->getPointeeType();
1042 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001043 return false;
1044
Douglas Gregor932778b2008-12-19 19:13:09 +00001045 // If we have pointers to pointers, recursively check whether this
1046 // is an Objective-C conversion.
1047 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1048 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1049 IncompatibleObjC)) {
1050 // We always complain about this conversion.
1051 IncompatibleObjC = true;
1052 ConvertedType = ToType;
1053 return true;
1054 }
Douglas Gregor80402cf2008-12-23 00:53:59 +00001055 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001056 // differences in the argument and result types are in Objective-C
1057 // pointer conversions. If so, we permit the conversion (but
1058 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001059 const FunctionProtoType *FromFunctionType
1060 = FromPointeeType->getAsFunctionProtoType();
1061 const FunctionProtoType *ToFunctionType
1062 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001063 if (FromFunctionType && ToFunctionType) {
1064 // If the function types are exactly the same, this isn't an
1065 // Objective-C pointer conversion.
1066 if (Context.getCanonicalType(FromPointeeType)
1067 == Context.getCanonicalType(ToPointeeType))
1068 return false;
1069
1070 // Perform the quick checks that will tell us whether these
1071 // function types are obviously different.
1072 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1073 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1074 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1075 return false;
1076
1077 bool HasObjCConversion = false;
1078 if (Context.getCanonicalType(FromFunctionType->getResultType())
1079 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1080 // Okay, the types match exactly. Nothing to do.
1081 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1082 ToFunctionType->getResultType(),
1083 ConvertedType, IncompatibleObjC)) {
1084 // Okay, we have an Objective-C pointer conversion.
1085 HasObjCConversion = true;
1086 } else {
1087 // Function types are too different. Abort.
1088 return false;
1089 }
1090
1091 // Check argument types.
1092 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1093 ArgIdx != NumArgs; ++ArgIdx) {
1094 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1095 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1096 if (Context.getCanonicalType(FromArgType)
1097 == Context.getCanonicalType(ToArgType)) {
1098 // Okay, the types match exactly. Nothing to do.
1099 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1100 ConvertedType, IncompatibleObjC)) {
1101 // Okay, we have an Objective-C pointer conversion.
1102 HasObjCConversion = true;
1103 } else {
1104 // Argument types are too different. Abort.
1105 return false;
1106 }
1107 }
1108
1109 if (HasObjCConversion) {
1110 // We had an Objective-C conversion. Allow this pointer
1111 // conversion, but complain about it.
1112 ConvertedType = ToType;
1113 IncompatibleObjC = true;
1114 return true;
1115 }
1116 }
1117
Sebastian Redlba387562009-01-25 19:43:20 +00001118 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001119}
1120
Douglas Gregorbb461502008-10-24 04:54:22 +00001121/// CheckPointerConversion - Check the pointer conversion from the
1122/// expression From to the type ToType. This routine checks for
Sebastian Redl0e35d042009-07-25 15:41:38 +00001123/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregorbb461502008-10-24 04:54:22 +00001124/// conversions for which IsPointerConversion has already returned
1125/// true. It returns true and produces a diagnostic if there was an
1126/// error, or returns false otherwise.
1127bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1128 QualType FromType = From->getType();
1129
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001130 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1131 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001132 QualType FromPointeeType = FromPtrType->getPointeeType(),
1133 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001134
Douglas Gregorbb461502008-10-24 04:54:22 +00001135 if (FromPointeeType->isRecordType() &&
1136 ToPointeeType->isRecordType()) {
1137 // We must have a derived-to-base conversion. Check an
1138 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001139 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1140 From->getExprLoc(),
1141 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001142 }
1143 }
Steve Naroff329ec222009-07-10 23:34:53 +00001144 if (const ObjCObjectPointerType *FromPtrType =
1145 FromType->getAsObjCObjectPointerType())
1146 if (const ObjCObjectPointerType *ToPtrType =
1147 ToType->getAsObjCObjectPointerType()) {
1148 // Objective-C++ conversions are always okay.
1149 // FIXME: We should have a different class of conversions for the
1150 // Objective-C++ implicit conversions.
Steve Naroff7bffd372009-07-15 18:40:39 +00001151 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff329ec222009-07-10 23:34:53 +00001152 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +00001153
Steve Naroff329ec222009-07-10 23:34:53 +00001154 }
Douglas Gregorbb461502008-10-24 04:54:22 +00001155 return false;
1156}
1157
Sebastian Redlba387562009-01-25 19:43:20 +00001158/// IsMemberPointerConversion - Determines whether the conversion of the
1159/// expression From, which has the (possibly adjusted) type FromType, can be
1160/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1161/// If so, returns true and places the converted type (that might differ from
1162/// ToType in its cv-qualifiers at some level) into ConvertedType.
1163bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1164 QualType ToType, QualType &ConvertedType)
1165{
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001166 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001167 if (!ToTypePtr)
1168 return false;
1169
1170 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1171 if (From->isNullPointerConstant(Context)) {
1172 ConvertedType = ToType;
1173 return true;
1174 }
1175
1176 // Otherwise, both types have to be member pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001177 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001178 if (!FromTypePtr)
1179 return false;
1180
1181 // A pointer to member of B can be converted to a pointer to member of D,
1182 // where D is derived from B (C++ 4.11p2).
1183 QualType FromClass(FromTypePtr->getClass(), 0);
1184 QualType ToClass(ToTypePtr->getClass(), 0);
1185 // FIXME: What happens when these are dependent? Is this function even called?
1186
1187 if (IsDerivedFrom(ToClass, FromClass)) {
1188 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1189 ToClass.getTypePtr());
1190 return true;
1191 }
1192
1193 return false;
1194}
1195
1196/// CheckMemberPointerConversion - Check the member pointer conversion from the
1197/// expression From to the type ToType. This routine checks for ambiguous or
1198/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1199/// for which IsMemberPointerConversion has already returned true. It returns
1200/// true and produces a diagnostic if there was an error, or returns false
1201/// otherwise.
1202bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1203 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001204 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001205 if (!FromPtrType)
1206 return false;
Sebastian Redlba387562009-01-25 19:43:20 +00001207
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001208 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001209 assert(ToPtrType && "No member pointer cast has a target type "
1210 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001211
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001212 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1213 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001214
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001215 // FIXME: What about dependent types?
1216 assert(FromClass->isRecordType() && "Pointer into non-class.");
1217 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001218
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001219 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1220 /*DetectVirtual=*/true);
1221 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1222 assert(DerivationOkay &&
1223 "Should not have been called if derivation isn't OK.");
1224 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001225
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001226 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1227 getUnqualifiedType())) {
1228 // Derivation is ambiguous. Redo the check to find the exact paths.
1229 Paths.clear();
1230 Paths.setRecordingPaths(true);
1231 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1232 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1233 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001234
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001235 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1236 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1237 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1238 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001239 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001240
Douglas Gregor2e047592009-02-28 01:32:25 +00001241 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001242 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1243 << FromClass << ToClass << QualType(VBase, 0)
1244 << From->getSourceRange();
1245 return true;
1246 }
1247
Sebastian Redlba387562009-01-25 19:43:20 +00001248 return false;
1249}
1250
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001251/// IsQualificationConversion - Determines whether the conversion from
1252/// an rvalue of type FromType to ToType is a qualification conversion
1253/// (C++ 4.4).
1254bool
1255Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1256{
1257 FromType = Context.getCanonicalType(FromType);
1258 ToType = Context.getCanonicalType(ToType);
1259
1260 // If FromType and ToType are the same type, this is not a
1261 // qualification conversion.
1262 if (FromType == ToType)
1263 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001264
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001265 // (C++ 4.4p4):
1266 // A conversion can add cv-qualifiers at levels other than the first
1267 // in multi-level pointers, subject to the following rules: [...]
1268 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001269 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001270 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001271 // Within each iteration of the loop, we check the qualifiers to
1272 // determine if this still looks like a qualification
1273 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001274 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001275 // until there are no more pointers or pointers-to-members left to
1276 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001277 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001278
1279 // -- for every j > 0, if const is in cv 1,j then const is in cv
1280 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001281 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001282 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001283
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001284 // -- if the cv 1,j and cv 2,j are different, then const is in
1285 // every cv for 0 < k < j.
1286 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001287 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001288 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001289
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001290 // Keep track of whether all prior cv-qualifiers in the "to" type
1291 // include const.
1292 PreviousToQualsIncludeConst
1293 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001294 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001295
1296 // We are left with FromType and ToType being the pointee types
1297 // after unwrapping the original FromType and ToType the same number
1298 // of types. If we unwrapped any pointers, and if FromType and
1299 // ToType have the same unqualified type (since we checked
1300 // qualifiers above), then this is a qualification conversion.
1301 return UnwrappedAnyPointer &&
1302 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1303}
1304
Douglas Gregorb206cc42009-01-30 23:27:23 +00001305/// Determines whether there is a user-defined conversion sequence
1306/// (C++ [over.ics.user]) that converts expression From to the type
1307/// ToType. If such a conversion exists, User will contain the
1308/// user-defined conversion sequence that performs such a conversion
1309/// and this routine will return true. Otherwise, this routine returns
1310/// false and User is unspecified.
1311///
1312/// \param AllowConversionFunctions true if the conversion should
1313/// consider conversion functions at all. If false, only constructors
1314/// will be considered.
1315///
1316/// \param AllowExplicit true if the conversion should consider C++0x
1317/// "explicit" conversion functions as well as non-explicit conversion
1318/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001319///
1320/// \param ForceRValue true if the expression should be treated as an rvalue
1321/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001322bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001323 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001324 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001325 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001326{
1327 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001328 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001329 if (CXXRecordDecl *ToRecordDecl
1330 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1331 // C++ [over.match.ctor]p1:
1332 // When objects of class type are direct-initialized (8.5), or
1333 // copy-initialized from an expression of the same or a
1334 // derived class type (8.5), overload resolution selects the
1335 // constructor. [...] For copy-initialization, the candidate
1336 // functions are all the converting constructors (12.3.1) of
1337 // that class. The argument list is the expression-list within
1338 // the parentheses of the initializer.
1339 DeclarationName ConstructorName
1340 = Context.DeclarationNames.getCXXConstructorName(
1341 Context.getCanonicalType(ToType).getUnqualifiedType());
1342 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001343 for (llvm::tie(Con, ConEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001344 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001345 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00001346 // Find the constructor (which may be a template).
1347 CXXConstructorDecl *Constructor = 0;
1348 FunctionTemplateDecl *ConstructorTmpl
1349 = dyn_cast<FunctionTemplateDecl>(*Con);
1350 if (ConstructorTmpl)
1351 Constructor
1352 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1353 else
1354 Constructor = cast<CXXConstructorDecl>(*Con);
1355
Fariborz Jahanian625fb9d2009-08-06 17:22:51 +00001356 if (!Constructor->isInvalidDecl() &&
Douglas Gregor050cabf2009-08-21 18:42:58 +00001357 Constructor->isConvertingConstructor()) {
1358 if (ConstructorTmpl)
1359 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1360 1, CandidateSet,
1361 /*SuppressUserConversions=*/true,
1362 ForceRValue);
1363 else
1364 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1365 /*SuppressUserConversions=*/true, ForceRValue);
1366 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001367 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001368 }
1369 }
1370
Douglas Gregorb206cc42009-01-30 23:27:23 +00001371 if (!AllowConversionFunctions) {
1372 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-02-28 01:32:25 +00001373 } else if (const RecordType *FromRecordType
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001374 = From->getType()->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001375 if (CXXRecordDecl *FromRecordDecl
1376 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1377 // Add all of the conversion functions as candidates.
1378 // FIXME: Look for conversions in base classes!
1379 OverloadedFunctionDecl *Conversions
1380 = FromRecordDecl->getConversionFunctions();
1381 for (OverloadedFunctionDecl::function_iterator Func
1382 = Conversions->function_begin();
1383 Func != Conversions->function_end(); ++Func) {
1384 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1385 if (AllowExplicit || !Conv->isExplicit())
1386 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1387 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001388 }
1389 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001390
1391 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001392 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001393 case OR_Success:
1394 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001395 if (CXXConstructorDecl *Constructor
1396 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1397 // C++ [over.ics.user]p1:
1398 // If the user-defined conversion is specified by a
1399 // constructor (12.3.1), the initial standard conversion
1400 // sequence converts the source type to the type required by
1401 // the argument of the constructor.
1402 //
1403 // FIXME: What about ellipsis conversions?
1404 QualType ThisType = Constructor->getThisType(Context);
1405 User.Before = Best->Conversions[0].Standard;
1406 User.ConversionFunction = Constructor;
1407 User.After.setAsIdentityConversion();
1408 User.After.FromTypePtr
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001409 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001410 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1411 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001412 } else if (CXXConversionDecl *Conversion
1413 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1414 // C++ [over.ics.user]p1:
1415 //
1416 // [...] If the user-defined conversion is specified by a
1417 // conversion function (12.3.2), the initial standard
1418 // conversion sequence converts the source type to the
1419 // implicit object parameter of the conversion function.
1420 User.Before = Best->Conversions[0].Standard;
1421 User.ConversionFunction = Conversion;
1422
1423 // C++ [over.ics.user]p2:
1424 // The second standard conversion sequence converts the
1425 // result of the user-defined conversion to the target type
1426 // for the sequence. Since an implicit conversion sequence
1427 // is an initialization, the special rules for
1428 // initialization by user-defined conversion apply when
1429 // selecting the best user-defined conversion for a
1430 // user-defined conversion sequence (see 13.3.3 and
1431 // 13.3.3.1).
1432 User.After = Best->FinalConversion;
1433 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001434 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001435 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001436 return false;
1437 }
1438
1439 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001440 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001441 // No conversion here! We're done.
1442 return false;
1443
1444 case OR_Ambiguous:
1445 // FIXME: See C++ [over.best.ics]p10 for the handling of
1446 // ambiguous conversion sequences.
1447 return false;
1448 }
1449
1450 return false;
1451}
1452
Douglas Gregord2baafd2008-10-21 16:13:35 +00001453/// CompareImplicitConversionSequences - Compare two implicit
1454/// conversion sequences to determine whether one is better than the
1455/// other or if they are indistinguishable (C++ 13.3.3.2).
1456ImplicitConversionSequence::CompareKind
1457Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1458 const ImplicitConversionSequence& ICS2)
1459{
1460 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1461 // conversion sequences (as defined in 13.3.3.1)
1462 // -- a standard conversion sequence (13.3.3.1.1) is a better
1463 // conversion sequence than a user-defined conversion sequence or
1464 // an ellipsis conversion sequence, and
1465 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1466 // conversion sequence than an ellipsis conversion sequence
1467 // (13.3.3.1.3).
1468 //
1469 if (ICS1.ConversionKind < ICS2.ConversionKind)
1470 return ImplicitConversionSequence::Better;
1471 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1472 return ImplicitConversionSequence::Worse;
1473
1474 // Two implicit conversion sequences of the same form are
1475 // indistinguishable conversion sequences unless one of the
1476 // following rules apply: (C++ 13.3.3.2p3):
1477 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1478 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1479 else if (ICS1.ConversionKind ==
1480 ImplicitConversionSequence::UserDefinedConversion) {
1481 // User-defined conversion sequence U1 is a better conversion
1482 // sequence than another user-defined conversion sequence U2 if
1483 // they contain the same user-defined conversion function or
1484 // constructor and if the second standard conversion sequence of
1485 // U1 is better than the second standard conversion sequence of
1486 // U2 (C++ 13.3.3.2p3).
1487 if (ICS1.UserDefined.ConversionFunction ==
1488 ICS2.UserDefined.ConversionFunction)
1489 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1490 ICS2.UserDefined.After);
1491 }
1492
1493 return ImplicitConversionSequence::Indistinguishable;
1494}
1495
1496/// CompareStandardConversionSequences - Compare two standard
1497/// conversion sequences to determine whether one is better than the
1498/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1499ImplicitConversionSequence::CompareKind
1500Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1501 const StandardConversionSequence& SCS2)
1502{
1503 // Standard conversion sequence S1 is a better conversion sequence
1504 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1505
1506 // -- S1 is a proper subsequence of S2 (comparing the conversion
1507 // sequences in the canonical form defined by 13.3.3.1.1,
1508 // excluding any Lvalue Transformation; the identity conversion
1509 // sequence is considered to be a subsequence of any
1510 // non-identity conversion sequence) or, if not that,
1511 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1512 // Neither is a proper subsequence of the other. Do nothing.
1513 ;
1514 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1515 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1516 (SCS1.Second == ICK_Identity &&
1517 SCS1.Third == ICK_Identity))
1518 // SCS1 is a proper subsequence of SCS2.
1519 return ImplicitConversionSequence::Better;
1520 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1521 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1522 (SCS2.Second == ICK_Identity &&
1523 SCS2.Third == ICK_Identity))
1524 // SCS2 is a proper subsequence of SCS1.
1525 return ImplicitConversionSequence::Worse;
1526
1527 // -- the rank of S1 is better than the rank of S2 (by the rules
1528 // defined below), or, if not that,
1529 ImplicitConversionRank Rank1 = SCS1.getRank();
1530 ImplicitConversionRank Rank2 = SCS2.getRank();
1531 if (Rank1 < Rank2)
1532 return ImplicitConversionSequence::Better;
1533 else if (Rank2 < Rank1)
1534 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001535
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001536 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1537 // are indistinguishable unless one of the following rules
1538 // applies:
1539
1540 // A conversion that is not a conversion of a pointer, or
1541 // pointer to member, to bool is better than another conversion
1542 // that is such a conversion.
1543 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1544 return SCS2.isPointerConversionToBool()
1545 ? ImplicitConversionSequence::Better
1546 : ImplicitConversionSequence::Worse;
1547
Douglas Gregor14046502008-10-23 00:40:37 +00001548 // C++ [over.ics.rank]p4b2:
1549 //
1550 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001551 // conversion of B* to A* is better than conversion of B* to
1552 // void*, and conversion of A* to void* is better than conversion
1553 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001554 bool SCS1ConvertsToVoid
1555 = SCS1.isPointerConversionToVoidPointer(Context);
1556 bool SCS2ConvertsToVoid
1557 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001558 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1559 // Exactly one of the conversion sequences is a conversion to
1560 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001561 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1562 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001563 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1564 // Neither conversion sequence converts to a void pointer; compare
1565 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001566 if (ImplicitConversionSequence::CompareKind DerivedCK
1567 = CompareDerivedToBaseConversions(SCS1, SCS2))
1568 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001569 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1570 // Both conversion sequences are conversions to void
1571 // pointers. Compare the source types to determine if there's an
1572 // inheritance relationship in their sources.
1573 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1574 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1575
1576 // Adjust the types we're converting from via the array-to-pointer
1577 // conversion, if we need to.
1578 if (SCS1.First == ICK_Array_To_Pointer)
1579 FromType1 = Context.getArrayDecayedType(FromType1);
1580 if (SCS2.First == ICK_Array_To_Pointer)
1581 FromType2 = Context.getArrayDecayedType(FromType2);
1582
1583 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001584 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001585 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001586 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001587
1588 if (IsDerivedFrom(FromPointee2, FromPointee1))
1589 return ImplicitConversionSequence::Better;
1590 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1591 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001592
1593 // Objective-C++: If one interface is more specific than the
1594 // other, it is the better one.
1595 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1596 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1597 if (FromIface1 && FromIface1) {
1598 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1599 return ImplicitConversionSequence::Better;
1600 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1601 return ImplicitConversionSequence::Worse;
1602 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001603 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001604
1605 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1606 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001607 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001608 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001609 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001610
Douglas Gregor0e343382008-10-29 14:50:44 +00001611 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001612 // C++0x [over.ics.rank]p3b4:
1613 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1614 // implicit object parameter of a non-static member function declared
1615 // without a ref-qualifier, and S1 binds an rvalue reference to an
1616 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001617 // FIXME: We don't know if we're dealing with the implicit object parameter,
1618 // or if the member function in this case has a ref qualifier.
1619 // (Of course, we don't have ref qualifiers yet.)
1620 if (SCS1.RRefBinding != SCS2.RRefBinding)
1621 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1622 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001623
1624 // C++ [over.ics.rank]p3b4:
1625 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1626 // which the references refer are the same type except for
1627 // top-level cv-qualifiers, and the type to which the reference
1628 // initialized by S2 refers is more cv-qualified than the type
1629 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001630 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1631 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001632 T1 = Context.getCanonicalType(T1);
1633 T2 = Context.getCanonicalType(T2);
1634 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1635 if (T2.isMoreQualifiedThan(T1))
1636 return ImplicitConversionSequence::Better;
1637 else if (T1.isMoreQualifiedThan(T2))
1638 return ImplicitConversionSequence::Worse;
1639 }
1640 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001641
1642 return ImplicitConversionSequence::Indistinguishable;
1643}
1644
1645/// CompareQualificationConversions - Compares two standard conversion
1646/// sequences to determine whether they can be ranked based on their
1647/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1648ImplicitConversionSequence::CompareKind
1649Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1650 const StandardConversionSequence& SCS2)
1651{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001652 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001653 // -- S1 and S2 differ only in their qualification conversion and
1654 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1655 // cv-qualification signature of type T1 is a proper subset of
1656 // the cv-qualification signature of type T2, and S1 is not the
1657 // deprecated string literal array-to-pointer conversion (4.2).
1658 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1659 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1660 return ImplicitConversionSequence::Indistinguishable;
1661
1662 // FIXME: the example in the standard doesn't use a qualification
1663 // conversion (!)
1664 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1665 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1666 T1 = Context.getCanonicalType(T1);
1667 T2 = Context.getCanonicalType(T2);
1668
1669 // If the types are the same, we won't learn anything by unwrapped
1670 // them.
1671 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1672 return ImplicitConversionSequence::Indistinguishable;
1673
1674 ImplicitConversionSequence::CompareKind Result
1675 = ImplicitConversionSequence::Indistinguishable;
1676 while (UnwrapSimilarPointerTypes(T1, T2)) {
1677 // Within each iteration of the loop, we check the qualifiers to
1678 // determine if this still looks like a qualification
1679 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001680 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001681 // until there are no more pointers or pointers-to-members left
1682 // to unwrap. This essentially mimics what
1683 // IsQualificationConversion does, but here we're checking for a
1684 // strict subset of qualifiers.
1685 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1686 // The qualifiers are the same, so this doesn't tell us anything
1687 // about how the sequences rank.
1688 ;
1689 else if (T2.isMoreQualifiedThan(T1)) {
1690 // T1 has fewer qualifiers, so it could be the better sequence.
1691 if (Result == ImplicitConversionSequence::Worse)
1692 // Neither has qualifiers that are a subset of the other's
1693 // qualifiers.
1694 return ImplicitConversionSequence::Indistinguishable;
1695
1696 Result = ImplicitConversionSequence::Better;
1697 } else if (T1.isMoreQualifiedThan(T2)) {
1698 // T2 has fewer qualifiers, so it could be the better sequence.
1699 if (Result == ImplicitConversionSequence::Better)
1700 // Neither has qualifiers that are a subset of the other's
1701 // qualifiers.
1702 return ImplicitConversionSequence::Indistinguishable;
1703
1704 Result = ImplicitConversionSequence::Worse;
1705 } else {
1706 // Qualifiers are disjoint.
1707 return ImplicitConversionSequence::Indistinguishable;
1708 }
1709
1710 // If the types after this point are equivalent, we're done.
1711 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1712 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001713 }
1714
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001715 // Check that the winning standard conversion sequence isn't using
1716 // the deprecated string literal array to pointer conversion.
1717 switch (Result) {
1718 case ImplicitConversionSequence::Better:
1719 if (SCS1.Deprecated)
1720 Result = ImplicitConversionSequence::Indistinguishable;
1721 break;
1722
1723 case ImplicitConversionSequence::Indistinguishable:
1724 break;
1725
1726 case ImplicitConversionSequence::Worse:
1727 if (SCS2.Deprecated)
1728 Result = ImplicitConversionSequence::Indistinguishable;
1729 break;
1730 }
1731
1732 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001733}
1734
Douglas Gregor14046502008-10-23 00:40:37 +00001735/// CompareDerivedToBaseConversions - Compares two standard conversion
1736/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001737/// various kinds of derived-to-base conversions (C++
1738/// [over.ics.rank]p4b3). As part of these checks, we also look at
1739/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001740ImplicitConversionSequence::CompareKind
1741Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1742 const StandardConversionSequence& SCS2) {
1743 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1744 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1745 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1746 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1747
1748 // Adjust the types we're converting from via the array-to-pointer
1749 // conversion, if we need to.
1750 if (SCS1.First == ICK_Array_To_Pointer)
1751 FromType1 = Context.getArrayDecayedType(FromType1);
1752 if (SCS2.First == ICK_Array_To_Pointer)
1753 FromType2 = Context.getArrayDecayedType(FromType2);
1754
1755 // Canonicalize all of the types.
1756 FromType1 = Context.getCanonicalType(FromType1);
1757 ToType1 = Context.getCanonicalType(ToType1);
1758 FromType2 = Context.getCanonicalType(FromType2);
1759 ToType2 = Context.getCanonicalType(ToType2);
1760
Douglas Gregor0e343382008-10-29 14:50:44 +00001761 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001762 //
1763 // If class B is derived directly or indirectly from class A and
1764 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001765 //
1766 // For Objective-C, we let A, B, and C also be Objective-C
1767 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001768
1769 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001770 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001771 SCS2.Second == ICK_Pointer_Conversion &&
1772 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1773 FromType1->isPointerType() && FromType2->isPointerType() &&
1774 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001775 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001776 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001777 QualType ToPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001778 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001779 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001780 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001781 QualType ToPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001782 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001783
1784 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1785 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1786 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1787 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1788
Douglas Gregor0e343382008-10-29 14:50:44 +00001789 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001790 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1791 if (IsDerivedFrom(ToPointee1, ToPointee2))
1792 return ImplicitConversionSequence::Better;
1793 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1794 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001795
1796 if (ToIface1 && ToIface2) {
1797 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1798 return ImplicitConversionSequence::Better;
1799 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1800 return ImplicitConversionSequence::Worse;
1801 }
Douglas Gregor14046502008-10-23 00:40:37 +00001802 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001803
1804 // -- conversion of B* to A* is better than conversion of C* to A*,
1805 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1806 if (IsDerivedFrom(FromPointee2, FromPointee1))
1807 return ImplicitConversionSequence::Better;
1808 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1809 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001810
1811 if (FromIface1 && FromIface2) {
1812 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1813 return ImplicitConversionSequence::Better;
1814 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1815 return ImplicitConversionSequence::Worse;
1816 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001817 }
Douglas Gregor14046502008-10-23 00:40:37 +00001818 }
1819
Douglas Gregor0e343382008-10-29 14:50:44 +00001820 // Compare based on reference bindings.
1821 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1822 SCS1.Second == ICK_Derived_To_Base) {
1823 // -- binding of an expression of type C to a reference of type
1824 // B& is better than binding an expression of type C to a
1825 // reference of type A&,
1826 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1827 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1828 if (IsDerivedFrom(ToType1, ToType2))
1829 return ImplicitConversionSequence::Better;
1830 else if (IsDerivedFrom(ToType2, ToType1))
1831 return ImplicitConversionSequence::Worse;
1832 }
1833
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001834 // -- binding of an expression of type B to a reference of type
1835 // A& is better than binding an expression of type C to a
1836 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001837 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1838 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1839 if (IsDerivedFrom(FromType2, FromType1))
1840 return ImplicitConversionSequence::Better;
1841 else if (IsDerivedFrom(FromType1, FromType2))
1842 return ImplicitConversionSequence::Worse;
1843 }
1844 }
1845
1846
1847 // FIXME: conversion of A::* to B::* is better than conversion of
1848 // A::* to C::*,
1849
1850 // FIXME: conversion of B::* to C::* is better than conversion of
1851 // A::* to C::*, and
1852
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001853 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1854 SCS1.Second == ICK_Derived_To_Base) {
1855 // -- conversion of C to B is better than conversion of C to A,
1856 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1857 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1858 if (IsDerivedFrom(ToType1, ToType2))
1859 return ImplicitConversionSequence::Better;
1860 else if (IsDerivedFrom(ToType2, ToType1))
1861 return ImplicitConversionSequence::Worse;
1862 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001863
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001864 // -- conversion of B to A is better than conversion of C to A.
1865 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1866 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1867 if (IsDerivedFrom(FromType2, FromType1))
1868 return ImplicitConversionSequence::Better;
1869 else if (IsDerivedFrom(FromType1, FromType2))
1870 return ImplicitConversionSequence::Worse;
1871 }
1872 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001873
Douglas Gregor14046502008-10-23 00:40:37 +00001874 return ImplicitConversionSequence::Indistinguishable;
1875}
1876
Douglas Gregor81c29152008-10-29 00:13:59 +00001877/// TryCopyInitialization - Try to copy-initialize a value of type
1878/// ToType from the expression From. Return the implicit conversion
1879/// sequence required to pass this argument, which may be a bad
1880/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001881/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001882/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1883/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001884ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001885Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001886 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001887 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001888 ImplicitConversionSequence ICS;
Sebastian Redla55834a2009-04-12 17:16:29 +00001889 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1890 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001891 return ICS;
1892 } else {
Sebastian Redla55834a2009-04-12 17:16:29 +00001893 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1894 ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001895 }
1896}
1897
Sebastian Redla55834a2009-04-12 17:16:29 +00001898/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1899/// the expression @p From. Returns true (and emits a diagnostic) if there was
1900/// an error, returns false if the initialization succeeded. Elidable should
1901/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1902/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001903bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001904 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001905 if (!getLangOptions().CPlusPlus) {
1906 // In C, argument passing is the same as performing an assignment.
1907 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001908
Douglas Gregor81c29152008-10-29 00:13:59 +00001909 AssignConvertType ConvTy =
1910 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001911 if (ConvTy != Compatible &&
1912 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1913 ConvTy = Compatible;
1914
Douglas Gregor81c29152008-10-29 00:13:59 +00001915 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1916 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001917 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001918
Chris Lattner271d4c22008-11-24 05:29:24 +00001919 if (ToType->isReferenceType())
1920 return CheckReferenceInit(From, ToType);
1921
Sebastian Redla55834a2009-04-12 17:16:29 +00001922 if (!PerformImplicitConversion(From, ToType, Flavor,
1923 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001924 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001925
Chris Lattner271d4c22008-11-24 05:29:24 +00001926 return Diag(From->getSourceRange().getBegin(),
1927 diag::err_typecheck_convert_incompatible)
1928 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001929}
1930
Douglas Gregor5ed15042008-11-18 23:14:02 +00001931/// TryObjectArgumentInitialization - Try to initialize the object
1932/// parameter of the given member function (@c Method) from the
1933/// expression @p From.
1934ImplicitConversionSequence
1935Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1936 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1937 unsigned MethodQuals = Method->getTypeQualifiers();
1938 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1939
1940 // Set up the conversion sequence as a "bad" conversion, to allow us
1941 // to exit early.
1942 ImplicitConversionSequence ICS;
1943 ICS.Standard.setAsIdentityConversion();
1944 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1945
1946 // We need to have an object of class type.
1947 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001948 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001949 FromType = PT->getPointeeType();
1950
1951 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00001952
1953 // The implicit object parmeter is has the type "reference to cv X",
1954 // where X is the class of which the function is a member
1955 // (C++ [over.match.funcs]p4). However, when finding an implicit
1956 // conversion sequence for the argument, we are not allowed to
1957 // create temporaries or perform user-defined conversions
1958 // (C++ [over.match.funcs]p5). We perform a simplified version of
1959 // reference binding here, that allows class rvalues to bind to
1960 // non-constant references.
1961
1962 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1963 // with the implicit object parameter (C++ [over.match.funcs]p5).
1964 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1965 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1966 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1967 return ICS;
1968
1969 // Check that we have either the same type or a derived type. It
1970 // affects the conversion rank.
1971 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1972 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1973 ICS.Standard.Second = ICK_Identity;
1974 else if (IsDerivedFrom(FromType, ClassType))
1975 ICS.Standard.Second = ICK_Derived_To_Base;
1976 else
1977 return ICS;
1978
1979 // Success. Mark this as a reference binding.
1980 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1981 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1982 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1983 ICS.Standard.ReferenceBinding = true;
1984 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00001985 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00001986 return ICS;
1987}
1988
1989/// PerformObjectArgumentInitialization - Perform initialization of
1990/// the implicit object parameter for the given Method with the given
1991/// expression.
1992bool
1993Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001994 QualType FromRecordType, DestType;
1995 QualType ImplicitParamRecordType =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001996 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001997
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001998 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001999 FromRecordType = PT->getPointeeType();
2000 DestType = Method->getThisType(Context);
2001 } else {
2002 FromRecordType = From->getType();
2003 DestType = ImplicitParamRecordType;
2004 }
2005
Douglas Gregor5ed15042008-11-18 23:14:02 +00002006 ImplicitConversionSequence ICS
2007 = TryObjectArgumentInitialization(From, Method);
2008 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2009 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002010 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002011 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2012
Douglas Gregor5ed15042008-11-18 23:14:02 +00002013 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002014 CheckDerivedToBaseConversion(FromRecordType,
2015 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002016 From->getSourceRange().getBegin(),
2017 From->getSourceRange()))
2018 return true;
2019
Anders Carlssone25b6cd2009-08-07 18:45:49 +00002020 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2021 /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002022 return false;
2023}
2024
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002025/// TryContextuallyConvertToBool - Attempt to contextually convert the
2026/// expression From to bool (C++0x [conv]p3).
2027ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2028 return TryImplicitConversion(From, Context.BoolTy, false, true);
2029}
2030
2031/// PerformContextuallyConvertToBool - Perform a contextual conversion
2032/// of the expression From to bool (C++0x [conv]p3).
2033bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2034 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2035 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2036 return false;
2037
2038 return Diag(From->getSourceRange().getBegin(),
2039 diag::err_typecheck_bool_condition)
2040 << From->getType() << From->getSourceRange();
2041}
2042
Douglas Gregord2baafd2008-10-21 16:13:35 +00002043/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002044/// candidate functions, using the given function call arguments. If
2045/// @p SuppressUserConversions, then don't allow user-defined
2046/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002047/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2048/// hacky way to implement the overloading rules for elidable copy
2049/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002050void
2051Sema::AddOverloadCandidate(FunctionDecl *Function,
2052 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002053 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002054 bool SuppressUserConversions,
2055 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002056{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002057 const FunctionProtoType* Proto
2058 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002059 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002060 assert(!isa<CXXConversionDecl>(Function) &&
2061 "Use AddConversionCandidate for conversion functions");
Douglas Gregorb60eb752009-06-25 22:08:12 +00002062 assert(!Function->getDescribedFunctionTemplate() &&
2063 "Use AddTemplateOverloadCandidate for function templates");
2064
Douglas Gregor3257fb52008-12-22 05:46:06 +00002065 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002066 if (!isa<CXXConstructorDecl>(Method)) {
2067 // If we get here, it's because we're calling a member function
2068 // that is named without a member access expression (e.g.,
2069 // "this->f") that was either written explicitly or created
2070 // implicitly. This can happen with a qualified call to a member
2071 // function, e.g., X::f(). We use a NULL object as the implied
2072 // object argument (C++ [over.call.func]p3).
2073 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2074 SuppressUserConversions, ForceRValue);
2075 return;
2076 }
2077 // We treat a constructor like a non-member function, since its object
2078 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002079 }
2080
2081
Douglas Gregord2baafd2008-10-21 16:13:35 +00002082 // Add this candidate
2083 CandidateSet.push_back(OverloadCandidate());
2084 OverloadCandidate& Candidate = CandidateSet.back();
2085 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002086 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002087 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002088 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002089
2090 unsigned NumArgsInProto = Proto->getNumArgs();
2091
2092 // (C++ 13.3.2p2): A candidate function having fewer than m
2093 // parameters is viable only if it has an ellipsis in its parameter
2094 // list (8.3.5).
2095 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2096 Candidate.Viable = false;
2097 return;
2098 }
2099
2100 // (C++ 13.3.2p2): A candidate function having more than m parameters
2101 // is viable only if the (m+1)st parameter has a default argument
2102 // (8.3.6). For the purposes of overload resolution, the
2103 // parameter list is truncated on the right, so that there are
2104 // exactly m parameters.
2105 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2106 if (NumArgs < MinRequiredArgs) {
2107 // Not enough arguments.
2108 Candidate.Viable = false;
2109 return;
2110 }
2111
2112 // Determine the implicit conversion sequences for each of the
2113 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002114 Candidate.Conversions.resize(NumArgs);
2115 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2116 if (ArgIdx < NumArgsInProto) {
2117 // (C++ 13.3.2p3): for F to be a viable function, there shall
2118 // exist for each argument an implicit conversion sequence
2119 // (13.3.3.1) that converts that argument to the corresponding
2120 // parameter of F.
2121 QualType ParamType = Proto->getArgType(ArgIdx);
2122 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002123 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002124 SuppressUserConversions, ForceRValue);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002125 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002126 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002127 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002128 break;
2129 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002130 } else {
2131 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2132 // argument for which there is no corresponding parameter is
2133 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2134 Candidate.Conversions[ArgIdx].ConversionKind
2135 = ImplicitConversionSequence::EllipsisConversion;
2136 }
2137 }
2138}
2139
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002140/// \brief Add all of the function declarations in the given function set to
2141/// the overload canddiate set.
2142void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2143 Expr **Args, unsigned NumArgs,
2144 OverloadCandidateSet& CandidateSet,
2145 bool SuppressUserConversions) {
2146 for (FunctionSet::const_iterator F = Functions.begin(),
2147 FEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00002148 F != FEnd; ++F) {
2149 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2150 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2151 SuppressUserConversions);
2152 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002153 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2154 /*FIXME: explicit args */false, 0, 0,
2155 Args, NumArgs, CandidateSet,
Douglas Gregor993a0602009-06-27 21:05:07 +00002156 SuppressUserConversions);
2157 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002158}
2159
Douglas Gregor5ed15042008-11-18 23:14:02 +00002160/// AddMethodCandidate - Adds the given C++ member function to the set
2161/// of candidate functions, using the given function call arguments
2162/// and the object argument (@c Object). For example, in a call
2163/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2164/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2165/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002166/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2167/// a slightly hacky way to implement the overloading rules for elidable copy
2168/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002169void
2170Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2171 Expr **Args, unsigned NumArgs,
2172 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002173 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002174{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002175 const FunctionProtoType* Proto
2176 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002177 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002178 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002179 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002180 assert(!isa<CXXConstructorDecl>(Method) &&
2181 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002182
2183 // Add this candidate
2184 CandidateSet.push_back(OverloadCandidate());
2185 OverloadCandidate& Candidate = CandidateSet.back();
2186 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002187 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002188 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002189
2190 unsigned NumArgsInProto = Proto->getNumArgs();
2191
2192 // (C++ 13.3.2p2): A candidate function having fewer than m
2193 // parameters is viable only if it has an ellipsis in its parameter
2194 // list (8.3.5).
2195 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2196 Candidate.Viable = false;
2197 return;
2198 }
2199
2200 // (C++ 13.3.2p2): A candidate function having more than m parameters
2201 // is viable only if the (m+1)st parameter has a default argument
2202 // (8.3.6). For the purposes of overload resolution, the
2203 // parameter list is truncated on the right, so that there are
2204 // exactly m parameters.
2205 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2206 if (NumArgs < MinRequiredArgs) {
2207 // Not enough arguments.
2208 Candidate.Viable = false;
2209 return;
2210 }
2211
2212 Candidate.Viable = true;
2213 Candidate.Conversions.resize(NumArgs + 1);
2214
Douglas Gregor3257fb52008-12-22 05:46:06 +00002215 if (Method->isStatic() || !Object)
2216 // The implicit object argument is ignored.
2217 Candidate.IgnoreObjectArgument = true;
2218 else {
2219 // Determine the implicit conversion sequence for the object
2220 // parameter.
2221 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2222 if (Candidate.Conversions[0].ConversionKind
2223 == ImplicitConversionSequence::BadConversion) {
2224 Candidate.Viable = false;
2225 return;
2226 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002227 }
2228
2229 // Determine the implicit conversion sequences for each of the
2230 // arguments.
2231 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2232 if (ArgIdx < NumArgsInProto) {
2233 // (C++ 13.3.2p3): for F to be a viable function, there shall
2234 // exist for each argument an implicit conversion sequence
2235 // (13.3.3.1) that converts that argument to the corresponding
2236 // parameter of F.
2237 QualType ParamType = Proto->getArgType(ArgIdx);
2238 Candidate.Conversions[ArgIdx + 1]
2239 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002240 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002241 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2242 == ImplicitConversionSequence::BadConversion) {
2243 Candidate.Viable = false;
2244 break;
2245 }
2246 } else {
2247 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2248 // argument for which there is no corresponding parameter is
2249 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2250 Candidate.Conversions[ArgIdx + 1].ConversionKind
2251 = ImplicitConversionSequence::EllipsisConversion;
2252 }
2253 }
2254}
2255
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002256/// \brief Add a C++ member function template as a candidate to the candidate
2257/// set, using template argument deduction to produce an appropriate member
2258/// function template specialization.
2259void
2260Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2261 bool HasExplicitTemplateArgs,
2262 const TemplateArgument *ExplicitTemplateArgs,
2263 unsigned NumExplicitTemplateArgs,
2264 Expr *Object, Expr **Args, unsigned NumArgs,
2265 OverloadCandidateSet& CandidateSet,
2266 bool SuppressUserConversions,
2267 bool ForceRValue) {
2268 // C++ [over.match.funcs]p7:
2269 // In each case where a candidate is a function template, candidate
2270 // function template specializations are generated using template argument
2271 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2272 // candidate functions in the usual way.113) A given name can refer to one
2273 // or more function templates and also to a set of overloaded non-template
2274 // functions. In such a case, the candidate functions generated from each
2275 // function template are combined with the set of non-template candidate
2276 // functions.
2277 TemplateDeductionInfo Info(Context);
2278 FunctionDecl *Specialization = 0;
2279 if (TemplateDeductionResult Result
2280 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2281 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2282 Args, NumArgs, Specialization, Info)) {
2283 // FIXME: Record what happened with template argument deduction, so
2284 // that we can give the user a beautiful diagnostic.
2285 (void)Result;
2286 return;
2287 }
2288
2289 // Add the function template specialization produced by template argument
2290 // deduction as a candidate.
2291 assert(Specialization && "Missing member function template specialization?");
2292 assert(isa<CXXMethodDecl>(Specialization) &&
2293 "Specialization is not a member function?");
2294 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2295 CandidateSet, SuppressUserConversions, ForceRValue);
2296}
2297
Douglas Gregorb60eb752009-06-25 22:08:12 +00002298/// \brief Add a C++ function template as a candidate in the candidate set,
2299/// using template argument deduction to produce an appropriate function
2300/// template specialization.
2301void
2302Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002303 bool HasExplicitTemplateArgs,
2304 const TemplateArgument *ExplicitTemplateArgs,
2305 unsigned NumExplicitTemplateArgs,
Douglas Gregorb60eb752009-06-25 22:08:12 +00002306 Expr **Args, unsigned NumArgs,
2307 OverloadCandidateSet& CandidateSet,
2308 bool SuppressUserConversions,
2309 bool ForceRValue) {
2310 // C++ [over.match.funcs]p7:
2311 // In each case where a candidate is a function template, candidate
2312 // function template specializations are generated using template argument
2313 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2314 // candidate functions in the usual way.113) A given name can refer to one
2315 // or more function templates and also to a set of overloaded non-template
2316 // functions. In such a case, the candidate functions generated from each
2317 // function template are combined with the set of non-template candidate
2318 // functions.
2319 TemplateDeductionInfo Info(Context);
2320 FunctionDecl *Specialization = 0;
2321 if (TemplateDeductionResult Result
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002322 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2323 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2324 Args, NumArgs, Specialization, Info)) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00002325 // FIXME: Record what happened with template argument deduction, so
2326 // that we can give the user a beautiful diagnostic.
2327 (void)Result;
2328 return;
2329 }
2330
2331 // Add the function template specialization produced by template argument
2332 // deduction as a candidate.
2333 assert(Specialization && "Missing function template specialization?");
2334 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2335 SuppressUserConversions, ForceRValue);
2336}
2337
Douglas Gregor60714f92008-11-07 22:36:19 +00002338/// AddConversionCandidate - Add a C++ conversion function as a
2339/// candidate in the candidate set (C++ [over.match.conv],
2340/// C++ [over.match.copy]). From is the expression we're converting from,
2341/// and ToType is the type that we're eventually trying to convert to
2342/// (which may or may not be the same type as the type that the
2343/// conversion function produces).
2344void
2345Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2346 Expr *From, QualType ToType,
2347 OverloadCandidateSet& CandidateSet) {
2348 // Add this candidate
2349 CandidateSet.push_back(OverloadCandidate());
2350 OverloadCandidate& Candidate = CandidateSet.back();
2351 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002352 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002353 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002354 Candidate.FinalConversion.setAsIdentityConversion();
2355 Candidate.FinalConversion.FromTypePtr
2356 = Conversion->getConversionType().getAsOpaquePtr();
2357 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2358
Douglas Gregor5ed15042008-11-18 23:14:02 +00002359 // Determine the implicit conversion sequence for the implicit
2360 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002361 Candidate.Viable = true;
2362 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002363 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002364
Douglas Gregor60714f92008-11-07 22:36:19 +00002365 if (Candidate.Conversions[0].ConversionKind
2366 == ImplicitConversionSequence::BadConversion) {
2367 Candidate.Viable = false;
2368 return;
2369 }
2370
2371 // To determine what the conversion from the result of calling the
2372 // conversion function to the type we're eventually trying to
2373 // convert to (ToType), we need to synthesize a call to the
2374 // conversion function and attempt copy initialization from it. This
2375 // makes sure that we get the right semantics with respect to
2376 // lvalues/rvalues and the type. Fortunately, we can allocate this
2377 // call on the stack and we don't need its arguments to be
2378 // well-formed.
2379 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2380 SourceLocation());
2381 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002382 CastExpr::CK_Unknown,
Douglas Gregor70d26122008-11-12 17:17:38 +00002383 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002384
2385 // Note that it is safe to allocate CallExpr on the stack here because
2386 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2387 // allocator).
2388 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002389 Conversion->getConversionType().getNonReferenceType(),
2390 SourceLocation());
2391 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2392 switch (ICS.ConversionKind) {
2393 case ImplicitConversionSequence::StandardConversion:
2394 Candidate.FinalConversion = ICS.Standard;
2395 break;
2396
2397 case ImplicitConversionSequence::BadConversion:
2398 Candidate.Viable = false;
2399 break;
2400
2401 default:
2402 assert(false &&
2403 "Can only end up with a standard conversion sequence or failure");
2404 }
2405}
2406
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002407/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2408/// converts the given @c Object to a function pointer via the
2409/// conversion function @c Conversion, and then attempts to call it
2410/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2411/// the type of function that we'll eventually be calling.
2412void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002413 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002414 Expr *Object, Expr **Args, unsigned NumArgs,
2415 OverloadCandidateSet& CandidateSet) {
2416 CandidateSet.push_back(OverloadCandidate());
2417 OverloadCandidate& Candidate = CandidateSet.back();
2418 Candidate.Function = 0;
2419 Candidate.Surrogate = Conversion;
2420 Candidate.Viable = true;
2421 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002422 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002423 Candidate.Conversions.resize(NumArgs + 1);
2424
2425 // Determine the implicit conversion sequence for the implicit
2426 // object parameter.
2427 ImplicitConversionSequence ObjectInit
2428 = TryObjectArgumentInitialization(Object, Conversion);
2429 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2430 Candidate.Viable = false;
2431 return;
2432 }
2433
2434 // The first conversion is actually a user-defined conversion whose
2435 // first conversion is ObjectInit's standard conversion (which is
2436 // effectively a reference binding). Record it as such.
2437 Candidate.Conversions[0].ConversionKind
2438 = ImplicitConversionSequence::UserDefinedConversion;
2439 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2440 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2441 Candidate.Conversions[0].UserDefined.After
2442 = Candidate.Conversions[0].UserDefined.Before;
2443 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2444
2445 // Find the
2446 unsigned NumArgsInProto = Proto->getNumArgs();
2447
2448 // (C++ 13.3.2p2): A candidate function having fewer than m
2449 // parameters is viable only if it has an ellipsis in its parameter
2450 // list (8.3.5).
2451 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2452 Candidate.Viable = false;
2453 return;
2454 }
2455
2456 // Function types don't have any default arguments, so just check if
2457 // we have enough arguments.
2458 if (NumArgs < NumArgsInProto) {
2459 // Not enough arguments.
2460 Candidate.Viable = false;
2461 return;
2462 }
2463
2464 // Determine the implicit conversion sequences for each of the
2465 // arguments.
2466 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2467 if (ArgIdx < NumArgsInProto) {
2468 // (C++ 13.3.2p3): for F to be a viable function, there shall
2469 // exist for each argument an implicit conversion sequence
2470 // (13.3.3.1) that converts that argument to the corresponding
2471 // parameter of F.
2472 QualType ParamType = Proto->getArgType(ArgIdx);
2473 Candidate.Conversions[ArgIdx + 1]
2474 = TryCopyInitialization(Args[ArgIdx], ParamType,
2475 /*SuppressUserConversions=*/false);
2476 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2477 == ImplicitConversionSequence::BadConversion) {
2478 Candidate.Viable = false;
2479 break;
2480 }
2481 } else {
2482 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2483 // argument for which there is no corresponding parameter is
2484 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2485 Candidate.Conversions[ArgIdx + 1].ConversionKind
2486 = ImplicitConversionSequence::EllipsisConversion;
2487 }
2488 }
2489}
2490
Mike Stumpe127ae32009-05-16 07:39:55 +00002491// FIXME: This will eventually be removed, once we've migrated all of the
2492// operator overloading logic over to the scheme used by binary operators, which
2493// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002494void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002495 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002496 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002497 OverloadCandidateSet& CandidateSet,
2498 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002499
2500 FunctionSet Functions;
2501
2502 QualType T1 = Args[0]->getType();
2503 QualType T2;
2504 if (NumArgs > 1)
2505 T2 = Args[1]->getType();
2506
2507 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002508 if (S)
2509 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002510 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2511 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2512 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2513 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2514}
2515
2516/// \brief Add overload candidates for overloaded operators that are
2517/// member functions.
2518///
2519/// Add the overloaded operator candidates that are member functions
2520/// for the operator Op that was used in an operator expression such
2521/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2522/// CandidateSet will store the added overload candidates. (C++
2523/// [over.match.oper]).
2524void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2525 SourceLocation OpLoc,
2526 Expr **Args, unsigned NumArgs,
2527 OverloadCandidateSet& CandidateSet,
2528 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002529 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2530
2531 // C++ [over.match.oper]p3:
2532 // For a unary operator @ with an operand of a type whose
2533 // cv-unqualified version is T1, and for a binary operator @ with
2534 // a left operand of a type whose cv-unqualified version is T1 and
2535 // a right operand of a type whose cv-unqualified version is T2,
2536 // three sets of candidate functions, designated member
2537 // candidates, non-member candidates and built-in candidates, are
2538 // constructed as follows:
2539 QualType T1 = Args[0]->getType();
2540 QualType T2;
2541 if (NumArgs > 1)
2542 T2 = Args[1]->getType();
2543
2544 // -- If T1 is a class type, the set of member candidates is the
2545 // result of the qualified lookup of T1::operator@
2546 // (13.3.1.1.1); otherwise, the set of member candidates is
2547 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002548 // FIXME: Lookup in base classes, too!
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002549 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002550 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002551 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002552 Oper != OperEnd; ++Oper)
2553 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2554 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002555 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002556 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002557}
2558
Douglas Gregor70d26122008-11-12 17:17:38 +00002559/// AddBuiltinCandidate - Add a candidate for a built-in
2560/// operator. ResultTy and ParamTys are the result and parameter types
2561/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002562/// arguments being passed to the candidate. IsAssignmentOperator
2563/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002564/// operator. NumContextualBoolArguments is the number of arguments
2565/// (at the beginning of the argument list) that will be contextually
2566/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002567void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2568 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002569 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002570 bool IsAssignmentOperator,
2571 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002572 // Add this candidate
2573 CandidateSet.push_back(OverloadCandidate());
2574 OverloadCandidate& Candidate = CandidateSet.back();
2575 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002576 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002577 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002578 Candidate.BuiltinTypes.ResultTy = ResultTy;
2579 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2580 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2581
2582 // Determine the implicit conversion sequences for each of the
2583 // arguments.
2584 Candidate.Viable = true;
2585 Candidate.Conversions.resize(NumArgs);
2586 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002587 // C++ [over.match.oper]p4:
2588 // For the built-in assignment operators, conversions of the
2589 // left operand are restricted as follows:
2590 // -- no temporaries are introduced to hold the left operand, and
2591 // -- no user-defined conversions are applied to the left
2592 // operand to achieve a type match with the left-most
2593 // parameter of a built-in candidate.
2594 //
2595 // We block these conversions by turning off user-defined
2596 // conversions, since that is the only way that initialization of
2597 // a reference to a non-class type can occur from something that
2598 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002599 if (ArgIdx < NumContextualBoolArguments) {
2600 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2601 "Contextual conversion to bool requires bool type");
2602 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2603 } else {
2604 Candidate.Conversions[ArgIdx]
2605 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2606 ArgIdx == 0 && IsAssignmentOperator);
2607 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002608 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002609 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002610 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002611 break;
2612 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002613 }
2614}
2615
2616/// BuiltinCandidateTypeSet - A set of types that will be used for the
2617/// candidate operator functions for built-in operators (C++
2618/// [over.built]). The types are separated into pointer types and
2619/// enumeration types.
2620class BuiltinCandidateTypeSet {
2621 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002622 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002623
2624 /// PointerTypes - The set of pointer types that will be used in the
2625 /// built-in candidates.
2626 TypeSet PointerTypes;
2627
Sebastian Redl674d1b72009-04-19 21:53:20 +00002628 /// MemberPointerTypes - The set of member pointer types that will be
2629 /// used in the built-in candidates.
2630 TypeSet MemberPointerTypes;
2631
Douglas Gregor70d26122008-11-12 17:17:38 +00002632 /// EnumerationTypes - The set of enumeration types that will be
2633 /// used in the built-in candidates.
2634 TypeSet EnumerationTypes;
2635
2636 /// Context - The AST context in which we will build the type sets.
2637 ASTContext &Context;
2638
Sebastian Redl674d1b72009-04-19 21:53:20 +00002639 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2640 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002641
2642public:
2643 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002644 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002645
2646 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2647
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002648 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2649 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002650
2651 /// pointer_begin - First pointer type found;
2652 iterator pointer_begin() { return PointerTypes.begin(); }
2653
Sebastian Redl674d1b72009-04-19 21:53:20 +00002654 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002655 iterator pointer_end() { return PointerTypes.end(); }
2656
Sebastian Redl674d1b72009-04-19 21:53:20 +00002657 /// member_pointer_begin - First member pointer type found;
2658 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2659
2660 /// member_pointer_end - Past the last member pointer type found;
2661 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2662
Douglas Gregor70d26122008-11-12 17:17:38 +00002663 /// enumeration_begin - First enumeration type found;
2664 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2665
Sebastian Redl674d1b72009-04-19 21:53:20 +00002666 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002667 iterator enumeration_end() { return EnumerationTypes.end(); }
2668};
2669
Sebastian Redl674d1b72009-04-19 21:53:20 +00002670/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002671/// the set of pointer types along with any more-qualified variants of
2672/// that type. For example, if @p Ty is "int const *", this routine
2673/// will add "int const *", "int const volatile *", "int const
2674/// restrict *", and "int const volatile restrict *" to the set of
2675/// pointer types. Returns true if the add of @p Ty itself succeeded,
2676/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002677bool
2678BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002679 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002680 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002681 return false;
2682
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002683 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002684 QualType PointeeTy = PointerTy->getPointeeType();
2685 // FIXME: Optimize this so that we don't keep trying to add the same types.
2686
Mike Stumpe127ae32009-05-16 07:39:55 +00002687 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2688 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002689 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002690 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002691 (Context.getPointerType(PointeeTy.withConst()));
2692 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002693 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002694 (Context.getPointerType(PointeeTy.withVolatile()));
2695 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002696 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002697 (Context.getPointerType(PointeeTy.withRestrict()));
2698 }
2699
2700 return true;
2701}
2702
Sebastian Redl674d1b72009-04-19 21:53:20 +00002703/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2704/// to the set of pointer types along with any more-qualified variants of
2705/// that type. For example, if @p Ty is "int const *", this routine
2706/// will add "int const *", "int const volatile *", "int const
2707/// restrict *", and "int const volatile restrict *" to the set of
2708/// pointer types. Returns true if the add of @p Ty itself succeeded,
2709/// false otherwise.
2710bool
2711BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2712 QualType Ty) {
2713 // Insert this type.
2714 if (!MemberPointerTypes.insert(Ty))
2715 return false;
2716
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002717 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl674d1b72009-04-19 21:53:20 +00002718 QualType PointeeTy = PointerTy->getPointeeType();
2719 const Type *ClassTy = PointerTy->getClass();
2720 // FIXME: Optimize this so that we don't keep trying to add the same types.
2721
2722 if (!PointeeTy.isConstQualified())
2723 AddMemberPointerWithMoreQualifiedTypeVariants
2724 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2725 if (!PointeeTy.isVolatileQualified())
2726 AddMemberPointerWithMoreQualifiedTypeVariants
2727 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2728 if (!PointeeTy.isRestrictQualified())
2729 AddMemberPointerWithMoreQualifiedTypeVariants
2730 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2731 }
2732
2733 return true;
2734}
2735
Douglas Gregor70d26122008-11-12 17:17:38 +00002736/// AddTypesConvertedFrom - Add each of the types to which the type @p
2737/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002738/// primarily interested in pointer types and enumeration types. We also
2739/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002740/// AllowUserConversions is true if we should look at the conversion
2741/// functions of a class type, and AllowExplicitConversions if we
2742/// should also include the explicit conversion functions of a class
2743/// type.
2744void
2745BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2746 bool AllowUserConversions,
2747 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002748 // Only deal with canonical types.
2749 Ty = Context.getCanonicalType(Ty);
2750
2751 // Look through reference types; they aren't part of the type of an
2752 // expression for the purposes of conversions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002753 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregor70d26122008-11-12 17:17:38 +00002754 Ty = RefTy->getPointeeType();
2755
2756 // We don't care about qualifiers on the type.
2757 Ty = Ty.getUnqualifiedType();
2758
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002759 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002760 QualType PointeeTy = PointerTy->getPointeeType();
2761
2762 // Insert our type, and its more-qualified variants, into the set
2763 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002764 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002765 return;
2766
2767 // Add 'cv void*' to our set of types.
2768 if (!Ty->isVoidType()) {
2769 QualType QualVoid
2770 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002771 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002772 }
2773
2774 // If this is a pointer to a class type, add pointers to its bases
2775 // (with the same level of cv-qualification as the original
2776 // derived class, of course).
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002777 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002778 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2779 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2780 Base != ClassDecl->bases_end(); ++Base) {
2781 QualType BaseTy = Context.getCanonicalType(Base->getType());
2782 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2783
2784 // Add the pointer type, recursively, so that we get all of
2785 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002786 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002787 }
2788 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002789 } else if (Ty->isMemberPointerType()) {
2790 // Member pointers are far easier, since the pointee can't be converted.
2791 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2792 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002793 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002794 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002795 } else if (AllowUserConversions) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002796 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002797 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2798 // FIXME: Visit conversion functions in the base classes, too.
2799 OverloadedFunctionDecl *Conversions
2800 = ClassDecl->getConversionFunctions();
2801 for (OverloadedFunctionDecl::function_iterator Func
2802 = Conversions->function_begin();
2803 Func != Conversions->function_end(); ++Func) {
2804 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002805 if (AllowExplicitConversions || !Conv->isExplicit())
2806 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002807 }
2808 }
2809 }
2810}
2811
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002812/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2813/// operator overloads to the candidate set (C++ [over.built]), based
2814/// on the operator @p Op and the arguments given. For example, if the
2815/// operator is a binary '+', this routine might add "int
2816/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002817void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002818Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2819 Expr **Args, unsigned NumArgs,
2820 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002821 // The set of "promoted arithmetic types", which are the arithmetic
2822 // types are that preserved by promotion (C++ [over.built]p2). Note
2823 // that the first few of these types are the promoted integral
2824 // types; these types need to be first.
2825 // FIXME: What about complex?
2826 const unsigned FirstIntegralType = 0;
2827 const unsigned LastIntegralType = 13;
2828 const unsigned FirstPromotedIntegralType = 7,
2829 LastPromotedIntegralType = 13;
2830 const unsigned FirstPromotedArithmeticType = 7,
2831 LastPromotedArithmeticType = 16;
2832 const unsigned NumArithmeticTypes = 16;
2833 QualType ArithmeticTypes[NumArithmeticTypes] = {
Alisdair Meredith2bcacb62009-07-14 06:30:34 +00002834 Context.BoolTy, Context.CharTy, Context.WCharTy,
2835// Context.Char16Ty, Context.Char32Ty,
Douglas Gregor70d26122008-11-12 17:17:38 +00002836 Context.SignedCharTy, Context.ShortTy,
2837 Context.UnsignedCharTy, Context.UnsignedShortTy,
2838 Context.IntTy, Context.LongTy, Context.LongLongTy,
2839 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2840 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2841 };
2842
2843 // Find all of the types that the arguments can convert to, but only
2844 // if the operator we're looking at has built-in operator candidates
2845 // that make use of these types.
2846 BuiltinCandidateTypeSet CandidateTypes(Context);
2847 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2848 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002849 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002850 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002851 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00002852 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002853 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002854 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2855 true,
2856 (Op == OO_Exclaim ||
2857 Op == OO_AmpAmp ||
2858 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002859 }
2860
2861 bool isComparison = false;
2862 switch (Op) {
2863 case OO_None:
2864 case NUM_OVERLOADED_OPERATORS:
2865 assert(false && "Expected an overloaded operator");
2866 break;
2867
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002868 case OO_Star: // '*' is either unary or binary
2869 if (NumArgs == 1)
2870 goto UnaryStar;
2871 else
2872 goto BinaryStar;
2873 break;
2874
2875 case OO_Plus: // '+' is either unary or binary
2876 if (NumArgs == 1)
2877 goto UnaryPlus;
2878 else
2879 goto BinaryPlus;
2880 break;
2881
2882 case OO_Minus: // '-' is either unary or binary
2883 if (NumArgs == 1)
2884 goto UnaryMinus;
2885 else
2886 goto BinaryMinus;
2887 break;
2888
2889 case OO_Amp: // '&' is either unary or binary
2890 if (NumArgs == 1)
2891 goto UnaryAmp;
2892 else
2893 goto BinaryAmp;
2894
2895 case OO_PlusPlus:
2896 case OO_MinusMinus:
2897 // C++ [over.built]p3:
2898 //
2899 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2900 // is either volatile or empty, there exist candidate operator
2901 // functions of the form
2902 //
2903 // VQ T& operator++(VQ T&);
2904 // T operator++(VQ T&, int);
2905 //
2906 // C++ [over.built]p4:
2907 //
2908 // For every pair (T, VQ), where T is an arithmetic type other
2909 // than bool, and VQ is either volatile or empty, there exist
2910 // candidate operator functions of the form
2911 //
2912 // VQ T& operator--(VQ T&);
2913 // T operator--(VQ T&, int);
2914 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2915 Arith < NumArithmeticTypes; ++Arith) {
2916 QualType ArithTy = ArithmeticTypes[Arith];
2917 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00002918 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002919
2920 // Non-volatile version.
2921 if (NumArgs == 1)
2922 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2923 else
2924 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2925
2926 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00002927 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002928 if (NumArgs == 1)
2929 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2930 else
2931 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2932 }
2933
2934 // C++ [over.built]p5:
2935 //
2936 // For every pair (T, VQ), where T is a cv-qualified or
2937 // cv-unqualified object type, and VQ is either volatile or
2938 // empty, there exist candidate operator functions of the form
2939 //
2940 // T*VQ& operator++(T*VQ&);
2941 // T*VQ& operator--(T*VQ&);
2942 // T* operator++(T*VQ&, int);
2943 // T* operator--(T*VQ&, int);
2944 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2945 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2946 // Skip pointer types that aren't pointers to object types.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002947 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002948 continue;
2949
2950 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002951 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002952 };
2953
2954 // Without volatile
2955 if (NumArgs == 1)
2956 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2957 else
2958 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2959
2960 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2961 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00002962 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002963 if (NumArgs == 1)
2964 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2965 else
2966 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2967 }
2968 }
2969 break;
2970
2971 UnaryStar:
2972 // C++ [over.built]p6:
2973 // For every cv-qualified or cv-unqualified object type T, there
2974 // exist candidate operator functions of the form
2975 //
2976 // T& operator*(T*);
2977 //
2978 // C++ [over.built]p7:
2979 // For every function type T, there exist candidate operator
2980 // functions of the form
2981 // T& operator*(T*);
2982 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2983 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2984 QualType ParamTy = *Ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002985 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00002986 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002987 &ParamTy, Args, 1, CandidateSet);
2988 }
2989 break;
2990
2991 UnaryPlus:
2992 // C++ [over.built]p8:
2993 // For every type T, there exist candidate operator functions of
2994 // the form
2995 //
2996 // T* operator+(T*);
2997 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2998 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2999 QualType ParamTy = *Ptr;
3000 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3001 }
3002
3003 // Fall through
3004
3005 UnaryMinus:
3006 // C++ [over.built]p9:
3007 // For every promoted arithmetic type T, there exist candidate
3008 // operator functions of the form
3009 //
3010 // T operator+(T);
3011 // T operator-(T);
3012 for (unsigned Arith = FirstPromotedArithmeticType;
3013 Arith < LastPromotedArithmeticType; ++Arith) {
3014 QualType ArithTy = ArithmeticTypes[Arith];
3015 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3016 }
3017 break;
3018
3019 case OO_Tilde:
3020 // C++ [over.built]p10:
3021 // For every promoted integral type T, there exist candidate
3022 // operator functions of the form
3023 //
3024 // T operator~(T);
3025 for (unsigned Int = FirstPromotedIntegralType;
3026 Int < LastPromotedIntegralType; ++Int) {
3027 QualType IntTy = ArithmeticTypes[Int];
3028 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3029 }
3030 break;
3031
Douglas Gregor70d26122008-11-12 17:17:38 +00003032 case OO_New:
3033 case OO_Delete:
3034 case OO_Array_New:
3035 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00003036 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003037 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00003038 break;
3039
3040 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003041 UnaryAmp:
3042 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00003043 // C++ [over.match.oper]p3:
3044 // -- For the operator ',', the unary operator '&', or the
3045 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00003046 break;
3047
3048 case OO_Less:
3049 case OO_Greater:
3050 case OO_LessEqual:
3051 case OO_GreaterEqual:
3052 case OO_EqualEqual:
3053 case OO_ExclaimEqual:
3054 // C++ [over.built]p15:
3055 //
3056 // For every pointer or enumeration type T, there exist
3057 // candidate operator functions of the form
3058 //
3059 // bool operator<(T, T);
3060 // bool operator>(T, T);
3061 // bool operator<=(T, T);
3062 // bool operator>=(T, T);
3063 // bool operator==(T, T);
3064 // bool operator!=(T, T);
3065 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3066 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3067 QualType ParamTypes[2] = { *Ptr, *Ptr };
3068 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3069 }
3070 for (BuiltinCandidateTypeSet::iterator Enum
3071 = CandidateTypes.enumeration_begin();
3072 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3073 QualType ParamTypes[2] = { *Enum, *Enum };
3074 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3075 }
3076
3077 // Fall through.
3078 isComparison = true;
3079
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003080 BinaryPlus:
3081 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003082 if (!isComparison) {
3083 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3084
3085 // C++ [over.built]p13:
3086 //
3087 // For every cv-qualified or cv-unqualified object type T
3088 // there exist candidate operator functions of the form
3089 //
3090 // T* operator+(T*, ptrdiff_t);
3091 // T& operator[](T*, ptrdiff_t); [BELOW]
3092 // T* operator-(T*, ptrdiff_t);
3093 // T* operator+(ptrdiff_t, T*);
3094 // T& operator[](ptrdiff_t, T*); [BELOW]
3095 //
3096 // C++ [over.built]p14:
3097 //
3098 // For every T, where T is a pointer to object type, there
3099 // exist candidate operator functions of the form
3100 //
3101 // ptrdiff_t operator-(T, T);
3102 for (BuiltinCandidateTypeSet::iterator Ptr
3103 = CandidateTypes.pointer_begin();
3104 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3105 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3106
3107 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3108 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3109
3110 if (Op == OO_Plus) {
3111 // T* operator+(ptrdiff_t, T*);
3112 ParamTypes[0] = ParamTypes[1];
3113 ParamTypes[1] = *Ptr;
3114 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3115 } else {
3116 // ptrdiff_t operator-(T, T);
3117 ParamTypes[1] = *Ptr;
3118 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3119 Args, 2, CandidateSet);
3120 }
3121 }
3122 }
3123 // Fall through
3124
Douglas Gregor70d26122008-11-12 17:17:38 +00003125 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003126 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003127 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003128 // C++ [over.built]p12:
3129 //
3130 // For every pair of promoted arithmetic types L and R, there
3131 // exist candidate operator functions of the form
3132 //
3133 // LR operator*(L, R);
3134 // LR operator/(L, R);
3135 // LR operator+(L, R);
3136 // LR operator-(L, R);
3137 // bool operator<(L, R);
3138 // bool operator>(L, R);
3139 // bool operator<=(L, R);
3140 // bool operator>=(L, R);
3141 // bool operator==(L, R);
3142 // bool operator!=(L, R);
3143 //
3144 // where LR is the result of the usual arithmetic conversions
3145 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003146 //
3147 // C++ [over.built]p24:
3148 //
3149 // For every pair of promoted arithmetic types L and R, there exist
3150 // candidate operator functions of the form
3151 //
3152 // LR operator?(bool, L, R);
3153 //
3154 // where LR is the result of the usual arithmetic conversions
3155 // between types L and R.
3156 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003157 for (unsigned Left = FirstPromotedArithmeticType;
3158 Left < LastPromotedArithmeticType; ++Left) {
3159 for (unsigned Right = FirstPromotedArithmeticType;
3160 Right < LastPromotedArithmeticType; ++Right) {
3161 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman6ae7d112009-08-19 07:44:53 +00003162 QualType Result
3163 = isComparison
3164 ? Context.BoolTy
3165 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003166 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3167 }
3168 }
3169 break;
3170
3171 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003172 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003173 case OO_Caret:
3174 case OO_Pipe:
3175 case OO_LessLess:
3176 case OO_GreaterGreater:
3177 // C++ [over.built]p17:
3178 //
3179 // For every pair of promoted integral types L and R, there
3180 // exist candidate operator functions of the form
3181 //
3182 // LR operator%(L, R);
3183 // LR operator&(L, R);
3184 // LR operator^(L, R);
3185 // LR operator|(L, R);
3186 // L operator<<(L, R);
3187 // L operator>>(L, R);
3188 //
3189 // where LR is the result of the usual arithmetic conversions
3190 // between types L and R.
3191 for (unsigned Left = FirstPromotedIntegralType;
3192 Left < LastPromotedIntegralType; ++Left) {
3193 for (unsigned Right = FirstPromotedIntegralType;
3194 Right < LastPromotedIntegralType; ++Right) {
3195 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3196 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3197 ? LandR[0]
Eli Friedman6ae7d112009-08-19 07:44:53 +00003198 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003199 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3200 }
3201 }
3202 break;
3203
3204 case OO_Equal:
3205 // C++ [over.built]p20:
3206 //
3207 // For every pair (T, VQ), where T is an enumeration or
3208 // (FIXME:) pointer to member type and VQ is either volatile or
3209 // empty, there exist candidate operator functions of the form
3210 //
3211 // VQ T& operator=(VQ T&, T);
3212 for (BuiltinCandidateTypeSet::iterator Enum
3213 = CandidateTypes.enumeration_begin();
3214 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3215 QualType ParamTypes[2];
3216
3217 // T& operator=(T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003218 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregor70d26122008-11-12 17:17:38 +00003219 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003220 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003221 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003222
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003223 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3224 // volatile T& operator=(volatile T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003225 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003226 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003227 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003228 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003229 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003230 }
3231 // Fall through.
3232
3233 case OO_PlusEqual:
3234 case OO_MinusEqual:
3235 // C++ [over.built]p19:
3236 //
3237 // For every pair (T, VQ), where T is any type and VQ is either
3238 // volatile or empty, there exist candidate operator functions
3239 // of the form
3240 //
3241 // T*VQ& operator=(T*VQ&, T*);
3242 //
3243 // C++ [over.built]p21:
3244 //
3245 // For every pair (T, VQ), where T is a cv-qualified or
3246 // cv-unqualified object type and VQ is either volatile or
3247 // empty, there exist candidate operator functions of the form
3248 //
3249 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3250 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3251 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3252 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3253 QualType ParamTypes[2];
3254 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3255
3256 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003257 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003258 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3259 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003260
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003261 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3262 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003263 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003264 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3265 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003266 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003267 }
3268 // Fall through.
3269
3270 case OO_StarEqual:
3271 case OO_SlashEqual:
3272 // C++ [over.built]p18:
3273 //
3274 // For every triple (L, VQ, R), where L is an arithmetic type,
3275 // VQ is either volatile or empty, and R is a promoted
3276 // arithmetic type, there exist candidate operator functions of
3277 // the form
3278 //
3279 // VQ L& operator=(VQ L&, R);
3280 // VQ L& operator*=(VQ L&, R);
3281 // VQ L& operator/=(VQ L&, R);
3282 // VQ L& operator+=(VQ L&, R);
3283 // VQ L& operator-=(VQ L&, R);
3284 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3285 for (unsigned Right = FirstPromotedArithmeticType;
3286 Right < LastPromotedArithmeticType; ++Right) {
3287 QualType ParamTypes[2];
3288 ParamTypes[1] = ArithmeticTypes[Right];
3289
3290 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003291 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003292 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3293 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003294
3295 // Add this built-in operator as a candidate (VQ is 'volatile').
3296 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003297 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003298 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3299 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003300 }
3301 }
3302 break;
3303
3304 case OO_PercentEqual:
3305 case OO_LessLessEqual:
3306 case OO_GreaterGreaterEqual:
3307 case OO_AmpEqual:
3308 case OO_CaretEqual:
3309 case OO_PipeEqual:
3310 // C++ [over.built]p22:
3311 //
3312 // For every triple (L, VQ, R), where L is an integral type, VQ
3313 // is either volatile or empty, and R is a promoted integral
3314 // type, there exist candidate operator functions of the form
3315 //
3316 // VQ L& operator%=(VQ L&, R);
3317 // VQ L& operator<<=(VQ L&, R);
3318 // VQ L& operator>>=(VQ L&, R);
3319 // VQ L& operator&=(VQ L&, R);
3320 // VQ L& operator^=(VQ L&, R);
3321 // VQ L& operator|=(VQ L&, R);
3322 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3323 for (unsigned Right = FirstPromotedIntegralType;
3324 Right < LastPromotedIntegralType; ++Right) {
3325 QualType ParamTypes[2];
3326 ParamTypes[1] = ArithmeticTypes[Right];
3327
3328 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003329 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003330 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3331
3332 // Add this built-in operator as a candidate (VQ is 'volatile').
3333 ParamTypes[0] = ArithmeticTypes[Left];
3334 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003335 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003336 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3337 }
3338 }
3339 break;
3340
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003341 case OO_Exclaim: {
3342 // C++ [over.operator]p23:
3343 //
3344 // There also exist candidate operator functions of the form
3345 //
3346 // bool operator!(bool);
3347 // bool operator&&(bool, bool); [BELOW]
3348 // bool operator||(bool, bool); [BELOW]
3349 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003350 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3351 /*IsAssignmentOperator=*/false,
3352 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003353 break;
3354 }
3355
Douglas Gregor70d26122008-11-12 17:17:38 +00003356 case OO_AmpAmp:
3357 case OO_PipePipe: {
3358 // C++ [over.operator]p23:
3359 //
3360 // There also exist candidate operator functions of the form
3361 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003362 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003363 // bool operator&&(bool, bool);
3364 // bool operator||(bool, bool);
3365 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003366 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3367 /*IsAssignmentOperator=*/false,
3368 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003369 break;
3370 }
3371
3372 case OO_Subscript:
3373 // C++ [over.built]p13:
3374 //
3375 // For every cv-qualified or cv-unqualified object type T there
3376 // exist candidate operator functions of the form
3377 //
3378 // T* operator+(T*, ptrdiff_t); [ABOVE]
3379 // T& operator[](T*, ptrdiff_t);
3380 // T* operator-(T*, ptrdiff_t); [ABOVE]
3381 // T* operator+(ptrdiff_t, T*); [ABOVE]
3382 // T& operator[](ptrdiff_t, T*);
3383 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3384 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3385 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003386 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003387 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003388
3389 // T& operator[](T*, ptrdiff_t)
3390 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3391
3392 // T& operator[](ptrdiff_t, T*);
3393 ParamTypes[0] = ParamTypes[1];
3394 ParamTypes[1] = *Ptr;
3395 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3396 }
3397 break;
3398
3399 case OO_ArrowStar:
3400 // FIXME: No support for pointer-to-members yet.
3401 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003402
3403 case OO_Conditional:
3404 // Note that we don't consider the first argument, since it has been
3405 // contextually converted to bool long ago. The candidates below are
3406 // therefore added as binary.
3407 //
3408 // C++ [over.built]p24:
3409 // For every type T, where T is a pointer or pointer-to-member type,
3410 // there exist candidate operator functions of the form
3411 //
3412 // T operator?(bool, T, T);
3413 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003414 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3415 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3416 QualType ParamTypes[2] = { *Ptr, *Ptr };
3417 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3418 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003419 for (BuiltinCandidateTypeSet::iterator Ptr =
3420 CandidateTypes.member_pointer_begin(),
3421 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3422 QualType ParamTypes[2] = { *Ptr, *Ptr };
3423 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3424 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003425 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003426 }
3427}
3428
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003429/// \brief Add function candidates found via argument-dependent lookup
3430/// to the set of overloading candidates.
3431///
3432/// This routine performs argument-dependent name lookup based on the
3433/// given function name (which may also be an operator name) and adds
3434/// all of the overload candidates found by ADL to the overload
3435/// candidate set (C++ [basic.lookup.argdep]).
3436void
3437Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3438 Expr **Args, unsigned NumArgs,
3439 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003440 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003441
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003442 // Record all of the function candidates that we've already
3443 // added to the overload set, so that we don't add those same
3444 // candidates a second time.
3445 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3446 CandEnd = CandidateSet.end();
3447 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003448 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003449 Functions.insert(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003450 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3451 Functions.insert(FunTmpl);
3452 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003453
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003454 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003455
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003456 // Erase all of the candidates we already knew about.
3457 // FIXME: This is suboptimal. Is there a better way?
3458 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3459 CandEnd = CandidateSet.end();
3460 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003461 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003462 Functions.erase(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003463 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3464 Functions.erase(FunTmpl);
3465 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003466
3467 // For each of the ADL candidates we found, add it to the overload
3468 // set.
3469 for (FunctionSet::iterator Func = Functions.begin(),
3470 FuncEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00003471 Func != FuncEnd; ++Func) {
3472 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3473 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3474 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003475 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3476 /*FIXME: explicit args */false, 0, 0,
3477 Args, NumArgs, CandidateSet);
Douglas Gregor993a0602009-06-27 21:05:07 +00003478 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003479}
3480
Douglas Gregord2baafd2008-10-21 16:13:35 +00003481/// isBetterOverloadCandidate - Determines whether the first overload
3482/// candidate is a better candidate than the second (C++ 13.3.3p1).
3483bool
3484Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3485 const OverloadCandidate& Cand2)
3486{
3487 // Define viable functions to be better candidates than non-viable
3488 // functions.
3489 if (!Cand2.Viable)
3490 return Cand1.Viable;
3491 else if (!Cand1.Viable)
3492 return false;
3493
Douglas Gregor3257fb52008-12-22 05:46:06 +00003494 // C++ [over.match.best]p1:
3495 //
3496 // -- if F is a static member function, ICS1(F) is defined such
3497 // that ICS1(F) is neither better nor worse than ICS1(G) for
3498 // any function G, and, symmetrically, ICS1(G) is neither
3499 // better nor worse than ICS1(F).
3500 unsigned StartArg = 0;
3501 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3502 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003503
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003504 // C++ [over.match.best]p1:
3505 // A viable function F1 is defined to be a better function than another
3506 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3507 // conversion sequence than ICSi(F2), and then...
Douglas Gregord2baafd2008-10-21 16:13:35 +00003508 unsigned NumArgs = Cand1.Conversions.size();
3509 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3510 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003511 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003512 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3513 Cand2.Conversions[ArgIdx])) {
3514 case ImplicitConversionSequence::Better:
3515 // Cand1 has a better conversion sequence.
3516 HasBetterConversion = true;
3517 break;
3518
3519 case ImplicitConversionSequence::Worse:
3520 // Cand1 can't be better than Cand2.
3521 return false;
3522
3523 case ImplicitConversionSequence::Indistinguishable:
3524 // Do nothing.
3525 break;
3526 }
3527 }
3528
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003529 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3530 // ICSj(F2), or, if not that,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003531 if (HasBetterConversion)
3532 return true;
3533
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003534 // - F1 is a non-template function and F2 is a function template
3535 // specialization, or, if not that,
3536 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3537 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3538 return true;
3539
3540 // -- F1 and F2 are function template specializations, and the function
3541 // template for F1 is more specialized than the template for F2
3542 // according to the partial ordering rules described in 14.5.5.2, or,
3543 // if not that,
Douglas Gregorf8e51672009-08-02 23:46:29 +00003544 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3545 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3546 // FIXME: Implement partial ordering of function templates.
3547 Diag(SourceLocation(), diag::unsup_function_template_partial_ordering);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003548
Douglas Gregor60714f92008-11-07 22:36:19 +00003549 // -- the context is an initialization by user-defined conversion
3550 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3551 // from the return type of F1 to the destination type (i.e.,
3552 // the type of the entity being initialized) is a better
3553 // conversion sequence than the standard conversion sequence
3554 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003555 if (Cand1.Function && Cand2.Function &&
3556 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003557 isa<CXXConversionDecl>(Cand2.Function)) {
3558 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3559 Cand2.FinalConversion)) {
3560 case ImplicitConversionSequence::Better:
3561 // Cand1 has a better conversion sequence.
3562 return true;
3563
3564 case ImplicitConversionSequence::Worse:
3565 // Cand1 can't be better than Cand2.
3566 return false;
3567
3568 case ImplicitConversionSequence::Indistinguishable:
3569 // Do nothing
3570 break;
3571 }
3572 }
3573
Douglas Gregord2baafd2008-10-21 16:13:35 +00003574 return false;
3575}
3576
Douglas Gregor98189262009-06-19 23:52:42 +00003577/// \brief Computes the best viable function (C++ 13.3.3)
3578/// within an overload candidate set.
3579///
3580/// \param CandidateSet the set of candidate functions.
3581///
3582/// \param Loc the location of the function name (or operator symbol) for
3583/// which overload resolution occurs.
3584///
3585/// \param Best f overload resolution was successful or found a deleted
3586/// function, Best points to the candidate function found.
3587///
3588/// \returns The result of overload resolution.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003589Sema::OverloadingResult
3590Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003591 SourceLocation Loc,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003592 OverloadCandidateSet::iterator& Best)
3593{
3594 // Find the best viable function.
3595 Best = CandidateSet.end();
3596 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3597 Cand != CandidateSet.end(); ++Cand) {
3598 if (Cand->Viable) {
3599 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3600 Best = Cand;
3601 }
3602 }
3603
3604 // If we didn't find any viable functions, abort.
3605 if (Best == CandidateSet.end())
3606 return OR_No_Viable_Function;
3607
3608 // Make sure that this function is better than every other viable
3609 // function. If not, we have an ambiguity.
3610 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3611 Cand != CandidateSet.end(); ++Cand) {
3612 if (Cand->Viable &&
3613 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003614 !isBetterOverloadCandidate(*Best, *Cand)) {
3615 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003616 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003617 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003618 }
3619
3620 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003621 if (Best->Function &&
3622 (Best->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003623 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003624 return OR_Deleted;
3625
Douglas Gregor98189262009-06-19 23:52:42 +00003626 // C++ [basic.def.odr]p2:
3627 // An overloaded function is used if it is selected by overload resolution
3628 // when referred to from a potentially-evaluated expression. [Note: this
3629 // covers calls to named functions (5.2.2), operator overloading
3630 // (clause 13), user-defined conversions (12.3.2), allocation function for
3631 // placement new (5.3.4), as well as non-default initialization (8.5).
3632 if (Best->Function)
3633 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003634 return OR_Success;
3635}
3636
3637/// PrintOverloadCandidates - When overload resolution fails, prints
3638/// diagnostic messages containing the candidates in the candidate
3639/// set. If OnlyViable is true, only viable candidates will be printed.
3640void
3641Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3642 bool OnlyViable)
3643{
3644 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3645 LastCand = CandidateSet.end();
3646 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003647 if (Cand->Viable || !OnlyViable) {
3648 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003649 if (Cand->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003650 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003651 // Deleted or "unavailable" function.
3652 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3653 << Cand->Function->isDeleted();
3654 } else {
3655 // Normal function
3656 // FIXME: Give a better reason!
3657 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3658 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003659 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003660 // Desugar the type of the surrogate down to a function type,
3661 // retaining as many typedefs as possible while still showing
3662 // the function type (and, therefore, its parameter types).
3663 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003664 bool isLValueReference = false;
3665 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003666 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003667 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003668 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003669 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003670 isLValueReference = true;
3671 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003672 FnType->getAs<RValueReferenceType>()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003673 FnType = FnTypeRef->getPointeeType();
3674 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003675 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003676 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003677 FnType = FnTypePtr->getPointeeType();
3678 isPointer = true;
3679 }
3680 // Desugar down to a function type.
3681 FnType = QualType(FnType->getAsFunctionType(), 0);
3682 // Reconstruct the pointer/reference as appropriate.
3683 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003684 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3685 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003686
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003687 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003688 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003689 } else {
3690 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003691 // FIXME: Do we want the error message to point at the operator?
3692 // (built-ins won't have a location)
Douglas Gregor70d26122008-11-12 17:17:38 +00003693 QualType FnType
3694 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3695 Cand->BuiltinTypes.ParamTypes,
3696 Cand->Conversions.size(),
3697 false, 0);
3698
Chris Lattner4bfd2232008-11-24 06:25:27 +00003699 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003700 }
3701 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003702 }
3703}
3704
Douglas Gregor45014fd2008-11-10 20:40:00 +00003705/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3706/// an overloaded function (C++ [over.over]), where @p From is an
3707/// expression with overloaded function type and @p ToType is the type
3708/// we're trying to resolve to. For example:
3709///
3710/// @code
3711/// int f(double);
3712/// int f(int);
3713///
3714/// int (*pfd)(double) = f; // selects f(double)
3715/// @endcode
3716///
3717/// This routine returns the resulting FunctionDecl if it could be
3718/// resolved, and NULL otherwise. When @p Complain is true, this
3719/// routine will emit diagnostics if there is an error.
3720FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003721Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003722 bool Complain) {
3723 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003724 bool IsMember = false;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003725 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003726 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003727 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003728 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003729 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003730 ToType->getAs<MemberPointerType>()) {
Sebastian Redl7434fc32009-02-04 21:23:32 +00003731 FunctionType = MemTypePtr->getPointeeType();
3732 IsMember = true;
3733 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003734
3735 // We only look at pointers or references to functions.
Douglas Gregor72bb4992009-07-09 17:16:51 +00003736 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor62f78762009-07-08 20:55:45 +00003737 if (!FunctionType->isFunctionType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003738 return 0;
3739
3740 // Find the actual overloaded function declaration.
3741 OverloadedFunctionDecl *Ovl = 0;
3742
3743 // C++ [over.over]p1:
3744 // [...] [Note: any redundant set of parentheses surrounding the
3745 // overloaded function name is ignored (5.1). ]
3746 Expr *OvlExpr = From->IgnoreParens();
3747
3748 // C++ [over.over]p1:
3749 // [...] The overloaded function name can be preceded by the &
3750 // operator.
3751 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3752 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3753 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3754 }
3755
3756 // Try to dig out the overloaded function.
Douglas Gregor62f78762009-07-08 20:55:45 +00003757 FunctionTemplateDecl *FunctionTemplate = 0;
3758 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003759 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor62f78762009-07-08 20:55:45 +00003760 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3761 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003762
Douglas Gregor62f78762009-07-08 20:55:45 +00003763 // If there's no overloaded function declaration or function template,
3764 // we're done.
3765 if (!Ovl && !FunctionTemplate)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003766 return 0;
3767
Douglas Gregor62f78762009-07-08 20:55:45 +00003768 OverloadIterator Fun;
3769 if (Ovl)
3770 Fun = Ovl;
3771 else
3772 Fun = FunctionTemplate;
3773
Douglas Gregor45014fd2008-11-10 20:40:00 +00003774 // Look through all of the overloaded functions, searching for one
3775 // whose type matches exactly.
Douglas Gregora142a052009-07-08 23:33:52 +00003776 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3777
3778 bool FoundNonTemplateFunction = false;
Douglas Gregor62f78762009-07-08 20:55:45 +00003779 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003780 // C++ [over.over]p3:
3781 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003782 // targets of type "pointer-to-function" or "reference-to-function."
3783 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003784 // type "pointer-to-member-function."
3785 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor62f78762009-07-08 20:55:45 +00003786
3787 if (FunctionTemplateDecl *FunctionTemplate
3788 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003789 if (CXXMethodDecl *Method
3790 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3791 // Skip non-static function templates when converting to pointer, and
3792 // static when converting to member pointer.
3793 if (Method->isStatic() == IsMember)
3794 continue;
3795 } else if (IsMember)
3796 continue;
3797
3798 // C++ [over.over]p2:
3799 // If the name is a function template, template argument deduction is
3800 // done (14.8.2.2), and if the argument deduction succeeds, the
3801 // resulting template argument list is used to generate a single
3802 // function template specialization, which is added to the set of
3803 // overloaded functions considered.
Douglas Gregor62f78762009-07-08 20:55:45 +00003804 FunctionDecl *Specialization = 0;
3805 TemplateDeductionInfo Info(Context);
3806 if (TemplateDeductionResult Result
3807 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3808 /*FIXME:*/0, /*FIXME:*/0,
3809 FunctionType, Specialization, Info)) {
3810 // FIXME: make a note of the failed deduction for diagnostics.
3811 (void)Result;
3812 } else {
3813 assert(FunctionType
3814 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregora142a052009-07-08 23:33:52 +00003815 Matches.insert(
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003816 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor62f78762009-07-08 20:55:45 +00003817 }
3818 }
3819
Sebastian Redl7434fc32009-02-04 21:23:32 +00003820 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3821 // Skip non-static functions when converting to pointer, and static
3822 // when converting to member pointer.
3823 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003824 continue;
Douglas Gregora142a052009-07-08 23:33:52 +00003825 } else if (IsMember)
Sebastian Redl7434fc32009-02-04 21:23:32 +00003826 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003827
Douglas Gregorb60eb752009-06-25 22:08:12 +00003828 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003829 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003830 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregora142a052009-07-08 23:33:52 +00003831 FoundNonTemplateFunction = true;
3832 }
Douglas Gregor62f78762009-07-08 20:55:45 +00003833 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003834 }
3835
Douglas Gregora142a052009-07-08 23:33:52 +00003836 // If there were 0 or 1 matches, we're done.
3837 if (Matches.empty())
3838 return 0;
3839 else if (Matches.size() == 1)
3840 return *Matches.begin();
3841
3842 // C++ [over.over]p4:
3843 // If more than one function is selected, [...]
3844 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
3845 if (FoundNonTemplateFunction) {
3846 // [...] any function template specializations in the set are eliminated
3847 // if the set also contains a non-template function, [...]
3848 for (llvm::SmallPtrSet<FunctionDecl *, 4>::iterator M = Matches.begin(),
3849 MEnd = Matches.end();
3850 M != MEnd; ++M)
3851 if ((*M)->getPrimaryTemplate() == 0)
3852 RemainingMatches.push_back(*M);
3853 } else {
3854 // [...] and any given function template specialization F1 is eliminated
3855 // if the set contains a second function template specialization whose
3856 // function template is more specialized than the function template of F1
3857 // according to the partial ordering rules of 14.5.5.2.
3858 // FIXME: Implement this!
3859 RemainingMatches.append(Matches.begin(), Matches.end());
3860 }
3861
3862 // [...] After such eliminations, if any, there shall remain exactly one
3863 // selected function.
3864 if (RemainingMatches.size() == 1)
3865 return RemainingMatches.front();
3866
3867 // FIXME: We should probably return the same thing that BestViableFunction
3868 // returns (even if we issue the diagnostics here).
3869 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
3870 << RemainingMatches[0]->getDeclName();
3871 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
3872 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor45014fd2008-11-10 20:40:00 +00003873 return 0;
3874}
3875
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003876/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003877/// (which eventually refers to the declaration Func) and the call
3878/// arguments Args/NumArgs, attempt to resolve the function call down
3879/// to a specific function. If overload resolution succeeds, returns
3880/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003881/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003882/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003883FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003884 DeclarationName UnqualifiedName,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003885 bool HasExplicitTemplateArgs,
3886 const TemplateArgument *ExplicitTemplateArgs,
3887 unsigned NumExplicitTemplateArgs,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003888 SourceLocation LParenLoc,
3889 Expr **Args, unsigned NumArgs,
3890 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003891 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003892 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003893 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003894
3895 // Add the functions denoted by Callee to the set of candidate
3896 // functions. While we're doing so, track whether argument-dependent
3897 // lookup still applies, per:
3898 //
3899 // C++0x [basic.lookup.argdep]p3:
3900 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3901 // and let Y be the lookup set produced by argument dependent
3902 // lookup (defined as follows). If X contains
3903 //
3904 // -- a declaration of a class member, or
3905 //
3906 // -- a block-scope function declaration that is not a
3907 // using-declaration, or
3908 //
3909 // -- a declaration that is neither a function or a function
3910 // template
3911 //
3912 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003913 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003914 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3915 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3916 FuncEnd = Ovl->function_end();
3917 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00003918 DeclContext *Ctx = 0;
3919 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003920 if (HasExplicitTemplateArgs)
3921 continue;
3922
Douglas Gregorb60eb752009-06-25 22:08:12 +00003923 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
3924 Ctx = FunDecl->getDeclContext();
3925 } else {
3926 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003927 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
3928 ExplicitTemplateArgs,
3929 NumExplicitTemplateArgs,
3930 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00003931 Ctx = FunTmpl->getDeclContext();
3932 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003933
Douglas Gregorb60eb752009-06-25 22:08:12 +00003934
3935 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003936 ArgumentDependentLookup = false;
3937 }
3938 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003939 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003940 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3941
3942 if (Func->getDeclContext()->isRecord() ||
3943 Func->getDeclContext()->isFunctionOrMethod())
3944 ArgumentDependentLookup = false;
Douglas Gregorb60eb752009-06-25 22:08:12 +00003945 } else if (FunctionTemplateDecl *FuncTemplate
3946 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003947 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
3948 ExplicitTemplateArgs,
3949 NumExplicitTemplateArgs,
3950 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00003951
3952 if (FuncTemplate->getDeclContext()->isRecord())
3953 ArgumentDependentLookup = false;
3954 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003955
3956 if (Callee)
3957 UnqualifiedName = Callee->getDeclName();
3958
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003959 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003960 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003961 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003962 CandidateSet);
3963
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003964 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00003965 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003966 case OR_Success:
3967 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003968
3969 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00003970 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003971 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00003972 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003973 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3974 break;
3975
3976 case OR_Ambiguous:
3977 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003978 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003979 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3980 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00003981
3982 case OR_Deleted:
3983 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3984 << Best->Function->isDeleted()
3985 << UnqualifiedName
3986 << Fn->getSourceRange();
3987 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3988 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003989 }
3990
3991 // Overload resolution failed. Destroy all of the subexpressions and
3992 // return NULL.
3993 Fn->Destroy(Context);
3994 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3995 Args[Arg]->Destroy(Context);
3996 return 0;
3997}
3998
Douglas Gregorc78182d2009-03-13 23:49:33 +00003999/// \brief Create a unary operation that may resolve to an overloaded
4000/// operator.
4001///
4002/// \param OpLoc The location of the operator itself (e.g., '*').
4003///
4004/// \param OpcIn The UnaryOperator::Opcode that describes this
4005/// operator.
4006///
4007/// \param Functions The set of non-member functions that will be
4008/// considered by overload resolution. The caller needs to build this
4009/// set based on the context using, e.g.,
4010/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4011/// set should not contain any member functions; those will be added
4012/// by CreateOverloadedUnaryOp().
4013///
4014/// \param input The input argument.
4015Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4016 unsigned OpcIn,
4017 FunctionSet &Functions,
4018 ExprArg input) {
4019 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4020 Expr *Input = (Expr *)input.get();
4021
4022 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4023 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4024 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4025
4026 Expr *Args[2] = { Input, 0 };
4027 unsigned NumArgs = 1;
4028
4029 // For post-increment and post-decrement, add the implicit '0' as
4030 // the second argument, so that we know this is a post-increment or
4031 // post-decrement.
4032 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4033 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4034 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4035 SourceLocation());
4036 NumArgs = 2;
4037 }
4038
4039 if (Input->isTypeDependent()) {
4040 OverloadedFunctionDecl *Overloads
4041 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4042 for (FunctionSet::iterator Func = Functions.begin(),
4043 FuncEnd = Functions.end();
4044 Func != FuncEnd; ++Func)
4045 Overloads->addOverload(*Func);
4046
4047 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4048 OpLoc, false, false);
4049
4050 input.release();
4051 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4052 &Args[0], NumArgs,
4053 Context.DependentTy,
4054 OpLoc));
4055 }
4056
4057 // Build an empty overload set.
4058 OverloadCandidateSet CandidateSet;
4059
4060 // Add the candidates from the given function set.
4061 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4062
4063 // Add operator candidates that are member functions.
4064 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4065
4066 // Add builtin operator candidates.
4067 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4068
4069 // Perform overload resolution.
4070 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004071 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004072 case OR_Success: {
4073 // We found a built-in operator or an overloaded operator.
4074 FunctionDecl *FnDecl = Best->Function;
4075
4076 if (FnDecl) {
4077 // We matched an overloaded operator. Build a call to that
4078 // operator.
4079
4080 // Convert the arguments.
4081 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4082 if (PerformObjectArgumentInitialization(Input, Method))
4083 return ExprError();
4084 } else {
4085 // Convert the arguments.
4086 if (PerformCopyInitialization(Input,
4087 FnDecl->getParamDecl(0)->getType(),
4088 "passing"))
4089 return ExprError();
4090 }
4091
4092 // Determine the result type
4093 QualType ResultTy
4094 = FnDecl->getType()->getAsFunctionType()->getResultType();
4095 ResultTy = ResultTy.getNonReferenceType();
4096
4097 // Build the actual expression node.
4098 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4099 SourceLocation());
4100 UsualUnaryConversions(FnExpr);
4101
4102 input.release();
Anders Carlsson16497742009-08-16 04:11:06 +00004103
4104 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4105 &Input, 1, ResultTy, OpLoc);
4106 return MaybeBindToTemporary(CE);
Douglas Gregorc78182d2009-03-13 23:49:33 +00004107 } else {
4108 // We matched a built-in operator. Convert the arguments, then
4109 // break out so that we will build the appropriate built-in
4110 // operator node.
4111 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4112 Best->Conversions[0], "passing"))
4113 return ExprError();
4114
4115 break;
4116 }
4117 }
4118
4119 case OR_No_Viable_Function:
4120 // No viable function; fall through to handling this as a
4121 // built-in operator, which will produce an error message for us.
4122 break;
4123
4124 case OR_Ambiguous:
4125 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4126 << UnaryOperator::getOpcodeStr(Opc)
4127 << Input->getSourceRange();
4128 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4129 return ExprError();
4130
4131 case OR_Deleted:
4132 Diag(OpLoc, diag::err_ovl_deleted_oper)
4133 << Best->Function->isDeleted()
4134 << UnaryOperator::getOpcodeStr(Opc)
4135 << Input->getSourceRange();
4136 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4137 return ExprError();
4138 }
4139
4140 // Either we found no viable overloaded operator or we matched a
4141 // built-in operator. In either case, fall through to trying to
4142 // build a built-in operation.
4143 input.release();
4144 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4145}
4146
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004147/// \brief Create a binary operation that may resolve to an overloaded
4148/// operator.
4149///
4150/// \param OpLoc The location of the operator itself (e.g., '+').
4151///
4152/// \param OpcIn The BinaryOperator::Opcode that describes this
4153/// operator.
4154///
4155/// \param Functions The set of non-member functions that will be
4156/// considered by overload resolution. The caller needs to build this
4157/// set based on the context using, e.g.,
4158/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4159/// set should not contain any member functions; those will be added
4160/// by CreateOverloadedBinOp().
4161///
4162/// \param LHS Left-hand argument.
4163/// \param RHS Right-hand argument.
4164Sema::OwningExprResult
4165Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4166 unsigned OpcIn,
4167 FunctionSet &Functions,
4168 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004169 Expr *Args[2] = { LHS, RHS };
4170
4171 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4172 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4173 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4174
4175 // If either side is type-dependent, create an appropriate dependent
4176 // expression.
4177 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
4178 // .* cannot be overloaded.
4179 if (Opc == BinaryOperator::PtrMemD)
4180 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
4181 Context.DependentTy, OpLoc));
4182
4183 OverloadedFunctionDecl *Overloads
4184 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4185 for (FunctionSet::iterator Func = Functions.begin(),
4186 FuncEnd = Functions.end();
4187 Func != FuncEnd; ++Func)
4188 Overloads->addOverload(*Func);
4189
4190 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4191 OpLoc, false, false);
4192
4193 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4194 Args, 2,
4195 Context.DependentTy,
4196 OpLoc));
4197 }
4198
4199 // If this is the .* operator, which is not overloadable, just
4200 // create a built-in binary operator.
4201 if (Opc == BinaryOperator::PtrMemD)
4202 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4203
4204 // If this is one of the assignment operators, we only perform
4205 // overload resolution if the left-hand side is a class or
4206 // enumeration type (C++ [expr.ass]p3).
4207 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4208 !LHS->getType()->isOverloadableType())
4209 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4210
Douglas Gregorc78182d2009-03-13 23:49:33 +00004211 // Build an empty overload set.
4212 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004213
4214 // Add the candidates from the given function set.
4215 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4216
4217 // Add operator candidates that are member functions.
4218 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4219
4220 // Add builtin operator candidates.
4221 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4222
4223 // Perform overload resolution.
4224 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004225 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004226 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004227 // We found a built-in operator or an overloaded operator.
4228 FunctionDecl *FnDecl = Best->Function;
4229
4230 if (FnDecl) {
4231 // We matched an overloaded operator. Build a call to that
4232 // operator.
4233
4234 // Convert the arguments.
4235 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4236 if (PerformObjectArgumentInitialization(LHS, Method) ||
4237 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
4238 "passing"))
4239 return ExprError();
4240 } else {
4241 // Convert the arguments.
4242 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
4243 "passing") ||
4244 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
4245 "passing"))
4246 return ExprError();
4247 }
4248
4249 // Determine the result type
4250 QualType ResultTy
4251 = FnDecl->getType()->getAsFunctionType()->getResultType();
4252 ResultTy = ResultTy.getNonReferenceType();
4253
4254 // Build the actual expression node.
4255 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argiris Kirtzidiscca21b82009-07-14 03:19:38 +00004256 OpLoc);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004257 UsualUnaryConversions(FnExpr);
4258
Anders Carlsson16497742009-08-16 04:11:06 +00004259 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4260 Args, 2, ResultTy, OpLoc);
4261 return MaybeBindToTemporary(CE);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004262 } else {
4263 // We matched a built-in operator. Convert the arguments, then
4264 // break out so that we will build the appropriate built-in
4265 // operator node.
4266 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4267 Best->Conversions[0], "passing") ||
4268 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4269 Best->Conversions[1], "passing"))
4270 return ExprError();
4271
4272 break;
4273 }
4274 }
4275
4276 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004277 // For class as left operand for assignment or compound assigment operator
4278 // do not fall through to handling in built-in, but report that no overloaded
4279 // assignment operator found
4280 if (LHS->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4281 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4282 << BinaryOperator::getOpcodeStr(Opc)
4283 << LHS->getSourceRange() << RHS->getSourceRange();
4284 return ExprError();
4285 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004286 // No viable function; fall through to handling this as a
4287 // built-in operator, which will produce an error message for us.
4288 break;
4289
4290 case OR_Ambiguous:
4291 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4292 << BinaryOperator::getOpcodeStr(Opc)
4293 << LHS->getSourceRange() << RHS->getSourceRange();
4294 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4295 return ExprError();
4296
4297 case OR_Deleted:
4298 Diag(OpLoc, diag::err_ovl_deleted_oper)
4299 << Best->Function->isDeleted()
4300 << BinaryOperator::getOpcodeStr(Opc)
4301 << LHS->getSourceRange() << RHS->getSourceRange();
4302 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4303 return ExprError();
4304 }
4305
4306 // Either we found no viable overloaded operator or we matched a
4307 // built-in operator. In either case, try to build a built-in
4308 // operation.
4309 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4310}
4311
Douglas Gregor3257fb52008-12-22 05:46:06 +00004312/// BuildCallToMemberFunction - Build a call to a member
4313/// function. MemExpr is the expression that refers to the member
4314/// function (and includes the object parameter), Args/NumArgs are the
4315/// arguments to the function call (not including the object
4316/// parameter). The caller needs to validate that the member
4317/// expression refers to a member function or an overloaded member
4318/// function.
4319Sema::ExprResult
4320Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4321 SourceLocation LParenLoc, Expr **Args,
4322 unsigned NumArgs, SourceLocation *CommaLocs,
4323 SourceLocation RParenLoc) {
4324 // Dig out the member expression. This holds both the object
4325 // argument and the member function we're referring to.
4326 MemberExpr *MemExpr = 0;
4327 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4328 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4329 else
4330 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4331 assert(MemExpr && "Building member call without member expression");
4332
4333 // Extract the object argument.
4334 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004335
Douglas Gregor3257fb52008-12-22 05:46:06 +00004336 CXXMethodDecl *Method = 0;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004337 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4338 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004339 // Add overload candidates
4340 OverloadCandidateSet CandidateSet;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004341 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4342
Douglas Gregor050cabf2009-08-21 18:42:58 +00004343 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4344 Func != FuncEnd; ++Func) {
4345 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4346 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4347 /*SuppressUserConversions=*/false);
4348 else
4349 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4350 /*FIXME:*/false, /*FIXME:*/0,
4351 /*FIXME:*/0, ObjectArg, Args, NumArgs,
4352 CandidateSet,
4353 /*SuppressUsedConversions=*/false);
4354 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004355
Douglas Gregor3257fb52008-12-22 05:46:06 +00004356 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004357 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004358 case OR_Success:
4359 Method = cast<CXXMethodDecl>(Best->Function);
4360 break;
4361
4362 case OR_No_Viable_Function:
4363 Diag(MemExpr->getSourceRange().getBegin(),
4364 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004365 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004366 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4367 // FIXME: Leaking incoming expressions!
4368 return true;
4369
4370 case OR_Ambiguous:
4371 Diag(MemExpr->getSourceRange().getBegin(),
4372 diag::err_ovl_ambiguous_member_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004373 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004374 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4375 // FIXME: Leaking incoming expressions!
4376 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004377
4378 case OR_Deleted:
4379 Diag(MemExpr->getSourceRange().getBegin(),
4380 diag::err_ovl_deleted_member_call)
4381 << Best->Function->isDeleted()
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004382 << DeclName << MemExprE->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004383 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4384 // FIXME: Leaking incoming expressions!
4385 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004386 }
4387
4388 FixOverloadedFunctionReference(MemExpr, Method);
4389 } else {
4390 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4391 }
4392
4393 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004394 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004395 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4396 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004397 Method->getResultType().getNonReferenceType(),
4398 RParenLoc));
4399
4400 // Convert the object argument (for a non-static member function call).
4401 if (!Method->isStatic() &&
4402 PerformObjectArgumentInitialization(ObjectArg, Method))
4403 return true;
4404 MemExpr->setBase(ObjectArg);
4405
4406 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004407 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004408 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4409 RParenLoc))
4410 return true;
4411
Anders Carlsson7fb13802009-08-16 01:56:34 +00004412 if (CheckFunctionCall(Method, TheCall.get()))
4413 return true;
Anders Carlssonb8ff3402009-08-16 03:42:12 +00004414
4415 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004416}
4417
Douglas Gregor10f3c502008-11-19 21:05:33 +00004418/// BuildCallToObjectOfClassType - Build a call to an object of class
4419/// type (C++ [over.call.object]), which can end up invoking an
4420/// overloaded function call operator (@c operator()) or performing a
4421/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004422Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004423Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4424 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004425 Expr **Args, unsigned NumArgs,
4426 SourceLocation *CommaLocs,
4427 SourceLocation RParenLoc) {
4428 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004429 const RecordType *Record = Object->getType()->getAs<RecordType>();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004430
4431 // C++ [over.call.object]p1:
4432 // If the primary-expression E in the function call syntax
Eli Friedmand5a72f02009-08-05 19:21:58 +00004433 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor10f3c502008-11-19 21:05:33 +00004434 // candidate functions includes at least the function call
4435 // operators of T. The function call operators of T are obtained by
4436 // ordinary lookup of the name operator() in the context of
4437 // (E).operator().
4438 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004439 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004440 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004441 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004442 Oper != OperEnd; ++Oper)
4443 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4444 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004445
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004446 // C++ [over.call.object]p2:
4447 // In addition, for each conversion function declared in T of the
4448 // form
4449 //
4450 // operator conversion-type-id () cv-qualifier;
4451 //
4452 // where cv-qualifier is the same cv-qualification as, or a
4453 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004454 // denotes the type "pointer to function of (P1,...,Pn) returning
4455 // R", or the type "reference to pointer to function of
4456 // (P1,...,Pn) returning R", or the type "reference to function
4457 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004458 // is also considered as a candidate function. Similarly,
4459 // surrogate call functions are added to the set of candidate
4460 // functions for each conversion function declared in an
4461 // accessible base class provided the function is not hidden
4462 // within T by another intervening declaration.
4463 //
4464 // FIXME: Look in base classes for more conversion operators!
4465 OverloadedFunctionDecl *Conversions
4466 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004467 for (OverloadedFunctionDecl::function_iterator
4468 Func = Conversions->function_begin(),
4469 FuncEnd = Conversions->function_end();
4470 Func != FuncEnd; ++Func) {
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004471 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4472
4473 // Strip the reference type (if any) and then the pointer type (if
4474 // any) to get down to what might be a function type.
4475 QualType ConvType = Conv->getConversionType().getNonReferenceType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004476 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004477 ConvType = ConvPtrType->getPointeeType();
4478
Douglas Gregor4fa58902009-02-26 23:50:07 +00004479 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004480 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4481 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004482
4483 // Perform overload resolution.
4484 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004485 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004486 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004487 // Overload resolution succeeded; we'll build the appropriate call
4488 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004489 break;
4490
4491 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004492 Diag(Object->getSourceRange().getBegin(),
4493 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004494 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004495 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004496 break;
4497
4498 case OR_Ambiguous:
4499 Diag(Object->getSourceRange().getBegin(),
4500 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004501 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004502 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4503 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004504
4505 case OR_Deleted:
4506 Diag(Object->getSourceRange().getBegin(),
4507 diag::err_ovl_deleted_object_call)
4508 << Best->Function->isDeleted()
4509 << Object->getType() << Object->getSourceRange();
4510 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4511 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004512 }
4513
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004514 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004515 // We had an error; delete all of the subexpressions and return
4516 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004517 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004518 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004519 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004520 return true;
4521 }
4522
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004523 if (Best->Function == 0) {
4524 // Since there is no function declaration, this is one of the
4525 // surrogate candidates. Dig out the conversion function.
4526 CXXConversionDecl *Conv
4527 = cast<CXXConversionDecl>(
4528 Best->Conversions[0].UserDefined.ConversionFunction);
4529
4530 // We selected one of the surrogate functions that converts the
4531 // object parameter to a function pointer. Perform the conversion
4532 // on the object argument, then let ActOnCallExpr finish the job.
4533 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004534 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004535 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00004536 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00004537 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004538 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4539 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4540 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004541 }
4542
4543 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4544 // that calls this method, using Object for the implicit object
4545 // parameter and passing along the remaining arguments.
4546 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004547 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004548
4549 unsigned NumArgsInProto = Proto->getNumArgs();
4550 unsigned NumArgsToCheck = NumArgs;
4551
4552 // Build the full argument list for the method call (the
4553 // implicit object parameter is placed at the beginning of the
4554 // list).
4555 Expr **MethodArgs;
4556 if (NumArgs < NumArgsInProto) {
4557 NumArgsToCheck = NumArgsInProto;
4558 MethodArgs = new Expr*[NumArgsInProto + 1];
4559 } else {
4560 MethodArgs = new Expr*[NumArgs + 1];
4561 }
4562 MethodArgs[0] = Object;
4563 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4564 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4565
Ted Kremenek0c97e042009-02-07 01:47:29 +00004566 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4567 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004568 UsualUnaryConversions(NewFn);
4569
4570 // Once we've built TheCall, all of the expressions are properly
4571 // owned.
4572 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004573 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004574 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4575 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004576 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004577 delete [] MethodArgs;
4578
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004579 // We may have default arguments. If so, we need to allocate more
4580 // slots in the call for them.
4581 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004582 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004583 else if (NumArgs > NumArgsInProto)
4584 NumArgsToCheck = NumArgsInProto;
4585
Chris Lattner81f00ed2009-04-12 08:11:20 +00004586 bool IsError = false;
4587
Douglas Gregor10f3c502008-11-19 21:05:33 +00004588 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004589 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004590 TheCall->setArg(0, Object);
4591
Chris Lattner81f00ed2009-04-12 08:11:20 +00004592
Douglas Gregor10f3c502008-11-19 21:05:33 +00004593 // Check the argument types.
4594 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004595 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004596 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004597 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004598
4599 // Pass the argument.
4600 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004601 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004602 } else {
Anders Carlsson3d752db2009-08-14 18:30:22 +00004603 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004604 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004605
4606 TheCall->setArg(i + 1, Arg);
4607 }
4608
4609 // If this is a variadic call, handle args passed through "...".
4610 if (Proto->isVariadic()) {
4611 // Promote the arguments (C99 6.5.2.2p7).
4612 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4613 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004614 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004615 TheCall->setArg(i + 1, Arg);
4616 }
4617 }
4618
Chris Lattner81f00ed2009-04-12 08:11:20 +00004619 if (IsError) return true;
4620
Anders Carlsson7fb13802009-08-16 01:56:34 +00004621 if (CheckFunctionCall(Method, TheCall.get()))
4622 return true;
4623
Anders Carlsson422a5fe2009-08-16 03:53:54 +00004624 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004625}
4626
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004627/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4628/// (if one exists), where @c Base is an expression of class type and
4629/// @c Member is the name of the member we're trying to find.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004630Sema::OwningExprResult
4631Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4632 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004633 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4634
4635 // C++ [over.ref]p1:
4636 //
4637 // [...] An expression x->m is interpreted as (x.operator->())->m
4638 // for a class object x of type T if T::operator->() exists and if
4639 // the operator is selected as the best match function by the
4640 // overload resolution mechanism (13.3).
4641 // FIXME: look in base classes.
4642 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4643 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004644 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorda61ad22009-08-06 03:17:00 +00004645
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004646 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004647 for (llvm::tie(Oper, OperEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004648 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004649 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004650 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004651
4652 // Perform overload resolution.
4653 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004654 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004655 case OR_Success:
4656 // Overload resolution succeeded; we'll build the call below.
4657 break;
4658
4659 case OR_No_Viable_Function:
4660 if (CandidateSet.empty())
4661 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004662 << Base->getType() << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004663 else
4664 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004665 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004666 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004667 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004668
4669 case OR_Ambiguous:
4670 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004671 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004672 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004673 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004674
4675 case OR_Deleted:
4676 Diag(OpLoc, diag::err_ovl_deleted_oper)
4677 << Best->Function->isDeleted()
Douglas Gregorda61ad22009-08-06 03:17:00 +00004678 << "operator->" << Base->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004679 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004680 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004681 }
4682
4683 // Convert the object parameter.
4684 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004685 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorda61ad22009-08-06 03:17:00 +00004686 return ExprError();
Douglas Gregor9c690e92008-11-21 03:04:22 +00004687
4688 // No concerns about early exits now.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004689 BaseIn.release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004690
4691 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004692 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4693 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004694 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004695 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004696 Method->getResultType().getNonReferenceType(),
4697 OpLoc);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004698 return Owned(Base);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004699}
4700
Douglas Gregor45014fd2008-11-10 20:40:00 +00004701/// FixOverloadedFunctionReference - E is an expression that refers to
4702/// a C++ overloaded function (possibly with some parentheses and
4703/// perhaps a '&' around it). We have resolved the overloaded function
4704/// to the function declaration Fn, so patch up the expression E to
4705/// refer (possibly indirectly) to Fn.
4706void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4707 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4708 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4709 E->setType(PE->getSubExpr()->getType());
4710 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4711 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4712 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004713 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4714 if (Method->isStatic()) {
4715 // Do nothing: static member functions aren't any different
4716 // from non-member functions.
Mike Stump90fc78e2009-08-04 21:02:39 +00004717 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor3f411962009-02-11 01:18:59 +00004718 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4719 // We have taken the address of a pointer to member
4720 // function. Perform the computation here so that we get the
4721 // appropriate pointer to member type.
4722 DRE->setDecl(Fn);
4723 DRE->setType(Fn->getType());
4724 QualType ClassType
4725 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4726 E->setType(Context.getMemberPointerType(Fn->getType(),
4727 ClassType.getTypePtr()));
4728 return;
4729 }
4730 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004731 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004732 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004733 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor62f78762009-07-08 20:55:45 +00004734 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4735 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4736 "Expected overloaded function or function template");
Douglas Gregor45014fd2008-11-10 20:40:00 +00004737 DR->setDecl(Fn);
4738 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004739 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4740 MemExpr->setMemberDecl(Fn);
4741 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004742 } else {
4743 assert(false && "Invalid reference to overloaded function");
4744 }
4745}
4746
Douglas Gregord2baafd2008-10-21 16:13:35 +00004747} // end namespace clang