blob: e240c04e5dc7d82286bbc8f32f1897be8422ff26 [file] [log] [blame]
Douglas Gregord2baafd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor10f3c502008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000042 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000045 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000050 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000051 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000052 ICC_Conversion
53 };
54 return Category[(int)Kind];
55}
56
57/// GetConversionRank - Retrieve the implicit conversion rank
58/// corresponding to the given implicit conversion kind.
59ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
60 static const ImplicitConversionRank
61 Rank[(int)ICK_Num_Conversion_Kinds] = {
62 ICR_Exact_Match,
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Promotion,
68 ICR_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000069 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000072 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000077 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000078 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000079 ICR_Conversion
80 };
81 return Rank[(int)Kind];
82}
83
84/// GetImplicitConversionName - Return the name of this kind of
85/// implicit conversion.
86const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
87 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
88 "No conversion",
89 "Lvalue-to-rvalue",
90 "Array-to-pointer",
91 "Function-to-pointer",
92 "Qualification",
93 "Integral promotion",
94 "Floating point promotion",
Douglas Gregore819caf2009-02-12 00:15:05 +000095 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000096 "Integral conversion",
97 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +000098 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000099 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000100 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000101 "Pointer conversion",
102 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000103 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000104 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000105 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000106 };
107 return Name[Kind];
108}
109
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113 First = ICK_Identity;
114 Second = ICK_Identity;
115 Third = ICK_Identity;
116 Deprecated = false;
117 ReferenceBinding = false;
118 DirectBinding = false;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +0000119 RRefBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000120 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000121}
122
Douglas Gregord2baafd2008-10-21 16:13:35 +0000123/// getRank - Retrieve the rank of this standard conversion sequence
124/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
125/// implicit conversions.
126ImplicitConversionRank StandardConversionSequence::getRank() const {
127 ImplicitConversionRank Rank = ICR_Exact_Match;
128 if (GetConversionRank(First) > Rank)
129 Rank = GetConversionRank(First);
130 if (GetConversionRank(Second) > Rank)
131 Rank = GetConversionRank(Second);
132 if (GetConversionRank(Third) > Rank)
133 Rank = GetConversionRank(Third);
134 return Rank;
135}
136
137/// isPointerConversionToBool - Determines whether this conversion is
138/// a conversion of a pointer or pointer-to-member to bool. This is
139/// used as part of the ranking of standard conversion sequences
140/// (C++ 13.3.3.2p4).
141bool StandardConversionSequence::isPointerConversionToBool() const
142{
143 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
144 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
145
146 // Note that FromType has not necessarily been transformed by the
147 // array-to-pointer or function-to-pointer implicit conversions, so
148 // check for their presence as well as checking whether FromType is
149 // a pointer.
150 if (ToType->isBooleanType() &&
Douglas Gregor80402cf2008-12-23 00:53:59 +0000151 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000152 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
153 return true;
154
155 return false;
156}
157
Douglas Gregor14046502008-10-23 00:40:37 +0000158/// isPointerConversionToVoidPointer - Determines whether this
159/// conversion is a conversion of a pointer to a void pointer. This is
160/// used as part of the ranking of standard conversion sequences (C++
161/// 13.3.3.2p4).
162bool
163StandardConversionSequence::
164isPointerConversionToVoidPointer(ASTContext& Context) const
165{
166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
176 if (const PointerType* ToPtrType = ToType->getAsPointerType())
177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregord2baafd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
263// FunctionDecl that New cannot be overloaded with.
264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
272// so IsOverload will not be used.
273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl)
288{
289 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
290 // Is this new function an overload of every function in the
291 // overload set?
292 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
293 FuncEnd = Ovl->function_end();
294 for (; Func != FuncEnd; ++Func) {
295 if (!IsOverload(New, *Func, MatchedDecl)) {
296 MatchedDecl = Func;
297 return false;
298 }
299 }
300
301 // This function overloads every function in the overload set.
302 return true;
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();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000512 }
513 // Array-to-pointer conversion (C++ 4.2)
514 else if (FromType->isArrayType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000515 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000516
517 // An lvalue or rvalue of type "array of N T" or "array of unknown
518 // bound of T" can be converted to an rvalue of type "pointer to
519 // T" (C++ 4.2p1).
520 FromType = Context.getArrayDecayedType(FromType);
521
522 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
523 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000524 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000525
526 // For the purpose of ranking in overload resolution
527 // (13.3.3.1.1), this conversion is considered an
528 // array-to-pointer conversion followed by a qualification
529 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000530 SCS.Second = ICK_Identity;
531 SCS.Third = ICK_Qualification;
532 SCS.ToTypePtr = ToType.getAsOpaquePtr();
533 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000534 }
535 }
536 // Function-to-pointer conversion (C++ 4.3).
537 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000538 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000539
540 // An lvalue of function type T can be converted to an rvalue of
541 // type "pointer to T." The result is a pointer to the
542 // function. (C++ 4.3p1).
543 FromType = Context.getPointerType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000544 }
Douglas Gregor45014fd2008-11-10 20:40:00 +0000545 // Address of overloaded function (C++ [over.over]).
546 else if (FunctionDecl *Fn
547 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
548 SCS.First = ICK_Function_To_Pointer;
549
550 // We were able to resolve the address of the overloaded function,
551 // so we can convert to the type of that function.
552 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000553 if (ToType->isLValueReferenceType())
554 FromType = Context.getLValueReferenceType(FromType);
555 else if (ToType->isRValueReferenceType())
556 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000557 else if (ToType->isMemberPointerType()) {
558 // Resolve address only succeeds if both sides are member pointers,
559 // but it doesn't have to be the same class. See DR 247.
560 // Note that this means that the type of &Derived::fn can be
561 // Ret (Base::*)(Args) if the fn overload actually found is from the
562 // base class, even if it was brought into the derived class via a
563 // using declaration. The standard isn't clear on this issue at all.
564 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
565 FromType = Context.getMemberPointerType(FromType,
566 Context.getTypeDeclType(M->getParent()).getTypePtr());
567 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000568 FromType = Context.getPointerType(FromType);
569 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000570 // We don't require any conversions for the first step.
571 else {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000572 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000573 }
574
575 // The second conversion can be an integral promotion, floating
576 // point promotion, integral conversion, floating point conversion,
577 // floating-integral conversion, pointer conversion,
578 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000579 // For overloading in C, this can also be a "compatible-type"
580 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000581 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000582 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000583 // The unqualified versions of the types are the same: there's no
584 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000585 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000586 }
587 // Integral promotion (C++ 4.5).
588 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000589 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000590 FromType = ToType.getUnqualifiedType();
591 }
592 // Floating point promotion (C++ 4.6).
593 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000594 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000595 FromType = ToType.getUnqualifiedType();
596 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000597 // Complex promotion (Clang extension)
598 else if (IsComplexPromotion(FromType, ToType)) {
599 SCS.Second = ICK_Complex_Promotion;
600 FromType = ToType.getUnqualifiedType();
601 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000602 // Integral conversions (C++ 4.7).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000603 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000604 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000605 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000606 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000607 FromType = ToType.getUnqualifiedType();
608 }
609 // Floating point conversions (C++ 4.8).
610 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000611 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000612 FromType = ToType.getUnqualifiedType();
613 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000614 // Complex conversions (C99 6.3.1.6)
615 else if (FromType->isComplexType() && ToType->isComplexType()) {
616 SCS.Second = ICK_Complex_Conversion;
617 FromType = ToType.getUnqualifiedType();
618 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000619 // Floating-integral conversions (C++ 4.9).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000620 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000621 else if ((FromType->isFloatingType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000622 ToType->isIntegralType() && !ToType->isBooleanType() &&
623 !ToType->isEnumeralType()) ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000624 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
625 ToType->isFloatingType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000626 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000627 FromType = ToType.getUnqualifiedType();
628 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000629 // Complex-real conversions (C99 6.3.1.7)
630 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631 (ToType->isComplexType() && FromType->isArithmeticType())) {
632 SCS.Second = ICK_Complex_Real;
633 FromType = ToType.getUnqualifiedType();
634 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000635 // Pointer conversions (C++ 4.10).
Douglas Gregor6fd35572008-12-19 17:40:08 +0000636 else if (IsPointerConversion(From, FromType, ToType, FromType,
637 IncompatibleObjC)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000638 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000639 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000640 }
Sebastian Redlba387562009-01-25 19:43:20 +0000641 // Pointer to member conversions (4.11).
642 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
643 SCS.Second = ICK_Pointer_Member;
644 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000645 // Boolean conversions (C++ 4.12).
Douglas Gregord2baafd2008-10-21 16:13:35 +0000646 else if (ToType->isBooleanType() &&
647 (FromType->isArithmeticType() ||
648 FromType->isEnumeralType() ||
Douglas Gregor80402cf2008-12-23 00:53:59 +0000649 FromType->isPointerType() ||
Sebastian Redlba387562009-01-25 19:43:20 +0000650 FromType->isBlockPointerType() ||
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000651 FromType->isMemberPointerType() ||
652 FromType->isNullPtrType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000653 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000654 FromType = Context.BoolTy;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000655 }
656 // Compatible conversions (Clang extension for C function overloading)
657 else if (!getLangOptions().CPlusPlus &&
658 Context.typesAreCompatible(ToType, FromType)) {
659 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000660 } else {
661 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000662 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000663 }
664
Douglas Gregor81c29152008-10-29 00:13:59 +0000665 QualType CanonFrom;
666 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000667 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000668 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000669 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000670 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000671 CanonFrom = Context.getCanonicalType(FromType);
672 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000673 } else {
674 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000675 SCS.Third = ICK_Identity;
676
677 // C++ [over.best.ics]p6:
678 // [...] Any difference in top-level cv-qualification is
679 // subsumed by the initialization itself and does not constitute
680 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000681 CanonFrom = Context.getCanonicalType(FromType);
682 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000683 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000684 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
685 FromType = ToType;
686 CanonFrom = CanonTo;
687 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000688 }
689
690 // If we have not converted the argument type to the parameter type,
691 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000692 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000693 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000694
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000695 SCS.ToTypePtr = FromType.getAsOpaquePtr();
696 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000697}
698
699/// IsIntegralPromotion - Determines whether the conversion from the
700/// expression From (whose potentially-adjusted type is FromType) to
701/// ToType is an integral promotion (C++ 4.5). If so, returns true and
702/// sets PromotedType to the promoted type.
703bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
704{
705 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000706 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000707 if (!To) {
708 return false;
709 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000710
711 // An rvalue of type char, signed char, unsigned char, short int, or
712 // unsigned short int can be converted to an rvalue of type int if
713 // int can represent all the values of the source type; otherwise,
714 // the source rvalue can be converted to an rvalue of type unsigned
715 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000717 if (// We can promote any signed, promotable integer type to an int
718 (FromType->isSignedIntegerType() ||
719 // We can promote any unsigned integer type whose size is
720 // less than int to an int.
721 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000722 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000723 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000724 }
725
Douglas Gregord2baafd2008-10-21 16:13:35 +0000726 return To->getKind() == BuiltinType::UInt;
727 }
728
729 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
730 // can be converted to an rvalue of the first of the following types
731 // that can represent all the values of its underlying type: int,
732 // unsigned int, long, or unsigned long (C++ 4.5p2).
733 if ((FromType->isEnumeralType() || FromType->isWideCharType())
734 && ToType->isIntegerType()) {
735 // Determine whether the type we're converting from is signed or
736 // unsigned.
737 bool FromIsSigned;
738 uint64_t FromSize = Context.getTypeSize(FromType);
739 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
740 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
741 FromIsSigned = UnderlyingType->isSignedIntegerType();
742 } else {
743 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
744 FromIsSigned = true;
745 }
746
747 // The types we'll try to promote to, in the appropriate
748 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000749 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000750 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000751 Context.LongTy, Context.UnsignedLongTy ,
752 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000753 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000754 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000755 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
756 if (FromSize < ToSize ||
757 (FromSize == ToSize &&
758 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
759 // We found the type that we can promote to. If this is the
760 // type we wanted, we have a promotion. Otherwise, no
761 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000762 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000763 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
764 }
765 }
766 }
767
768 // An rvalue for an integral bit-field (9.6) can be converted to an
769 // rvalue of type int if int can represent all the values of the
770 // bit-field; otherwise, it can be converted to unsigned int if
771 // unsigned int can represent all the values of the bit-field. If
772 // the bit-field is larger yet, no integral promotion applies to
773 // it. If the bit-field has an enumerated type, it is treated as any
774 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stumpe127ae32009-05-16 07:39:55 +0000775 // FIXME: We should delay checking of bit-fields until we actually perform the
776 // conversion.
Douglas Gregor531434b2009-05-02 02:18:30 +0000777 using llvm::APSInt;
778 if (From)
779 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000780 APSInt BitWidth;
Douglas Gregor531434b2009-05-02 02:18:30 +0000781 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
782 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
783 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
784 ToSize = Context.getTypeSize(ToType);
Douglas Gregor82d44772008-12-20 23:49:58 +0000785
786 // Are we promoting to an int from a bitfield that fits in an int?
787 if (BitWidth < ToSize ||
788 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
789 return To->getKind() == BuiltinType::Int;
790 }
791
792 // Are we promoting to an unsigned int from an unsigned bitfield
793 // that fits into an unsigned int?
794 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
795 return To->getKind() == BuiltinType::UInt;
796 }
797
798 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000799 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000800 }
Douglas Gregor531434b2009-05-02 02:18:30 +0000801
Douglas Gregord2baafd2008-10-21 16:13:35 +0000802 // An rvalue of type bool can be converted to an rvalue of type int,
803 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000804 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000805 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000806 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000807
808 return false;
809}
810
811/// IsFloatingPointPromotion - Determines whether the conversion from
812/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
813/// returns true and sets PromotedType to the promoted type.
814bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
815{
816 /// An rvalue of type float can be converted to an rvalue of type
817 /// double. (C++ 4.6p1).
818 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000819 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000820 if (FromBuiltin->getKind() == BuiltinType::Float &&
821 ToBuiltin->getKind() == BuiltinType::Double)
822 return true;
823
Douglas Gregore819caf2009-02-12 00:15:05 +0000824 // C99 6.3.1.5p1:
825 // When a float is promoted to double or long double, or a
826 // double is promoted to long double [...].
827 if (!getLangOptions().CPlusPlus &&
828 (FromBuiltin->getKind() == BuiltinType::Float ||
829 FromBuiltin->getKind() == BuiltinType::Double) &&
830 (ToBuiltin->getKind() == BuiltinType::LongDouble))
831 return true;
832 }
833
Douglas Gregord2baafd2008-10-21 16:13:35 +0000834 return false;
835}
836
Douglas Gregore819caf2009-02-12 00:15:05 +0000837/// \brief Determine if a conversion is a complex promotion.
838///
839/// A complex promotion is defined as a complex -> complex conversion
840/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000841/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000842bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
843 const ComplexType *FromComplex = FromType->getAsComplexType();
844 if (!FromComplex)
845 return false;
846
847 const ComplexType *ToComplex = ToType->getAsComplexType();
848 if (!ToComplex)
849 return false;
850
851 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000852 ToComplex->getElementType()) ||
853 IsIntegralPromotion(0, FromComplex->getElementType(),
854 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000855}
856
Douglas Gregor24a90a52008-11-26 23:31:11 +0000857/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
858/// the pointer type FromPtr to a pointer to type ToPointee, with the
859/// same type qualifiers as FromPtr has on its pointee type. ToType,
860/// if non-empty, will be a pointer to ToType that may or may not have
861/// the right set of qualifiers on its pointee.
862static QualType
863BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
864 QualType ToPointee, QualType ToType,
865 ASTContext &Context) {
866 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
867 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
868 unsigned Quals = CanonFromPointee.getCVRQualifiers();
869
870 // Exact qualifier match -> return the pointer type we're converting to.
871 if (CanonToPointee.getCVRQualifiers() == Quals) {
872 // ToType is exactly what we need. Return it.
873 if (ToType.getTypePtr())
874 return ToType;
875
876 // Build a pointer to ToPointee. It has the right qualifiers
877 // already.
878 return Context.getPointerType(ToPointee);
879 }
880
881 // Just build a canonical type that has the right qualifiers.
882 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
883}
884
Douglas Gregord2baafd2008-10-21 16:13:35 +0000885/// IsPointerConversion - Determines whether the conversion of the
886/// expression From, which has the (possibly adjusted) type FromType,
887/// can be converted to the type ToType via a pointer conversion (C++
888/// 4.10). If so, returns true and places the converted type (that
889/// might differ from ToType in its cv-qualifiers at some level) into
890/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000891///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000892/// This routine also supports conversions to and from block pointers
893/// and conversions with Objective-C's 'id', 'id<protocols...>', and
894/// pointers to interfaces. FIXME: Once we've determined the
895/// appropriate overloading rules for Objective-C, we may want to
896/// split the Objective-C checks into a different routine; however,
897/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000898/// conversions, so for now they live here. IncompatibleObjC will be
899/// set if the conversion is an allowed Objective-C conversion that
900/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000901bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000902 QualType& ConvertedType,
903 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000904{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000905 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000906 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
907 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000908
Douglas Gregorf1d75712008-12-22 20:51:52 +0000909 // Conversion from a null pointer constant to any Objective-C pointer type.
910 if (Context.isObjCObjectPointerType(ToType) &&
911 From->isNullPointerConstant(Context)) {
912 ConvertedType = ToType;
913 return true;
914 }
915
Douglas Gregor9036ef72008-11-27 00:15:41 +0000916 // Blocks: Block pointers can be converted to void*.
917 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
918 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
919 ConvertedType = ToType;
920 return true;
921 }
922 // Blocks: A null pointer constant can be converted to a block
923 // pointer type.
924 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
925 ConvertedType = ToType;
926 return true;
927 }
928
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000929 // If the left-hand-side is nullptr_t, the right side can be a null
930 // pointer constant.
931 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
932 ConvertedType = ToType;
933 return true;
934 }
935
Douglas Gregord2baafd2008-10-21 16:13:35 +0000936 const PointerType* ToTypePtr = ToType->getAsPointerType();
937 if (!ToTypePtr)
938 return false;
939
940 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
941 if (From->isNullPointerConstant(Context)) {
942 ConvertedType = ToType;
943 return true;
944 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000945
Douglas Gregor24a90a52008-11-26 23:31:11 +0000946 // Beyond this point, both types need to be pointers.
947 const PointerType *FromTypePtr = FromType->getAsPointerType();
948 if (!FromTypePtr)
949 return false;
950
951 QualType FromPointeeType = FromTypePtr->getPointeeType();
952 QualType ToPointeeType = ToTypePtr->getPointeeType();
953
Douglas Gregord2baafd2008-10-21 16:13:35 +0000954 // An rvalue of type "pointer to cv T," where T is an object type,
955 // can be converted to an rvalue of type "pointer to cv void" (C++
956 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000957 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000958 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
959 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000960 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000961 return true;
962 }
963
Douglas Gregorfcb19192009-02-11 23:02:49 +0000964 // When we're overloading in C, we allow a special kind of pointer
965 // conversion for compatible-but-not-identical pointee types.
966 if (!getLangOptions().CPlusPlus &&
967 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
969 ToPointeeType,
970 ToType, Context);
971 return true;
972 }
973
Douglas Gregor14046502008-10-23 00:40:37 +0000974 // C++ [conv.ptr]p3:
975 //
976 // An rvalue of type "pointer to cv D," where D is a class type,
977 // can be converted to an rvalue of type "pointer to cv B," where
978 // B is a base class (clause 10) of D. If B is an inaccessible
979 // (clause 11) or ambiguous (10.2) base class of D, a program that
980 // necessitates this conversion is ill-formed. The result of the
981 // conversion is a pointer to the base class sub-object of the
982 // derived class object. The null pointer value is converted to
983 // the null pointer value of the destination type.
984 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000985 // Note that we do not check for ambiguity or inaccessibility
986 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000987 if (getLangOptions().CPlusPlus &&
988 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000989 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000990 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
991 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000992 ToType, Context);
993 return true;
994 }
Douglas Gregor14046502008-10-23 00:40:37 +0000995
Douglas Gregor932778b2008-12-19 19:13:09 +0000996 return false;
997}
998
999/// isObjCPointerConversion - Determines whether this is an
1000/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1001/// with the same arguments and return values.
1002bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1003 QualType& ConvertedType,
1004 bool &IncompatibleObjC) {
1005 if (!getLangOptions().ObjC1)
1006 return false;
1007
1008 // Conversions with Objective-C's id<...>.
1009 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
1010 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
1011 ConvertedType = ToType;
1012 return true;
1013 }
1014
Douglas Gregor80402cf2008-12-23 00:53:59 +00001015 // Beyond this point, both types need to be pointers or block pointers.
1016 QualType ToPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +00001017 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +00001018 if (ToTypePtr)
1019 ToPointeeType = ToTypePtr->getPointeeType();
1020 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
1021 ToPointeeType = ToBlockPtr->getPointeeType();
1022 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001023 return false;
1024
Douglas Gregor80402cf2008-12-23 00:53:59 +00001025 QualType FromPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +00001026 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +00001027 if (FromTypePtr)
1028 FromPointeeType = FromTypePtr->getPointeeType();
1029 else if (const BlockPointerType *FromBlockPtr
1030 = FromType->getAsBlockPointerType())
1031 FromPointeeType = FromBlockPtr->getPointeeType();
1032 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001033 return false;
1034
Douglas Gregor24a90a52008-11-26 23:31:11 +00001035 // Objective C++: We're able to convert from a pointer to an
1036 // interface to a pointer to a different interface.
1037 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
1038 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1039 if (FromIface && ToIface &&
1040 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor80402cf2008-12-23 00:53:59 +00001041 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001042 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001043 ToType, Context);
1044 return true;
1045 }
1046
Douglas Gregor6fd35572008-12-19 17:40:08 +00001047 if (FromIface && ToIface &&
1048 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1049 // Okay: this is some kind of implicit downcast of Objective-C
1050 // interfaces, which is permitted. However, we're going to
1051 // complain about it.
1052 IncompatibleObjC = true;
Douglas Gregor80402cf2008-12-23 00:53:59 +00001053 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor6fd35572008-12-19 17:40:08 +00001054 ToPointeeType,
1055 ToType, Context);
1056 return true;
1057 }
1058
Douglas Gregor24a90a52008-11-26 23:31:11 +00001059 // Objective C++: We're able to convert between "id" and a pointer
1060 // to any interface (in both directions).
Steve Naroff17c03822009-02-12 17:52:19 +00001061 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1062 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1064 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001065 ToType, Context);
1066 return true;
1067 }
Douglas Gregor14046502008-10-23 00:40:37 +00001068
Douglas Gregord0c653a2008-12-18 23:43:31 +00001069 // Objective C++: Allow conversions between the Objective-C "id" and
1070 // "Class", in either direction.
Steve Naroff17c03822009-02-12 17:52:19 +00001071 if ((Context.isObjCIdStructType(FromPointeeType) &&
1072 Context.isObjCClassStructType(ToPointeeType)) ||
1073 (Context.isObjCClassStructType(FromPointeeType) &&
1074 Context.isObjCIdStructType(ToPointeeType))) {
Douglas Gregord0c653a2008-12-18 23:43:31 +00001075 ConvertedType = ToType;
1076 return true;
1077 }
1078
Douglas Gregor932778b2008-12-19 19:13:09 +00001079 // If we have pointers to pointers, recursively check whether this
1080 // is an Objective-C conversion.
1081 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1082 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1083 IncompatibleObjC)) {
1084 // We always complain about this conversion.
1085 IncompatibleObjC = true;
1086 ConvertedType = ToType;
1087 return true;
1088 }
1089
Douglas Gregor80402cf2008-12-23 00:53:59 +00001090 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001091 // differences in the argument and result types are in Objective-C
1092 // pointer conversions. If so, we permit the conversion (but
1093 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001094 const FunctionProtoType *FromFunctionType
1095 = FromPointeeType->getAsFunctionProtoType();
1096 const FunctionProtoType *ToFunctionType
1097 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001098 if (FromFunctionType && ToFunctionType) {
1099 // If the function types are exactly the same, this isn't an
1100 // Objective-C pointer conversion.
1101 if (Context.getCanonicalType(FromPointeeType)
1102 == Context.getCanonicalType(ToPointeeType))
1103 return false;
1104
1105 // Perform the quick checks that will tell us whether these
1106 // function types are obviously different.
1107 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1108 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1109 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1110 return false;
1111
1112 bool HasObjCConversion = false;
1113 if (Context.getCanonicalType(FromFunctionType->getResultType())
1114 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1115 // Okay, the types match exactly. Nothing to do.
1116 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1117 ToFunctionType->getResultType(),
1118 ConvertedType, IncompatibleObjC)) {
1119 // Okay, we have an Objective-C pointer conversion.
1120 HasObjCConversion = true;
1121 } else {
1122 // Function types are too different. Abort.
1123 return false;
1124 }
1125
1126 // Check argument types.
1127 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1128 ArgIdx != NumArgs; ++ArgIdx) {
1129 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1130 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1131 if (Context.getCanonicalType(FromArgType)
1132 == Context.getCanonicalType(ToArgType)) {
1133 // Okay, the types match exactly. Nothing to do.
1134 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1135 ConvertedType, IncompatibleObjC)) {
1136 // Okay, we have an Objective-C pointer conversion.
1137 HasObjCConversion = true;
1138 } else {
1139 // Argument types are too different. Abort.
1140 return false;
1141 }
1142 }
1143
1144 if (HasObjCConversion) {
1145 // We had an Objective-C conversion. Allow this pointer
1146 // conversion, but complain about it.
1147 ConvertedType = ToType;
1148 IncompatibleObjC = true;
1149 return true;
1150 }
1151 }
1152
Sebastian Redlba387562009-01-25 19:43:20 +00001153 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001154}
1155
Douglas Gregorbb461502008-10-24 04:54:22 +00001156/// CheckPointerConversion - Check the pointer conversion from the
1157/// expression From to the type ToType. This routine checks for
1158/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1159/// conversions for which IsPointerConversion has already returned
1160/// true. It returns true and produces a diagnostic if there was an
1161/// error, or returns false otherwise.
1162bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1163 QualType FromType = From->getType();
1164
1165 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1166 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001167 QualType FromPointeeType = FromPtrType->getPointeeType(),
1168 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001169
1170 // Objective-C++ conversions are always okay.
Mike Stumpe127ae32009-05-16 07:39:55 +00001171 // FIXME: We should have a different class of conversions for the
1172 // Objective-C++ implicit conversions.
Steve Naroff17c03822009-02-12 17:52:19 +00001173 if (Context.isObjCIdStructType(FromPointeeType) ||
1174 Context.isObjCIdStructType(ToPointeeType) ||
1175 Context.isObjCClassStructType(FromPointeeType) ||
1176 Context.isObjCClassStructType(ToPointeeType))
Douglas Gregord0c653a2008-12-18 23:43:31 +00001177 return false;
1178
Douglas Gregorbb461502008-10-24 04:54:22 +00001179 if (FromPointeeType->isRecordType() &&
1180 ToPointeeType->isRecordType()) {
1181 // We must have a derived-to-base conversion. Check an
1182 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001183 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1184 From->getExprLoc(),
1185 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001186 }
1187 }
1188
1189 return false;
1190}
1191
Sebastian Redlba387562009-01-25 19:43:20 +00001192/// IsMemberPointerConversion - Determines whether the conversion of the
1193/// expression From, which has the (possibly adjusted) type FromType, can be
1194/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1195/// If so, returns true and places the converted type (that might differ from
1196/// ToType in its cv-qualifiers at some level) into ConvertedType.
1197bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1198 QualType ToType, QualType &ConvertedType)
1199{
1200 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1201 if (!ToTypePtr)
1202 return false;
1203
1204 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1205 if (From->isNullPointerConstant(Context)) {
1206 ConvertedType = ToType;
1207 return true;
1208 }
1209
1210 // Otherwise, both types have to be member pointers.
1211 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1212 if (!FromTypePtr)
1213 return false;
1214
1215 // A pointer to member of B can be converted to a pointer to member of D,
1216 // where D is derived from B (C++ 4.11p2).
1217 QualType FromClass(FromTypePtr->getClass(), 0);
1218 QualType ToClass(ToTypePtr->getClass(), 0);
1219 // FIXME: What happens when these are dependent? Is this function even called?
1220
1221 if (IsDerivedFrom(ToClass, FromClass)) {
1222 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1223 ToClass.getTypePtr());
1224 return true;
1225 }
1226
1227 return false;
1228}
1229
1230/// CheckMemberPointerConversion - Check the member pointer conversion from the
1231/// expression From to the type ToType. This routine checks for ambiguous or
1232/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1233/// for which IsMemberPointerConversion has already returned true. It returns
1234/// true and produces a diagnostic if there was an error, or returns false
1235/// otherwise.
1236bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1237 QualType FromType = From->getType();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001238 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1239 if (!FromPtrType)
1240 return false;
Sebastian Redlba387562009-01-25 19:43:20 +00001241
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001242 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1243 assert(ToPtrType && "No member pointer cast has a target type "
1244 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001245
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001246 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1247 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001248
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001249 // FIXME: What about dependent types?
1250 assert(FromClass->isRecordType() && "Pointer into non-class.");
1251 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001252
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001253 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1254 /*DetectVirtual=*/true);
1255 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1256 assert(DerivationOkay &&
1257 "Should not have been called if derivation isn't OK.");
1258 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001259
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001260 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1261 getUnqualifiedType())) {
1262 // Derivation is ambiguous. Redo the check to find the exact paths.
1263 Paths.clear();
1264 Paths.setRecordingPaths(true);
1265 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1266 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1267 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001268
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001269 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1270 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1271 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1272 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001273 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001274
Douglas Gregor2e047592009-02-28 01:32:25 +00001275 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001276 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1277 << FromClass << ToClass << QualType(VBase, 0)
1278 << From->getSourceRange();
1279 return true;
1280 }
1281
Sebastian Redlba387562009-01-25 19:43:20 +00001282 return false;
1283}
1284
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001285/// IsQualificationConversion - Determines whether the conversion from
1286/// an rvalue of type FromType to ToType is a qualification conversion
1287/// (C++ 4.4).
1288bool
1289Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1290{
1291 FromType = Context.getCanonicalType(FromType);
1292 ToType = Context.getCanonicalType(ToType);
1293
1294 // If FromType and ToType are the same type, this is not a
1295 // qualification conversion.
1296 if (FromType == ToType)
1297 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001298
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001299 // (C++ 4.4p4):
1300 // A conversion can add cv-qualifiers at levels other than the first
1301 // in multi-level pointers, subject to the following rules: [...]
1302 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001303 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001304 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001305 // Within each iteration of the loop, we check the qualifiers to
1306 // determine if this still looks like a qualification
1307 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001308 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001309 // until there are no more pointers or pointers-to-members left to
1310 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001311 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001312
1313 // -- for every j > 0, if const is in cv 1,j then const is in cv
1314 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001315 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001316 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001317
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001318 // -- if the cv 1,j and cv 2,j are different, then const is in
1319 // every cv for 0 < k < j.
1320 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001321 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001322 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001323
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001324 // Keep track of whether all prior cv-qualifiers in the "to" type
1325 // include const.
1326 PreviousToQualsIncludeConst
1327 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001328 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001329
1330 // We are left with FromType and ToType being the pointee types
1331 // after unwrapping the original FromType and ToType the same number
1332 // of types. If we unwrapped any pointers, and if FromType and
1333 // ToType have the same unqualified type (since we checked
1334 // qualifiers above), then this is a qualification conversion.
1335 return UnwrappedAnyPointer &&
1336 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1337}
1338
Douglas Gregorb206cc42009-01-30 23:27:23 +00001339/// Determines whether there is a user-defined conversion sequence
1340/// (C++ [over.ics.user]) that converts expression From to the type
1341/// ToType. If such a conversion exists, User will contain the
1342/// user-defined conversion sequence that performs such a conversion
1343/// and this routine will return true. Otherwise, this routine returns
1344/// false and User is unspecified.
1345///
1346/// \param AllowConversionFunctions true if the conversion should
1347/// consider conversion functions at all. If false, only constructors
1348/// will be considered.
1349///
1350/// \param AllowExplicit true if the conversion should consider C++0x
1351/// "explicit" conversion functions as well as non-explicit conversion
1352/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001353///
1354/// \param ForceRValue true if the expression should be treated as an rvalue
1355/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001356bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001357 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001358 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001359 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001360{
1361 OverloadCandidateSet CandidateSet;
Douglas Gregor2e047592009-02-28 01:32:25 +00001362 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1363 if (CXXRecordDecl *ToRecordDecl
1364 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1365 // C++ [over.match.ctor]p1:
1366 // When objects of class type are direct-initialized (8.5), or
1367 // copy-initialized from an expression of the same or a
1368 // derived class type (8.5), overload resolution selects the
1369 // constructor. [...] For copy-initialization, the candidate
1370 // functions are all the converting constructors (12.3.1) of
1371 // that class. The argument list is the expression-list within
1372 // the parentheses of the initializer.
1373 DeclarationName ConstructorName
1374 = Context.DeclarationNames.getCXXConstructorName(
1375 Context.getCanonicalType(ToType).getUnqualifiedType());
1376 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001377 for (llvm::tie(Con, ConEnd)
1378 = ToRecordDecl->lookup(Context, ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001379 Con != ConEnd; ++Con) {
1380 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1381 if (Constructor->isConvertingConstructor())
1382 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00001383 /*SuppressUserConversions=*/true, ForceRValue);
Douglas Gregor2e047592009-02-28 01:32:25 +00001384 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001385 }
1386 }
1387
Douglas Gregorb206cc42009-01-30 23:27:23 +00001388 if (!AllowConversionFunctions) {
1389 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-02-28 01:32:25 +00001390 } else if (const RecordType *FromRecordType
1391 = From->getType()->getAsRecordType()) {
1392 if (CXXRecordDecl *FromRecordDecl
1393 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1394 // Add all of the conversion functions as candidates.
1395 // FIXME: Look for conversions in base classes!
1396 OverloadedFunctionDecl *Conversions
1397 = FromRecordDecl->getConversionFunctions();
1398 for (OverloadedFunctionDecl::function_iterator Func
1399 = Conversions->function_begin();
1400 Func != Conversions->function_end(); ++Func) {
1401 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1402 if (AllowExplicit || !Conv->isExplicit())
1403 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1404 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001405 }
1406 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001407
1408 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001409 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001410 case OR_Success:
1411 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001412 if (CXXConstructorDecl *Constructor
1413 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1414 // C++ [over.ics.user]p1:
1415 // If the user-defined conversion is specified by a
1416 // constructor (12.3.1), the initial standard conversion
1417 // sequence converts the source type to the type required by
1418 // the argument of the constructor.
1419 //
1420 // FIXME: What about ellipsis conversions?
1421 QualType ThisType = Constructor->getThisType(Context);
1422 User.Before = Best->Conversions[0].Standard;
1423 User.ConversionFunction = Constructor;
1424 User.After.setAsIdentityConversion();
1425 User.After.FromTypePtr
1426 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1427 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1428 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001429 } else if (CXXConversionDecl *Conversion
1430 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1431 // C++ [over.ics.user]p1:
1432 //
1433 // [...] If the user-defined conversion is specified by a
1434 // conversion function (12.3.2), the initial standard
1435 // conversion sequence converts the source type to the
1436 // implicit object parameter of the conversion function.
1437 User.Before = Best->Conversions[0].Standard;
1438 User.ConversionFunction = Conversion;
1439
1440 // C++ [over.ics.user]p2:
1441 // The second standard conversion sequence converts the
1442 // result of the user-defined conversion to the target type
1443 // for the sequence. Since an implicit conversion sequence
1444 // is an initialization, the special rules for
1445 // initialization by user-defined conversion apply when
1446 // selecting the best user-defined conversion for a
1447 // user-defined conversion sequence (see 13.3.3 and
1448 // 13.3.3.1).
1449 User.After = Best->FinalConversion;
1450 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001451 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001452 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001453 return false;
1454 }
1455
1456 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001457 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001458 // No conversion here! We're done.
1459 return false;
1460
1461 case OR_Ambiguous:
1462 // FIXME: See C++ [over.best.ics]p10 for the handling of
1463 // ambiguous conversion sequences.
1464 return false;
1465 }
1466
1467 return false;
1468}
1469
Douglas Gregord2baafd2008-10-21 16:13:35 +00001470/// CompareImplicitConversionSequences - Compare two implicit
1471/// conversion sequences to determine whether one is better than the
1472/// other or if they are indistinguishable (C++ 13.3.3.2).
1473ImplicitConversionSequence::CompareKind
1474Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1475 const ImplicitConversionSequence& ICS2)
1476{
1477 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1478 // conversion sequences (as defined in 13.3.3.1)
1479 // -- a standard conversion sequence (13.3.3.1.1) is a better
1480 // conversion sequence than a user-defined conversion sequence or
1481 // an ellipsis conversion sequence, and
1482 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1483 // conversion sequence than an ellipsis conversion sequence
1484 // (13.3.3.1.3).
1485 //
1486 if (ICS1.ConversionKind < ICS2.ConversionKind)
1487 return ImplicitConversionSequence::Better;
1488 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1489 return ImplicitConversionSequence::Worse;
1490
1491 // Two implicit conversion sequences of the same form are
1492 // indistinguishable conversion sequences unless one of the
1493 // following rules apply: (C++ 13.3.3.2p3):
1494 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1495 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1496 else if (ICS1.ConversionKind ==
1497 ImplicitConversionSequence::UserDefinedConversion) {
1498 // User-defined conversion sequence U1 is a better conversion
1499 // sequence than another user-defined conversion sequence U2 if
1500 // they contain the same user-defined conversion function or
1501 // constructor and if the second standard conversion sequence of
1502 // U1 is better than the second standard conversion sequence of
1503 // U2 (C++ 13.3.3.2p3).
1504 if (ICS1.UserDefined.ConversionFunction ==
1505 ICS2.UserDefined.ConversionFunction)
1506 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1507 ICS2.UserDefined.After);
1508 }
1509
1510 return ImplicitConversionSequence::Indistinguishable;
1511}
1512
1513/// CompareStandardConversionSequences - Compare two standard
1514/// conversion sequences to determine whether one is better than the
1515/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1516ImplicitConversionSequence::CompareKind
1517Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1518 const StandardConversionSequence& SCS2)
1519{
1520 // Standard conversion sequence S1 is a better conversion sequence
1521 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1522
1523 // -- S1 is a proper subsequence of S2 (comparing the conversion
1524 // sequences in the canonical form defined by 13.3.3.1.1,
1525 // excluding any Lvalue Transformation; the identity conversion
1526 // sequence is considered to be a subsequence of any
1527 // non-identity conversion sequence) or, if not that,
1528 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1529 // Neither is a proper subsequence of the other. Do nothing.
1530 ;
1531 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1532 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1533 (SCS1.Second == ICK_Identity &&
1534 SCS1.Third == ICK_Identity))
1535 // SCS1 is a proper subsequence of SCS2.
1536 return ImplicitConversionSequence::Better;
1537 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1538 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1539 (SCS2.Second == ICK_Identity &&
1540 SCS2.Third == ICK_Identity))
1541 // SCS2 is a proper subsequence of SCS1.
1542 return ImplicitConversionSequence::Worse;
1543
1544 // -- the rank of S1 is better than the rank of S2 (by the rules
1545 // defined below), or, if not that,
1546 ImplicitConversionRank Rank1 = SCS1.getRank();
1547 ImplicitConversionRank Rank2 = SCS2.getRank();
1548 if (Rank1 < Rank2)
1549 return ImplicitConversionSequence::Better;
1550 else if (Rank2 < Rank1)
1551 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001552
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001553 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1554 // are indistinguishable unless one of the following rules
1555 // applies:
1556
1557 // A conversion that is not a conversion of a pointer, or
1558 // pointer to member, to bool is better than another conversion
1559 // that is such a conversion.
1560 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1561 return SCS2.isPointerConversionToBool()
1562 ? ImplicitConversionSequence::Better
1563 : ImplicitConversionSequence::Worse;
1564
Douglas Gregor14046502008-10-23 00:40:37 +00001565 // C++ [over.ics.rank]p4b2:
1566 //
1567 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001568 // conversion of B* to A* is better than conversion of B* to
1569 // void*, and conversion of A* to void* is better than conversion
1570 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001571 bool SCS1ConvertsToVoid
1572 = SCS1.isPointerConversionToVoidPointer(Context);
1573 bool SCS2ConvertsToVoid
1574 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001575 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1576 // Exactly one of the conversion sequences is a conversion to
1577 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001578 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1579 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001580 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1581 // Neither conversion sequence converts to a void pointer; compare
1582 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001583 if (ImplicitConversionSequence::CompareKind DerivedCK
1584 = CompareDerivedToBaseConversions(SCS1, SCS2))
1585 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001586 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1587 // Both conversion sequences are conversions to void
1588 // pointers. Compare the source types to determine if there's an
1589 // inheritance relationship in their sources.
1590 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1591 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1592
1593 // Adjust the types we're converting from via the array-to-pointer
1594 // conversion, if we need to.
1595 if (SCS1.First == ICK_Array_To_Pointer)
1596 FromType1 = Context.getArrayDecayedType(FromType1);
1597 if (SCS2.First == ICK_Array_To_Pointer)
1598 FromType2 = Context.getArrayDecayedType(FromType2);
1599
1600 QualType FromPointee1
1601 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1602 QualType FromPointee2
1603 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1604
1605 if (IsDerivedFrom(FromPointee2, FromPointee1))
1606 return ImplicitConversionSequence::Better;
1607 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1608 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001609
1610 // Objective-C++: If one interface is more specific than the
1611 // other, it is the better one.
1612 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1613 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1614 if (FromIface1 && FromIface1) {
1615 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1616 return ImplicitConversionSequence::Better;
1617 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1618 return ImplicitConversionSequence::Worse;
1619 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001620 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001621
1622 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1623 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001624 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001625 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001626 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001627
Douglas Gregor0e343382008-10-29 14:50:44 +00001628 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001629 // C++0x [over.ics.rank]p3b4:
1630 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1631 // implicit object parameter of a non-static member function declared
1632 // without a ref-qualifier, and S1 binds an rvalue reference to an
1633 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001634 // FIXME: We don't know if we're dealing with the implicit object parameter,
1635 // or if the member function in this case has a ref qualifier.
1636 // (Of course, we don't have ref qualifiers yet.)
1637 if (SCS1.RRefBinding != SCS2.RRefBinding)
1638 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1639 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001640
1641 // C++ [over.ics.rank]p3b4:
1642 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1643 // which the references refer are the same type except for
1644 // top-level cv-qualifiers, and the type to which the reference
1645 // initialized by S2 refers is more cv-qualified than the type
1646 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001647 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1648 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001649 T1 = Context.getCanonicalType(T1);
1650 T2 = Context.getCanonicalType(T2);
1651 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1652 if (T2.isMoreQualifiedThan(T1))
1653 return ImplicitConversionSequence::Better;
1654 else if (T1.isMoreQualifiedThan(T2))
1655 return ImplicitConversionSequence::Worse;
1656 }
1657 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001658
1659 return ImplicitConversionSequence::Indistinguishable;
1660}
1661
1662/// CompareQualificationConversions - Compares two standard conversion
1663/// sequences to determine whether they can be ranked based on their
1664/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1665ImplicitConversionSequence::CompareKind
1666Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1667 const StandardConversionSequence& SCS2)
1668{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001669 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001670 // -- S1 and S2 differ only in their qualification conversion and
1671 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1672 // cv-qualification signature of type T1 is a proper subset of
1673 // the cv-qualification signature of type T2, and S1 is not the
1674 // deprecated string literal array-to-pointer conversion (4.2).
1675 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1676 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1677 return ImplicitConversionSequence::Indistinguishable;
1678
1679 // FIXME: the example in the standard doesn't use a qualification
1680 // conversion (!)
1681 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1682 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1683 T1 = Context.getCanonicalType(T1);
1684 T2 = Context.getCanonicalType(T2);
1685
1686 // If the types are the same, we won't learn anything by unwrapped
1687 // them.
1688 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1689 return ImplicitConversionSequence::Indistinguishable;
1690
1691 ImplicitConversionSequence::CompareKind Result
1692 = ImplicitConversionSequence::Indistinguishable;
1693 while (UnwrapSimilarPointerTypes(T1, T2)) {
1694 // Within each iteration of the loop, we check the qualifiers to
1695 // determine if this still looks like a qualification
1696 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001697 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001698 // until there are no more pointers or pointers-to-members left
1699 // to unwrap. This essentially mimics what
1700 // IsQualificationConversion does, but here we're checking for a
1701 // strict subset of qualifiers.
1702 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1703 // The qualifiers are the same, so this doesn't tell us anything
1704 // about how the sequences rank.
1705 ;
1706 else if (T2.isMoreQualifiedThan(T1)) {
1707 // T1 has fewer qualifiers, so it could be the better sequence.
1708 if (Result == ImplicitConversionSequence::Worse)
1709 // Neither has qualifiers that are a subset of the other's
1710 // qualifiers.
1711 return ImplicitConversionSequence::Indistinguishable;
1712
1713 Result = ImplicitConversionSequence::Better;
1714 } else if (T1.isMoreQualifiedThan(T2)) {
1715 // T2 has fewer qualifiers, so it could be the better sequence.
1716 if (Result == ImplicitConversionSequence::Better)
1717 // Neither has qualifiers that are a subset of the other's
1718 // qualifiers.
1719 return ImplicitConversionSequence::Indistinguishable;
1720
1721 Result = ImplicitConversionSequence::Worse;
1722 } else {
1723 // Qualifiers are disjoint.
1724 return ImplicitConversionSequence::Indistinguishable;
1725 }
1726
1727 // If the types after this point are equivalent, we're done.
1728 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1729 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001730 }
1731
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001732 // Check that the winning standard conversion sequence isn't using
1733 // the deprecated string literal array to pointer conversion.
1734 switch (Result) {
1735 case ImplicitConversionSequence::Better:
1736 if (SCS1.Deprecated)
1737 Result = ImplicitConversionSequence::Indistinguishable;
1738 break;
1739
1740 case ImplicitConversionSequence::Indistinguishable:
1741 break;
1742
1743 case ImplicitConversionSequence::Worse:
1744 if (SCS2.Deprecated)
1745 Result = ImplicitConversionSequence::Indistinguishable;
1746 break;
1747 }
1748
1749 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001750}
1751
Douglas Gregor14046502008-10-23 00:40:37 +00001752/// CompareDerivedToBaseConversions - Compares two standard conversion
1753/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001754/// various kinds of derived-to-base conversions (C++
1755/// [over.ics.rank]p4b3). As part of these checks, we also look at
1756/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001757ImplicitConversionSequence::CompareKind
1758Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1759 const StandardConversionSequence& SCS2) {
1760 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1761 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1762 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1763 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1764
1765 // Adjust the types we're converting from via the array-to-pointer
1766 // conversion, if we need to.
1767 if (SCS1.First == ICK_Array_To_Pointer)
1768 FromType1 = Context.getArrayDecayedType(FromType1);
1769 if (SCS2.First == ICK_Array_To_Pointer)
1770 FromType2 = Context.getArrayDecayedType(FromType2);
1771
1772 // Canonicalize all of the types.
1773 FromType1 = Context.getCanonicalType(FromType1);
1774 ToType1 = Context.getCanonicalType(ToType1);
1775 FromType2 = Context.getCanonicalType(FromType2);
1776 ToType2 = Context.getCanonicalType(ToType2);
1777
Douglas Gregor0e343382008-10-29 14:50:44 +00001778 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001779 //
1780 // If class B is derived directly or indirectly from class A and
1781 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001782 //
1783 // For Objective-C, we let A, B, and C also be Objective-C
1784 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001785
1786 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001787 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001788 SCS2.Second == ICK_Pointer_Conversion &&
1789 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1790 FromType1->isPointerType() && FromType2->isPointerType() &&
1791 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001792 QualType FromPointee1
1793 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1794 QualType ToPointee1
1795 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1796 QualType FromPointee2
1797 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1798 QualType ToPointee2
1799 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001800
1801 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1802 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1803 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1804 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1805
Douglas Gregor0e343382008-10-29 14:50:44 +00001806 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001807 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1808 if (IsDerivedFrom(ToPointee1, ToPointee2))
1809 return ImplicitConversionSequence::Better;
1810 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1811 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001812
1813 if (ToIface1 && ToIface2) {
1814 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1815 return ImplicitConversionSequence::Better;
1816 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1817 return ImplicitConversionSequence::Worse;
1818 }
Douglas Gregor14046502008-10-23 00:40:37 +00001819 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001820
1821 // -- conversion of B* to A* is better than conversion of C* to A*,
1822 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1823 if (IsDerivedFrom(FromPointee2, FromPointee1))
1824 return ImplicitConversionSequence::Better;
1825 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1826 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001827
1828 if (FromIface1 && FromIface2) {
1829 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1830 return ImplicitConversionSequence::Better;
1831 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1832 return ImplicitConversionSequence::Worse;
1833 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001834 }
Douglas Gregor14046502008-10-23 00:40:37 +00001835 }
1836
Douglas Gregor0e343382008-10-29 14:50:44 +00001837 // Compare based on reference bindings.
1838 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1839 SCS1.Second == ICK_Derived_To_Base) {
1840 // -- binding of an expression of type C to a reference of type
1841 // B& is better than binding an expression of type C to a
1842 // reference of type A&,
1843 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1844 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1845 if (IsDerivedFrom(ToType1, ToType2))
1846 return ImplicitConversionSequence::Better;
1847 else if (IsDerivedFrom(ToType2, ToType1))
1848 return ImplicitConversionSequence::Worse;
1849 }
1850
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001851 // -- binding of an expression of type B to a reference of type
1852 // A& is better than binding an expression of type C to a
1853 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001854 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1855 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1856 if (IsDerivedFrom(FromType2, FromType1))
1857 return ImplicitConversionSequence::Better;
1858 else if (IsDerivedFrom(FromType1, FromType2))
1859 return ImplicitConversionSequence::Worse;
1860 }
1861 }
1862
1863
1864 // FIXME: conversion of A::* to B::* is better than conversion of
1865 // A::* to C::*,
1866
1867 // FIXME: conversion of B::* to C::* is better than conversion of
1868 // A::* to C::*, and
1869
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001870 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1871 SCS1.Second == ICK_Derived_To_Base) {
1872 // -- conversion of C to B is better than conversion of C to A,
1873 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1874 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1875 if (IsDerivedFrom(ToType1, ToType2))
1876 return ImplicitConversionSequence::Better;
1877 else if (IsDerivedFrom(ToType2, ToType1))
1878 return ImplicitConversionSequence::Worse;
1879 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001880
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001881 // -- conversion of B to A is better than conversion of C to A.
1882 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1883 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1884 if (IsDerivedFrom(FromType2, FromType1))
1885 return ImplicitConversionSequence::Better;
1886 else if (IsDerivedFrom(FromType1, FromType2))
1887 return ImplicitConversionSequence::Worse;
1888 }
1889 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001890
Douglas Gregor14046502008-10-23 00:40:37 +00001891 return ImplicitConversionSequence::Indistinguishable;
1892}
1893
Douglas Gregor81c29152008-10-29 00:13:59 +00001894/// TryCopyInitialization - Try to copy-initialize a value of type
1895/// ToType from the expression From. Return the implicit conversion
1896/// sequence required to pass this argument, which may be a bad
1897/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001898/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001899/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1900/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001901ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001902Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001903 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001904 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001905 ImplicitConversionSequence ICS;
Sebastian Redla55834a2009-04-12 17:16:29 +00001906 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1907 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001908 return ICS;
1909 } else {
Sebastian Redla55834a2009-04-12 17:16:29 +00001910 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1911 ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001912 }
1913}
1914
Sebastian Redla55834a2009-04-12 17:16:29 +00001915/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1916/// the expression @p From. Returns true (and emits a diagnostic) if there was
1917/// an error, returns false if the initialization succeeded. Elidable should
1918/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1919/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001920bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001921 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001922 if (!getLangOptions().CPlusPlus) {
1923 // In C, argument passing is the same as performing an assignment.
1924 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001925
Douglas Gregor81c29152008-10-29 00:13:59 +00001926 AssignConvertType ConvTy =
1927 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001928 if (ConvTy != Compatible &&
1929 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1930 ConvTy = Compatible;
1931
Douglas Gregor81c29152008-10-29 00:13:59 +00001932 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1933 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001934 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001935
Chris Lattner271d4c22008-11-24 05:29:24 +00001936 if (ToType->isReferenceType())
1937 return CheckReferenceInit(From, ToType);
1938
Sebastian Redla55834a2009-04-12 17:16:29 +00001939 if (!PerformImplicitConversion(From, ToType, Flavor,
1940 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001941 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001942
Chris Lattner271d4c22008-11-24 05:29:24 +00001943 return Diag(From->getSourceRange().getBegin(),
1944 diag::err_typecheck_convert_incompatible)
1945 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001946}
1947
Douglas Gregor5ed15042008-11-18 23:14:02 +00001948/// TryObjectArgumentInitialization - Try to initialize the object
1949/// parameter of the given member function (@c Method) from the
1950/// expression @p From.
1951ImplicitConversionSequence
1952Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1953 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1954 unsigned MethodQuals = Method->getTypeQualifiers();
1955 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1956
1957 // Set up the conversion sequence as a "bad" conversion, to allow us
1958 // to exit early.
1959 ImplicitConversionSequence ICS;
1960 ICS.Standard.setAsIdentityConversion();
1961 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1962
1963 // We need to have an object of class type.
1964 QualType FromType = From->getType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001965 if (const PointerType *PT = FromType->getAsPointerType())
1966 FromType = PT->getPointeeType();
1967
1968 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00001969
1970 // The implicit object parmeter is has the type "reference to cv X",
1971 // where X is the class of which the function is a member
1972 // (C++ [over.match.funcs]p4). However, when finding an implicit
1973 // conversion sequence for the argument, we are not allowed to
1974 // create temporaries or perform user-defined conversions
1975 // (C++ [over.match.funcs]p5). We perform a simplified version of
1976 // reference binding here, that allows class rvalues to bind to
1977 // non-constant references.
1978
1979 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1980 // with the implicit object parameter (C++ [over.match.funcs]p5).
1981 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1982 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1983 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1984 return ICS;
1985
1986 // Check that we have either the same type or a derived type. It
1987 // affects the conversion rank.
1988 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1989 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1990 ICS.Standard.Second = ICK_Identity;
1991 else if (IsDerivedFrom(FromType, ClassType))
1992 ICS.Standard.Second = ICK_Derived_To_Base;
1993 else
1994 return ICS;
1995
1996 // Success. Mark this as a reference binding.
1997 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1998 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1999 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2000 ICS.Standard.ReferenceBinding = true;
2001 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00002002 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002003 return ICS;
2004}
2005
2006/// PerformObjectArgumentInitialization - Perform initialization of
2007/// the implicit object parameter for the given Method with the given
2008/// expression.
2009bool
2010Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002011 QualType FromRecordType, DestType;
2012 QualType ImplicitParamRecordType =
2013 Method->getThisType(Context)->getAsPointerType()->getPointeeType();
2014
2015 if (const PointerType *PT = From->getType()->getAsPointerType()) {
2016 FromRecordType = PT->getPointeeType();
2017 DestType = Method->getThisType(Context);
2018 } else {
2019 FromRecordType = From->getType();
2020 DestType = ImplicitParamRecordType;
2021 }
2022
Douglas Gregor5ed15042008-11-18 23:14:02 +00002023 ImplicitConversionSequence ICS
2024 = TryObjectArgumentInitialization(From, Method);
2025 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2026 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002027 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002028 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2029
Douglas Gregor5ed15042008-11-18 23:14:02 +00002030 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002031 CheckDerivedToBaseConversion(FromRecordType,
2032 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002033 From->getSourceRange().getBegin(),
2034 From->getSourceRange()))
2035 return true;
2036
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002037 ImpCastExprToType(From, DestType, /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002038 return false;
2039}
2040
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002041/// TryContextuallyConvertToBool - Attempt to contextually convert the
2042/// expression From to bool (C++0x [conv]p3).
2043ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2044 return TryImplicitConversion(From, Context.BoolTy, false, true);
2045}
2046
2047/// PerformContextuallyConvertToBool - Perform a contextual conversion
2048/// of the expression From to bool (C++0x [conv]p3).
2049bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2050 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2051 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2052 return false;
2053
2054 return Diag(From->getSourceRange().getBegin(),
2055 diag::err_typecheck_bool_condition)
2056 << From->getType() << From->getSourceRange();
2057}
2058
Douglas Gregord2baafd2008-10-21 16:13:35 +00002059/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002060/// candidate functions, using the given function call arguments. If
2061/// @p SuppressUserConversions, then don't allow user-defined
2062/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002063/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2064/// hacky way to implement the overloading rules for elidable copy
2065/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002066void
2067Sema::AddOverloadCandidate(FunctionDecl *Function,
2068 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002069 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002070 bool SuppressUserConversions,
2071 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002072{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002073 const FunctionProtoType* Proto
2074 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002075 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002076 assert(!isa<CXXConversionDecl>(Function) &&
2077 "Use AddConversionCandidate for conversion functions");
Douglas Gregorb60eb752009-06-25 22:08:12 +00002078 assert(!Function->getDescribedFunctionTemplate() &&
2079 "Use AddTemplateOverloadCandidate for function templates");
2080
Douglas Gregor3257fb52008-12-22 05:46:06 +00002081 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002082 if (!isa<CXXConstructorDecl>(Method)) {
2083 // If we get here, it's because we're calling a member function
2084 // that is named without a member access expression (e.g.,
2085 // "this->f") that was either written explicitly or created
2086 // implicitly. This can happen with a qualified call to a member
2087 // function, e.g., X::f(). We use a NULL object as the implied
2088 // object argument (C++ [over.call.func]p3).
2089 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2090 SuppressUserConversions, ForceRValue);
2091 return;
2092 }
2093 // We treat a constructor like a non-member function, since its object
2094 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002095 }
2096
2097
Douglas Gregord2baafd2008-10-21 16:13:35 +00002098 // Add this candidate
2099 CandidateSet.push_back(OverloadCandidate());
2100 OverloadCandidate& Candidate = CandidateSet.back();
2101 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002102 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002103 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002104 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002105
2106 unsigned NumArgsInProto = Proto->getNumArgs();
2107
2108 // (C++ 13.3.2p2): A candidate function having fewer than m
2109 // parameters is viable only if it has an ellipsis in its parameter
2110 // list (8.3.5).
2111 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2112 Candidate.Viable = false;
2113 return;
2114 }
2115
2116 // (C++ 13.3.2p2): A candidate function having more than m parameters
2117 // is viable only if the (m+1)st parameter has a default argument
2118 // (8.3.6). For the purposes of overload resolution, the
2119 // parameter list is truncated on the right, so that there are
2120 // exactly m parameters.
2121 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2122 if (NumArgs < MinRequiredArgs) {
2123 // Not enough arguments.
2124 Candidate.Viable = false;
2125 return;
2126 }
2127
2128 // Determine the implicit conversion sequences for each of the
2129 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002130 Candidate.Conversions.resize(NumArgs);
2131 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2132 if (ArgIdx < NumArgsInProto) {
2133 // (C++ 13.3.2p3): for F to be a viable function, there shall
2134 // exist for each argument an implicit conversion sequence
2135 // (13.3.3.1) that converts that argument to the corresponding
2136 // parameter of F.
2137 QualType ParamType = Proto->getArgType(ArgIdx);
2138 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002139 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002140 SuppressUserConversions, ForceRValue);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002141 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002142 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002143 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002144 break;
2145 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002146 } else {
2147 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2148 // argument for which there is no corresponding parameter is
2149 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2150 Candidate.Conversions[ArgIdx].ConversionKind
2151 = ImplicitConversionSequence::EllipsisConversion;
2152 }
2153 }
2154}
2155
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002156/// \brief Add all of the function declarations in the given function set to
2157/// the overload canddiate set.
2158void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2159 Expr **Args, unsigned NumArgs,
2160 OverloadCandidateSet& CandidateSet,
2161 bool SuppressUserConversions) {
2162 for (FunctionSet::const_iterator F = Functions.begin(),
2163 FEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00002164 F != FEnd; ++F) {
2165 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2166 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2167 SuppressUserConversions);
2168 else
2169 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F), Args,
2170 NumArgs, CandidateSet,
2171 SuppressUserConversions);
2172 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002173}
2174
Douglas Gregor5ed15042008-11-18 23:14:02 +00002175/// AddMethodCandidate - Adds the given C++ member function to the set
2176/// of candidate functions, using the given function call arguments
2177/// and the object argument (@c Object). For example, in a call
2178/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2179/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2180/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002181/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2182/// a slightly hacky way to implement the overloading rules for elidable copy
2183/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002184void
2185Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2186 Expr **Args, unsigned NumArgs,
2187 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002188 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002189{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002190 const FunctionProtoType* Proto
2191 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002192 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002193 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002194 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002195 assert(!isa<CXXConstructorDecl>(Method) &&
2196 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002197
2198 // Add this candidate
2199 CandidateSet.push_back(OverloadCandidate());
2200 OverloadCandidate& Candidate = CandidateSet.back();
2201 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002202 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002203 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002204
2205 unsigned NumArgsInProto = Proto->getNumArgs();
2206
2207 // (C++ 13.3.2p2): A candidate function having fewer than m
2208 // parameters is viable only if it has an ellipsis in its parameter
2209 // list (8.3.5).
2210 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2211 Candidate.Viable = false;
2212 return;
2213 }
2214
2215 // (C++ 13.3.2p2): A candidate function having more than m parameters
2216 // is viable only if the (m+1)st parameter has a default argument
2217 // (8.3.6). For the purposes of overload resolution, the
2218 // parameter list is truncated on the right, so that there are
2219 // exactly m parameters.
2220 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2221 if (NumArgs < MinRequiredArgs) {
2222 // Not enough arguments.
2223 Candidate.Viable = false;
2224 return;
2225 }
2226
2227 Candidate.Viable = true;
2228 Candidate.Conversions.resize(NumArgs + 1);
2229
Douglas Gregor3257fb52008-12-22 05:46:06 +00002230 if (Method->isStatic() || !Object)
2231 // The implicit object argument is ignored.
2232 Candidate.IgnoreObjectArgument = true;
2233 else {
2234 // Determine the implicit conversion sequence for the object
2235 // parameter.
2236 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2237 if (Candidate.Conversions[0].ConversionKind
2238 == ImplicitConversionSequence::BadConversion) {
2239 Candidate.Viable = false;
2240 return;
2241 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002242 }
2243
2244 // Determine the implicit conversion sequences for each of the
2245 // arguments.
2246 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2247 if (ArgIdx < NumArgsInProto) {
2248 // (C++ 13.3.2p3): for F to be a viable function, there shall
2249 // exist for each argument an implicit conversion sequence
2250 // (13.3.3.1) that converts that argument to the corresponding
2251 // parameter of F.
2252 QualType ParamType = Proto->getArgType(ArgIdx);
2253 Candidate.Conversions[ArgIdx + 1]
2254 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002255 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002256 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2257 == ImplicitConversionSequence::BadConversion) {
2258 Candidate.Viable = false;
2259 break;
2260 }
2261 } else {
2262 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2263 // argument for which there is no corresponding parameter is
2264 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2265 Candidate.Conversions[ArgIdx + 1].ConversionKind
2266 = ImplicitConversionSequence::EllipsisConversion;
2267 }
2268 }
2269}
2270
Douglas Gregorb60eb752009-06-25 22:08:12 +00002271/// \brief Add a C++ function template as a candidate in the candidate set,
2272/// using template argument deduction to produce an appropriate function
2273/// template specialization.
2274void
2275Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2276 Expr **Args, unsigned NumArgs,
2277 OverloadCandidateSet& CandidateSet,
2278 bool SuppressUserConversions,
2279 bool ForceRValue) {
2280 // C++ [over.match.funcs]p7:
2281 // In each case where a candidate is a function template, candidate
2282 // function template specializations are generated using template argument
2283 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2284 // candidate functions in the usual way.113) A given name can refer to one
2285 // or more function templates and also to a set of overloaded non-template
2286 // functions. In such a case, the candidate functions generated from each
2287 // function template are combined with the set of non-template candidate
2288 // functions.
2289 TemplateDeductionInfo Info(Context);
2290 FunctionDecl *Specialization = 0;
2291 if (TemplateDeductionResult Result
2292 = DeduceTemplateArguments(FunctionTemplate, Args, NumArgs,
2293 Specialization, Info)) {
2294 // FIXME: Record what happened with template argument deduction, so
2295 // that we can give the user a beautiful diagnostic.
2296 (void)Result;
2297 return;
2298 }
2299
2300 // Add the function template specialization produced by template argument
2301 // deduction as a candidate.
2302 assert(Specialization && "Missing function template specialization?");
2303 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2304 SuppressUserConversions, ForceRValue);
2305}
2306
Douglas Gregor60714f92008-11-07 22:36:19 +00002307/// AddConversionCandidate - Add a C++ conversion function as a
2308/// candidate in the candidate set (C++ [over.match.conv],
2309/// C++ [over.match.copy]). From is the expression we're converting from,
2310/// and ToType is the type that we're eventually trying to convert to
2311/// (which may or may not be the same type as the type that the
2312/// conversion function produces).
2313void
2314Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2315 Expr *From, QualType ToType,
2316 OverloadCandidateSet& CandidateSet) {
2317 // Add this candidate
2318 CandidateSet.push_back(OverloadCandidate());
2319 OverloadCandidate& Candidate = CandidateSet.back();
2320 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002321 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002322 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002323 Candidate.FinalConversion.setAsIdentityConversion();
2324 Candidate.FinalConversion.FromTypePtr
2325 = Conversion->getConversionType().getAsOpaquePtr();
2326 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2327
Douglas Gregor5ed15042008-11-18 23:14:02 +00002328 // Determine the implicit conversion sequence for the implicit
2329 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002330 Candidate.Viable = true;
2331 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002332 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002333
Douglas Gregor60714f92008-11-07 22:36:19 +00002334 if (Candidate.Conversions[0].ConversionKind
2335 == ImplicitConversionSequence::BadConversion) {
2336 Candidate.Viable = false;
2337 return;
2338 }
2339
2340 // To determine what the conversion from the result of calling the
2341 // conversion function to the type we're eventually trying to
2342 // convert to (ToType), we need to synthesize a call to the
2343 // conversion function and attempt copy initialization from it. This
2344 // makes sure that we get the right semantics with respect to
2345 // lvalues/rvalues and the type. Fortunately, we can allocate this
2346 // call on the stack and we don't need its arguments to be
2347 // well-formed.
2348 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2349 SourceLocation());
2350 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregor70d26122008-11-12 17:17:38 +00002351 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002352
2353 // Note that it is safe to allocate CallExpr on the stack here because
2354 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2355 // allocator).
2356 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002357 Conversion->getConversionType().getNonReferenceType(),
2358 SourceLocation());
2359 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2360 switch (ICS.ConversionKind) {
2361 case ImplicitConversionSequence::StandardConversion:
2362 Candidate.FinalConversion = ICS.Standard;
2363 break;
2364
2365 case ImplicitConversionSequence::BadConversion:
2366 Candidate.Viable = false;
2367 break;
2368
2369 default:
2370 assert(false &&
2371 "Can only end up with a standard conversion sequence or failure");
2372 }
2373}
2374
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002375/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2376/// converts the given @c Object to a function pointer via the
2377/// conversion function @c Conversion, and then attempts to call it
2378/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2379/// the type of function that we'll eventually be calling.
2380void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002381 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002382 Expr *Object, Expr **Args, unsigned NumArgs,
2383 OverloadCandidateSet& CandidateSet) {
2384 CandidateSet.push_back(OverloadCandidate());
2385 OverloadCandidate& Candidate = CandidateSet.back();
2386 Candidate.Function = 0;
2387 Candidate.Surrogate = Conversion;
2388 Candidate.Viable = true;
2389 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002390 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002391 Candidate.Conversions.resize(NumArgs + 1);
2392
2393 // Determine the implicit conversion sequence for the implicit
2394 // object parameter.
2395 ImplicitConversionSequence ObjectInit
2396 = TryObjectArgumentInitialization(Object, Conversion);
2397 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2398 Candidate.Viable = false;
2399 return;
2400 }
2401
2402 // The first conversion is actually a user-defined conversion whose
2403 // first conversion is ObjectInit's standard conversion (which is
2404 // effectively a reference binding). Record it as such.
2405 Candidate.Conversions[0].ConversionKind
2406 = ImplicitConversionSequence::UserDefinedConversion;
2407 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2408 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2409 Candidate.Conversions[0].UserDefined.After
2410 = Candidate.Conversions[0].UserDefined.Before;
2411 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2412
2413 // Find the
2414 unsigned NumArgsInProto = Proto->getNumArgs();
2415
2416 // (C++ 13.3.2p2): A candidate function having fewer than m
2417 // parameters is viable only if it has an ellipsis in its parameter
2418 // list (8.3.5).
2419 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2420 Candidate.Viable = false;
2421 return;
2422 }
2423
2424 // Function types don't have any default arguments, so just check if
2425 // we have enough arguments.
2426 if (NumArgs < NumArgsInProto) {
2427 // Not enough arguments.
2428 Candidate.Viable = false;
2429 return;
2430 }
2431
2432 // Determine the implicit conversion sequences for each of the
2433 // arguments.
2434 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2435 if (ArgIdx < NumArgsInProto) {
2436 // (C++ 13.3.2p3): for F to be a viable function, there shall
2437 // exist for each argument an implicit conversion sequence
2438 // (13.3.3.1) that converts that argument to the corresponding
2439 // parameter of F.
2440 QualType ParamType = Proto->getArgType(ArgIdx);
2441 Candidate.Conversions[ArgIdx + 1]
2442 = TryCopyInitialization(Args[ArgIdx], ParamType,
2443 /*SuppressUserConversions=*/false);
2444 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2445 == ImplicitConversionSequence::BadConversion) {
2446 Candidate.Viable = false;
2447 break;
2448 }
2449 } else {
2450 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2451 // argument for which there is no corresponding parameter is
2452 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2453 Candidate.Conversions[ArgIdx + 1].ConversionKind
2454 = ImplicitConversionSequence::EllipsisConversion;
2455 }
2456 }
2457}
2458
Mike Stumpe127ae32009-05-16 07:39:55 +00002459// FIXME: This will eventually be removed, once we've migrated all of the
2460// operator overloading logic over to the scheme used by binary operators, which
2461// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002462void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002463 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002464 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002465 OverloadCandidateSet& CandidateSet,
2466 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002467
2468 FunctionSet Functions;
2469
2470 QualType T1 = Args[0]->getType();
2471 QualType T2;
2472 if (NumArgs > 1)
2473 T2 = Args[1]->getType();
2474
2475 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002476 if (S)
2477 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002478 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2479 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2480 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2481 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2482}
2483
2484/// \brief Add overload candidates for overloaded operators that are
2485/// member functions.
2486///
2487/// Add the overloaded operator candidates that are member functions
2488/// for the operator Op that was used in an operator expression such
2489/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2490/// CandidateSet will store the added overload candidates. (C++
2491/// [over.match.oper]).
2492void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2493 SourceLocation OpLoc,
2494 Expr **Args, unsigned NumArgs,
2495 OverloadCandidateSet& CandidateSet,
2496 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002497 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2498
2499 // C++ [over.match.oper]p3:
2500 // For a unary operator @ with an operand of a type whose
2501 // cv-unqualified version is T1, and for a binary operator @ with
2502 // a left operand of a type whose cv-unqualified version is T1 and
2503 // a right operand of a type whose cv-unqualified version is T2,
2504 // three sets of candidate functions, designated member
2505 // candidates, non-member candidates and built-in candidates, are
2506 // constructed as follows:
2507 QualType T1 = Args[0]->getType();
2508 QualType T2;
2509 if (NumArgs > 1)
2510 T2 = Args[1]->getType();
2511
2512 // -- If T1 is a class type, the set of member candidates is the
2513 // result of the qualified lookup of T1::operator@
2514 // (13.3.1.1.1); otherwise, the set of member candidates is
2515 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002516 // FIXME: Lookup in base classes, too!
Douglas Gregor5ed15042008-11-18 23:14:02 +00002517 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002518 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002519 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002520 Oper != OperEnd; ++Oper)
2521 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2522 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002523 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002524 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002525}
2526
Douglas Gregor70d26122008-11-12 17:17:38 +00002527/// AddBuiltinCandidate - Add a candidate for a built-in
2528/// operator. ResultTy and ParamTys are the result and parameter types
2529/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002530/// arguments being passed to the candidate. IsAssignmentOperator
2531/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002532/// operator. NumContextualBoolArguments is the number of arguments
2533/// (at the beginning of the argument list) that will be contextually
2534/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002535void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2536 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002537 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002538 bool IsAssignmentOperator,
2539 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002540 // Add this candidate
2541 CandidateSet.push_back(OverloadCandidate());
2542 OverloadCandidate& Candidate = CandidateSet.back();
2543 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002544 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002545 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002546 Candidate.BuiltinTypes.ResultTy = ResultTy;
2547 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2548 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2549
2550 // Determine the implicit conversion sequences for each of the
2551 // arguments.
2552 Candidate.Viable = true;
2553 Candidate.Conversions.resize(NumArgs);
2554 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002555 // C++ [over.match.oper]p4:
2556 // For the built-in assignment operators, conversions of the
2557 // left operand are restricted as follows:
2558 // -- no temporaries are introduced to hold the left operand, and
2559 // -- no user-defined conversions are applied to the left
2560 // operand to achieve a type match with the left-most
2561 // parameter of a built-in candidate.
2562 //
2563 // We block these conversions by turning off user-defined
2564 // conversions, since that is the only way that initialization of
2565 // a reference to a non-class type can occur from something that
2566 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002567 if (ArgIdx < NumContextualBoolArguments) {
2568 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2569 "Contextual conversion to bool requires bool type");
2570 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2571 } else {
2572 Candidate.Conversions[ArgIdx]
2573 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2574 ArgIdx == 0 && IsAssignmentOperator);
2575 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002576 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002577 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002578 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002579 break;
2580 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002581 }
2582}
2583
2584/// BuiltinCandidateTypeSet - A set of types that will be used for the
2585/// candidate operator functions for built-in operators (C++
2586/// [over.built]). The types are separated into pointer types and
2587/// enumeration types.
2588class BuiltinCandidateTypeSet {
2589 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002590 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002591
2592 /// PointerTypes - The set of pointer types that will be used in the
2593 /// built-in candidates.
2594 TypeSet PointerTypes;
2595
Sebastian Redl674d1b72009-04-19 21:53:20 +00002596 /// MemberPointerTypes - The set of member pointer types that will be
2597 /// used in the built-in candidates.
2598 TypeSet MemberPointerTypes;
2599
Douglas Gregor70d26122008-11-12 17:17:38 +00002600 /// EnumerationTypes - The set of enumeration types that will be
2601 /// used in the built-in candidates.
2602 TypeSet EnumerationTypes;
2603
2604 /// Context - The AST context in which we will build the type sets.
2605 ASTContext &Context;
2606
Sebastian Redl674d1b72009-04-19 21:53:20 +00002607 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2608 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002609
2610public:
2611 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002612 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002613
2614 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2615
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002616 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2617 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002618
2619 /// pointer_begin - First pointer type found;
2620 iterator pointer_begin() { return PointerTypes.begin(); }
2621
Sebastian Redl674d1b72009-04-19 21:53:20 +00002622 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002623 iterator pointer_end() { return PointerTypes.end(); }
2624
Sebastian Redl674d1b72009-04-19 21:53:20 +00002625 /// member_pointer_begin - First member pointer type found;
2626 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2627
2628 /// member_pointer_end - Past the last member pointer type found;
2629 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2630
Douglas Gregor70d26122008-11-12 17:17:38 +00002631 /// enumeration_begin - First enumeration type found;
2632 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2633
Sebastian Redl674d1b72009-04-19 21:53:20 +00002634 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002635 iterator enumeration_end() { return EnumerationTypes.end(); }
2636};
2637
Sebastian Redl674d1b72009-04-19 21:53:20 +00002638/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002639/// the set of pointer types along with any more-qualified variants of
2640/// that type. For example, if @p Ty is "int const *", this routine
2641/// will add "int const *", "int const volatile *", "int const
2642/// restrict *", and "int const volatile restrict *" to the set of
2643/// pointer types. Returns true if the add of @p Ty itself succeeded,
2644/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002645bool
2646BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002647 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002648 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002649 return false;
2650
2651 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2652 QualType PointeeTy = PointerTy->getPointeeType();
2653 // FIXME: Optimize this so that we don't keep trying to add the same types.
2654
Mike Stumpe127ae32009-05-16 07:39:55 +00002655 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2656 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002657 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002658 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002659 (Context.getPointerType(PointeeTy.withConst()));
2660 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002661 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002662 (Context.getPointerType(PointeeTy.withVolatile()));
2663 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002664 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002665 (Context.getPointerType(PointeeTy.withRestrict()));
2666 }
2667
2668 return true;
2669}
2670
Sebastian Redl674d1b72009-04-19 21:53:20 +00002671/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2672/// to the set of pointer types along with any more-qualified variants of
2673/// that type. For example, if @p Ty is "int const *", this routine
2674/// will add "int const *", "int const volatile *", "int const
2675/// restrict *", and "int const volatile restrict *" to the set of
2676/// pointer types. Returns true if the add of @p Ty itself succeeded,
2677/// false otherwise.
2678bool
2679BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2680 QualType Ty) {
2681 // Insert this type.
2682 if (!MemberPointerTypes.insert(Ty))
2683 return false;
2684
2685 if (const MemberPointerType *PointerTy = Ty->getAsMemberPointerType()) {
2686 QualType PointeeTy = PointerTy->getPointeeType();
2687 const Type *ClassTy = PointerTy->getClass();
2688 // FIXME: Optimize this so that we don't keep trying to add the same types.
2689
2690 if (!PointeeTy.isConstQualified())
2691 AddMemberPointerWithMoreQualifiedTypeVariants
2692 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2693 if (!PointeeTy.isVolatileQualified())
2694 AddMemberPointerWithMoreQualifiedTypeVariants
2695 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2696 if (!PointeeTy.isRestrictQualified())
2697 AddMemberPointerWithMoreQualifiedTypeVariants
2698 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2699 }
2700
2701 return true;
2702}
2703
Douglas Gregor70d26122008-11-12 17:17:38 +00002704/// AddTypesConvertedFrom - Add each of the types to which the type @p
2705/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002706/// primarily interested in pointer types and enumeration types. We also
2707/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002708/// AllowUserConversions is true if we should look at the conversion
2709/// functions of a class type, and AllowExplicitConversions if we
2710/// should also include the explicit conversion functions of a class
2711/// type.
2712void
2713BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2714 bool AllowUserConversions,
2715 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002716 // Only deal with canonical types.
2717 Ty = Context.getCanonicalType(Ty);
2718
2719 // Look through reference types; they aren't part of the type of an
2720 // expression for the purposes of conversions.
2721 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2722 Ty = RefTy->getPointeeType();
2723
2724 // We don't care about qualifiers on the type.
2725 Ty = Ty.getUnqualifiedType();
2726
2727 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2728 QualType PointeeTy = PointerTy->getPointeeType();
2729
2730 // Insert our type, and its more-qualified variants, into the set
2731 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002732 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002733 return;
2734
2735 // Add 'cv void*' to our set of types.
2736 if (!Ty->isVoidType()) {
2737 QualType QualVoid
2738 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002739 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002740 }
2741
2742 // If this is a pointer to a class type, add pointers to its bases
2743 // (with the same level of cv-qualification as the original
2744 // derived class, of course).
2745 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2746 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2747 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2748 Base != ClassDecl->bases_end(); ++Base) {
2749 QualType BaseTy = Context.getCanonicalType(Base->getType());
2750 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2751
2752 // Add the pointer type, recursively, so that we get all of
2753 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002754 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002755 }
2756 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002757 } else if (Ty->isMemberPointerType()) {
2758 // Member pointers are far easier, since the pointee can't be converted.
2759 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2760 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002761 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002762 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002763 } else if (AllowUserConversions) {
2764 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2765 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2766 // FIXME: Visit conversion functions in the base classes, too.
2767 OverloadedFunctionDecl *Conversions
2768 = ClassDecl->getConversionFunctions();
2769 for (OverloadedFunctionDecl::function_iterator Func
2770 = Conversions->function_begin();
2771 Func != Conversions->function_end(); ++Func) {
2772 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002773 if (AllowExplicitConversions || !Conv->isExplicit())
2774 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002775 }
2776 }
2777 }
2778}
2779
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002780/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2781/// operator overloads to the candidate set (C++ [over.built]), based
2782/// on the operator @p Op and the arguments given. For example, if the
2783/// operator is a binary '+', this routine might add "int
2784/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002785void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002786Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2787 Expr **Args, unsigned NumArgs,
2788 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002789 // The set of "promoted arithmetic types", which are the arithmetic
2790 // types are that preserved by promotion (C++ [over.built]p2). Note
2791 // that the first few of these types are the promoted integral
2792 // types; these types need to be first.
2793 // FIXME: What about complex?
2794 const unsigned FirstIntegralType = 0;
2795 const unsigned LastIntegralType = 13;
2796 const unsigned FirstPromotedIntegralType = 7,
2797 LastPromotedIntegralType = 13;
2798 const unsigned FirstPromotedArithmeticType = 7,
2799 LastPromotedArithmeticType = 16;
2800 const unsigned NumArithmeticTypes = 16;
2801 QualType ArithmeticTypes[NumArithmeticTypes] = {
2802 Context.BoolTy, Context.CharTy, Context.WCharTy,
2803 Context.SignedCharTy, Context.ShortTy,
2804 Context.UnsignedCharTy, Context.UnsignedShortTy,
2805 Context.IntTy, Context.LongTy, Context.LongLongTy,
2806 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2807 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2808 };
2809
2810 // Find all of the types that the arguments can convert to, but only
2811 // if the operator we're looking at has built-in operator candidates
2812 // that make use of these types.
2813 BuiltinCandidateTypeSet CandidateTypes(Context);
2814 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2815 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002816 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002817 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002818 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00002819 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002820 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002821 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2822 true,
2823 (Op == OO_Exclaim ||
2824 Op == OO_AmpAmp ||
2825 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002826 }
2827
2828 bool isComparison = false;
2829 switch (Op) {
2830 case OO_None:
2831 case NUM_OVERLOADED_OPERATORS:
2832 assert(false && "Expected an overloaded operator");
2833 break;
2834
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002835 case OO_Star: // '*' is either unary or binary
2836 if (NumArgs == 1)
2837 goto UnaryStar;
2838 else
2839 goto BinaryStar;
2840 break;
2841
2842 case OO_Plus: // '+' is either unary or binary
2843 if (NumArgs == 1)
2844 goto UnaryPlus;
2845 else
2846 goto BinaryPlus;
2847 break;
2848
2849 case OO_Minus: // '-' is either unary or binary
2850 if (NumArgs == 1)
2851 goto UnaryMinus;
2852 else
2853 goto BinaryMinus;
2854 break;
2855
2856 case OO_Amp: // '&' is either unary or binary
2857 if (NumArgs == 1)
2858 goto UnaryAmp;
2859 else
2860 goto BinaryAmp;
2861
2862 case OO_PlusPlus:
2863 case OO_MinusMinus:
2864 // C++ [over.built]p3:
2865 //
2866 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2867 // is either volatile or empty, there exist candidate operator
2868 // functions of the form
2869 //
2870 // VQ T& operator++(VQ T&);
2871 // T operator++(VQ T&, int);
2872 //
2873 // C++ [over.built]p4:
2874 //
2875 // For every pair (T, VQ), where T is an arithmetic type other
2876 // than bool, and VQ is either volatile or empty, there exist
2877 // candidate operator functions of the form
2878 //
2879 // VQ T& operator--(VQ T&);
2880 // T operator--(VQ T&, int);
2881 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2882 Arith < NumArithmeticTypes; ++Arith) {
2883 QualType ArithTy = ArithmeticTypes[Arith];
2884 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00002885 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002886
2887 // Non-volatile version.
2888 if (NumArgs == 1)
2889 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2890 else
2891 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2892
2893 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00002894 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002895 if (NumArgs == 1)
2896 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2897 else
2898 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2899 }
2900
2901 // C++ [over.built]p5:
2902 //
2903 // For every pair (T, VQ), where T is a cv-qualified or
2904 // cv-unqualified object type, and VQ is either volatile or
2905 // empty, there exist candidate operator functions of the form
2906 //
2907 // T*VQ& operator++(T*VQ&);
2908 // T*VQ& operator--(T*VQ&);
2909 // T* operator++(T*VQ&, int);
2910 // T* operator--(T*VQ&, int);
2911 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2912 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2913 // Skip pointer types that aren't pointers to object types.
Douglas Gregor26ea1222009-03-24 20:32:41 +00002914 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002915 continue;
2916
2917 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002918 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002919 };
2920
2921 // Without volatile
2922 if (NumArgs == 1)
2923 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2924 else
2925 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2926
2927 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2928 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00002929 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002930 if (NumArgs == 1)
2931 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2932 else
2933 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2934 }
2935 }
2936 break;
2937
2938 UnaryStar:
2939 // C++ [over.built]p6:
2940 // For every cv-qualified or cv-unqualified object type T, there
2941 // exist candidate operator functions of the form
2942 //
2943 // T& operator*(T*);
2944 //
2945 // C++ [over.built]p7:
2946 // For every function type T, there exist candidate operator
2947 // functions of the form
2948 // T& operator*(T*);
2949 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2950 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2951 QualType ParamTy = *Ptr;
2952 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00002953 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002954 &ParamTy, Args, 1, CandidateSet);
2955 }
2956 break;
2957
2958 UnaryPlus:
2959 // C++ [over.built]p8:
2960 // For every type T, there exist candidate operator functions of
2961 // the form
2962 //
2963 // T* operator+(T*);
2964 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2965 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2966 QualType ParamTy = *Ptr;
2967 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2968 }
2969
2970 // Fall through
2971
2972 UnaryMinus:
2973 // C++ [over.built]p9:
2974 // For every promoted arithmetic type T, there exist candidate
2975 // operator functions of the form
2976 //
2977 // T operator+(T);
2978 // T operator-(T);
2979 for (unsigned Arith = FirstPromotedArithmeticType;
2980 Arith < LastPromotedArithmeticType; ++Arith) {
2981 QualType ArithTy = ArithmeticTypes[Arith];
2982 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2983 }
2984 break;
2985
2986 case OO_Tilde:
2987 // C++ [over.built]p10:
2988 // For every promoted integral type T, there exist candidate
2989 // operator functions of the form
2990 //
2991 // T operator~(T);
2992 for (unsigned Int = FirstPromotedIntegralType;
2993 Int < LastPromotedIntegralType; ++Int) {
2994 QualType IntTy = ArithmeticTypes[Int];
2995 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2996 }
2997 break;
2998
Douglas Gregor70d26122008-11-12 17:17:38 +00002999 case OO_New:
3000 case OO_Delete:
3001 case OO_Array_New:
3002 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00003003 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003004 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00003005 break;
3006
3007 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003008 UnaryAmp:
3009 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00003010 // C++ [over.match.oper]p3:
3011 // -- For the operator ',', the unary operator '&', or the
3012 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00003013 break;
3014
3015 case OO_Less:
3016 case OO_Greater:
3017 case OO_LessEqual:
3018 case OO_GreaterEqual:
3019 case OO_EqualEqual:
3020 case OO_ExclaimEqual:
3021 // C++ [over.built]p15:
3022 //
3023 // For every pointer or enumeration type T, there exist
3024 // candidate operator functions of the form
3025 //
3026 // bool operator<(T, T);
3027 // bool operator>(T, T);
3028 // bool operator<=(T, T);
3029 // bool operator>=(T, T);
3030 // bool operator==(T, T);
3031 // bool operator!=(T, T);
3032 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3033 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3034 QualType ParamTypes[2] = { *Ptr, *Ptr };
3035 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3036 }
3037 for (BuiltinCandidateTypeSet::iterator Enum
3038 = CandidateTypes.enumeration_begin();
3039 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3040 QualType ParamTypes[2] = { *Enum, *Enum };
3041 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3042 }
3043
3044 // Fall through.
3045 isComparison = true;
3046
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003047 BinaryPlus:
3048 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003049 if (!isComparison) {
3050 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3051
3052 // C++ [over.built]p13:
3053 //
3054 // For every cv-qualified or cv-unqualified object type T
3055 // there exist candidate operator functions of the form
3056 //
3057 // T* operator+(T*, ptrdiff_t);
3058 // T& operator[](T*, ptrdiff_t); [BELOW]
3059 // T* operator-(T*, ptrdiff_t);
3060 // T* operator+(ptrdiff_t, T*);
3061 // T& operator[](ptrdiff_t, T*); [BELOW]
3062 //
3063 // C++ [over.built]p14:
3064 //
3065 // For every T, where T is a pointer to object type, there
3066 // exist candidate operator functions of the form
3067 //
3068 // ptrdiff_t operator-(T, T);
3069 for (BuiltinCandidateTypeSet::iterator Ptr
3070 = CandidateTypes.pointer_begin();
3071 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3072 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3073
3074 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3075 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3076
3077 if (Op == OO_Plus) {
3078 // T* operator+(ptrdiff_t, T*);
3079 ParamTypes[0] = ParamTypes[1];
3080 ParamTypes[1] = *Ptr;
3081 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3082 } else {
3083 // ptrdiff_t operator-(T, T);
3084 ParamTypes[1] = *Ptr;
3085 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3086 Args, 2, CandidateSet);
3087 }
3088 }
3089 }
3090 // Fall through
3091
Douglas Gregor70d26122008-11-12 17:17:38 +00003092 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003093 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003094 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003095 // C++ [over.built]p12:
3096 //
3097 // For every pair of promoted arithmetic types L and R, there
3098 // exist candidate operator functions of the form
3099 //
3100 // LR operator*(L, R);
3101 // LR operator/(L, R);
3102 // LR operator+(L, R);
3103 // LR operator-(L, R);
3104 // bool operator<(L, R);
3105 // bool operator>(L, R);
3106 // bool operator<=(L, R);
3107 // bool operator>=(L, R);
3108 // bool operator==(L, R);
3109 // bool operator!=(L, R);
3110 //
3111 // where LR is the result of the usual arithmetic conversions
3112 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003113 //
3114 // C++ [over.built]p24:
3115 //
3116 // For every pair of promoted arithmetic types L and R, there exist
3117 // candidate operator functions of the form
3118 //
3119 // LR operator?(bool, L, R);
3120 //
3121 // where LR is the result of the usual arithmetic conversions
3122 // between types L and R.
3123 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003124 for (unsigned Left = FirstPromotedArithmeticType;
3125 Left < LastPromotedArithmeticType; ++Left) {
3126 for (unsigned Right = FirstPromotedArithmeticType;
3127 Right < LastPromotedArithmeticType; ++Right) {
3128 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3129 QualType Result
3130 = isComparison? Context.BoolTy
3131 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3132 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3133 }
3134 }
3135 break;
3136
3137 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003138 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003139 case OO_Caret:
3140 case OO_Pipe:
3141 case OO_LessLess:
3142 case OO_GreaterGreater:
3143 // C++ [over.built]p17:
3144 //
3145 // For every pair of promoted integral types L and R, there
3146 // exist candidate operator functions of the form
3147 //
3148 // LR operator%(L, R);
3149 // LR operator&(L, R);
3150 // LR operator^(L, R);
3151 // LR operator|(L, R);
3152 // L operator<<(L, R);
3153 // L operator>>(L, R);
3154 //
3155 // where LR is the result of the usual arithmetic conversions
3156 // between types L and R.
3157 for (unsigned Left = FirstPromotedIntegralType;
3158 Left < LastPromotedIntegralType; ++Left) {
3159 for (unsigned Right = FirstPromotedIntegralType;
3160 Right < LastPromotedIntegralType; ++Right) {
3161 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3162 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3163 ? LandR[0]
3164 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3165 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3166 }
3167 }
3168 break;
3169
3170 case OO_Equal:
3171 // C++ [over.built]p20:
3172 //
3173 // For every pair (T, VQ), where T is an enumeration or
3174 // (FIXME:) pointer to member type and VQ is either volatile or
3175 // empty, there exist candidate operator functions of the form
3176 //
3177 // VQ T& operator=(VQ T&, T);
3178 for (BuiltinCandidateTypeSet::iterator Enum
3179 = CandidateTypes.enumeration_begin();
3180 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3181 QualType ParamTypes[2];
3182
3183 // T& operator=(T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003184 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregor70d26122008-11-12 17:17:38 +00003185 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003186 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003187 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003188
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003189 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3190 // volatile T& operator=(volatile T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003191 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003192 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003193 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003194 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003195 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003196 }
3197 // Fall through.
3198
3199 case OO_PlusEqual:
3200 case OO_MinusEqual:
3201 // C++ [over.built]p19:
3202 //
3203 // For every pair (T, VQ), where T is any type and VQ is either
3204 // volatile or empty, there exist candidate operator functions
3205 // of the form
3206 //
3207 // T*VQ& operator=(T*VQ&, T*);
3208 //
3209 // C++ [over.built]p21:
3210 //
3211 // For every pair (T, VQ), where T is a cv-qualified or
3212 // cv-unqualified object type and VQ is either volatile or
3213 // empty, there exist candidate operator functions of the form
3214 //
3215 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3216 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3217 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3218 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3219 QualType ParamTypes[2];
3220 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3221
3222 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003223 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003224 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3225 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003226
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003227 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3228 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003229 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003230 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3231 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003232 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003233 }
3234 // Fall through.
3235
3236 case OO_StarEqual:
3237 case OO_SlashEqual:
3238 // C++ [over.built]p18:
3239 //
3240 // For every triple (L, VQ, R), where L is an arithmetic type,
3241 // VQ is either volatile or empty, and R is a promoted
3242 // arithmetic type, there exist candidate operator functions of
3243 // the form
3244 //
3245 // VQ L& operator=(VQ L&, R);
3246 // VQ L& operator*=(VQ L&, R);
3247 // VQ L& operator/=(VQ L&, R);
3248 // VQ L& operator+=(VQ L&, R);
3249 // VQ L& operator-=(VQ L&, R);
3250 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3251 for (unsigned Right = FirstPromotedArithmeticType;
3252 Right < LastPromotedArithmeticType; ++Right) {
3253 QualType ParamTypes[2];
3254 ParamTypes[1] = ArithmeticTypes[Right];
3255
3256 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003257 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
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
3261 // Add this built-in operator as a candidate (VQ is 'volatile').
3262 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003263 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003264 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3265 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003266 }
3267 }
3268 break;
3269
3270 case OO_PercentEqual:
3271 case OO_LessLessEqual:
3272 case OO_GreaterGreaterEqual:
3273 case OO_AmpEqual:
3274 case OO_CaretEqual:
3275 case OO_PipeEqual:
3276 // C++ [over.built]p22:
3277 //
3278 // For every triple (L, VQ, R), where L is an integral type, VQ
3279 // is either volatile or empty, and R is a promoted integral
3280 // type, there exist candidate operator functions of the form
3281 //
3282 // VQ L& operator%=(VQ L&, R);
3283 // VQ L& operator<<=(VQ L&, R);
3284 // VQ L& operator>>=(VQ L&, R);
3285 // VQ L& operator&=(VQ L&, R);
3286 // VQ L& operator^=(VQ L&, R);
3287 // VQ L& operator|=(VQ L&, R);
3288 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3289 for (unsigned Right = FirstPromotedIntegralType;
3290 Right < LastPromotedIntegralType; ++Right) {
3291 QualType ParamTypes[2];
3292 ParamTypes[1] = ArithmeticTypes[Right];
3293
3294 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003295 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003296 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3297
3298 // Add this built-in operator as a candidate (VQ is 'volatile').
3299 ParamTypes[0] = ArithmeticTypes[Left];
3300 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003301 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003302 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3303 }
3304 }
3305 break;
3306
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003307 case OO_Exclaim: {
3308 // C++ [over.operator]p23:
3309 //
3310 // There also exist candidate operator functions of the form
3311 //
3312 // bool operator!(bool);
3313 // bool operator&&(bool, bool); [BELOW]
3314 // bool operator||(bool, bool); [BELOW]
3315 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003316 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3317 /*IsAssignmentOperator=*/false,
3318 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003319 break;
3320 }
3321
Douglas Gregor70d26122008-11-12 17:17:38 +00003322 case OO_AmpAmp:
3323 case OO_PipePipe: {
3324 // C++ [over.operator]p23:
3325 //
3326 // There also exist candidate operator functions of the form
3327 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003328 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003329 // bool operator&&(bool, bool);
3330 // bool operator||(bool, bool);
3331 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003332 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3333 /*IsAssignmentOperator=*/false,
3334 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003335 break;
3336 }
3337
3338 case OO_Subscript:
3339 // C++ [over.built]p13:
3340 //
3341 // For every cv-qualified or cv-unqualified object type T there
3342 // exist candidate operator functions of the form
3343 //
3344 // T* operator+(T*, ptrdiff_t); [ABOVE]
3345 // T& operator[](T*, ptrdiff_t);
3346 // T* operator-(T*, ptrdiff_t); [ABOVE]
3347 // T* operator+(ptrdiff_t, T*); [ABOVE]
3348 // T& operator[](ptrdiff_t, T*);
3349 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3350 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3351 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3352 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003353 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003354
3355 // T& operator[](T*, ptrdiff_t)
3356 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3357
3358 // T& operator[](ptrdiff_t, T*);
3359 ParamTypes[0] = ParamTypes[1];
3360 ParamTypes[1] = *Ptr;
3361 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3362 }
3363 break;
3364
3365 case OO_ArrowStar:
3366 // FIXME: No support for pointer-to-members yet.
3367 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003368
3369 case OO_Conditional:
3370 // Note that we don't consider the first argument, since it has been
3371 // contextually converted to bool long ago. The candidates below are
3372 // therefore added as binary.
3373 //
3374 // C++ [over.built]p24:
3375 // For every type T, where T is a pointer or pointer-to-member type,
3376 // there exist candidate operator functions of the form
3377 //
3378 // T operator?(bool, T, T);
3379 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003380 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3381 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3382 QualType ParamTypes[2] = { *Ptr, *Ptr };
3383 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3384 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003385 for (BuiltinCandidateTypeSet::iterator Ptr =
3386 CandidateTypes.member_pointer_begin(),
3387 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3388 QualType ParamTypes[2] = { *Ptr, *Ptr };
3389 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3390 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003391 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003392 }
3393}
3394
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003395/// \brief Add function candidates found via argument-dependent lookup
3396/// to the set of overloading candidates.
3397///
3398/// This routine performs argument-dependent name lookup based on the
3399/// given function name (which may also be an operator name) and adds
3400/// all of the overload candidates found by ADL to the overload
3401/// candidate set (C++ [basic.lookup.argdep]).
3402void
3403Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3404 Expr **Args, unsigned NumArgs,
3405 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003406 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003407
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003408 // Record all of the function candidates that we've already
3409 // added to the overload set, so that we don't add those same
3410 // candidates a second time.
3411 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3412 CandEnd = CandidateSet.end();
3413 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003414 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003415 Functions.insert(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003416 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3417 Functions.insert(FunTmpl);
3418 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003419
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003420 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003421
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003422 // Erase all of the candidates we already knew about.
3423 // FIXME: This is suboptimal. Is there a better way?
3424 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3425 CandEnd = CandidateSet.end();
3426 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003427 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003428 Functions.erase(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003429 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3430 Functions.erase(FunTmpl);
3431 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003432
3433 // For each of the ADL candidates we found, add it to the overload
3434 // set.
3435 for (FunctionSet::iterator Func = Functions.begin(),
3436 FuncEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00003437 Func != FuncEnd; ++Func) {
3438 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3439 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3440 else
3441 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func), Args,
3442 NumArgs, CandidateSet);
3443 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003444}
3445
Douglas Gregord2baafd2008-10-21 16:13:35 +00003446/// isBetterOverloadCandidate - Determines whether the first overload
3447/// candidate is a better candidate than the second (C++ 13.3.3p1).
3448bool
3449Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3450 const OverloadCandidate& Cand2)
3451{
3452 // Define viable functions to be better candidates than non-viable
3453 // functions.
3454 if (!Cand2.Viable)
3455 return Cand1.Viable;
3456 else if (!Cand1.Viable)
3457 return false;
3458
Douglas Gregor3257fb52008-12-22 05:46:06 +00003459 // C++ [over.match.best]p1:
3460 //
3461 // -- if F is a static member function, ICS1(F) is defined such
3462 // that ICS1(F) is neither better nor worse than ICS1(G) for
3463 // any function G, and, symmetrically, ICS1(G) is neither
3464 // better nor worse than ICS1(F).
3465 unsigned StartArg = 0;
3466 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3467 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003468
3469 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3470 // function than another viable function F2 if for all arguments i,
3471 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3472 // then...
3473 unsigned NumArgs = Cand1.Conversions.size();
3474 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3475 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003476 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003477 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3478 Cand2.Conversions[ArgIdx])) {
3479 case ImplicitConversionSequence::Better:
3480 // Cand1 has a better conversion sequence.
3481 HasBetterConversion = true;
3482 break;
3483
3484 case ImplicitConversionSequence::Worse:
3485 // Cand1 can't be better than Cand2.
3486 return false;
3487
3488 case ImplicitConversionSequence::Indistinguishable:
3489 // Do nothing.
3490 break;
3491 }
3492 }
3493
3494 if (HasBetterConversion)
3495 return true;
3496
Douglas Gregor70d26122008-11-12 17:17:38 +00003497 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3498 // implemented, but they require template support.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003499
Douglas Gregor60714f92008-11-07 22:36:19 +00003500 // C++ [over.match.best]p1b4:
3501 //
3502 // -- the context is an initialization by user-defined conversion
3503 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3504 // from the return type of F1 to the destination type (i.e.,
3505 // the type of the entity being initialized) is a better
3506 // conversion sequence than the standard conversion sequence
3507 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003508 if (Cand1.Function && Cand2.Function &&
3509 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003510 isa<CXXConversionDecl>(Cand2.Function)) {
3511 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3512 Cand2.FinalConversion)) {
3513 case ImplicitConversionSequence::Better:
3514 // Cand1 has a better conversion sequence.
3515 return true;
3516
3517 case ImplicitConversionSequence::Worse:
3518 // Cand1 can't be better than Cand2.
3519 return false;
3520
3521 case ImplicitConversionSequence::Indistinguishable:
3522 // Do nothing
3523 break;
3524 }
3525 }
3526
Douglas Gregord2baafd2008-10-21 16:13:35 +00003527 return false;
3528}
3529
Douglas Gregor98189262009-06-19 23:52:42 +00003530/// \brief Computes the best viable function (C++ 13.3.3)
3531/// within an overload candidate set.
3532///
3533/// \param CandidateSet the set of candidate functions.
3534///
3535/// \param Loc the location of the function name (or operator symbol) for
3536/// which overload resolution occurs.
3537///
3538/// \param Best f overload resolution was successful or found a deleted
3539/// function, Best points to the candidate function found.
3540///
3541/// \returns The result of overload resolution.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003542Sema::OverloadingResult
3543Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003544 SourceLocation Loc,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003545 OverloadCandidateSet::iterator& Best)
3546{
3547 // Find the best viable function.
3548 Best = CandidateSet.end();
3549 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3550 Cand != CandidateSet.end(); ++Cand) {
3551 if (Cand->Viable) {
3552 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3553 Best = Cand;
3554 }
3555 }
3556
3557 // If we didn't find any viable functions, abort.
3558 if (Best == CandidateSet.end())
3559 return OR_No_Viable_Function;
3560
3561 // Make sure that this function is better than every other viable
3562 // function. If not, we have an ambiguity.
3563 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3564 Cand != CandidateSet.end(); ++Cand) {
3565 if (Cand->Viable &&
3566 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003567 !isBetterOverloadCandidate(*Best, *Cand)) {
3568 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003569 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003570 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003571 }
3572
3573 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003574 if (Best->Function &&
3575 (Best->Function->isDeleted() ||
Douglas Gregor98da6ae2009-06-18 16:11:24 +00003576 Best->Function->getAttr<UnavailableAttr>(Context)))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003577 return OR_Deleted;
3578
Douglas Gregor98189262009-06-19 23:52:42 +00003579 // C++ [basic.def.odr]p2:
3580 // An overloaded function is used if it is selected by overload resolution
3581 // when referred to from a potentially-evaluated expression. [Note: this
3582 // covers calls to named functions (5.2.2), operator overloading
3583 // (clause 13), user-defined conversions (12.3.2), allocation function for
3584 // placement new (5.3.4), as well as non-default initialization (8.5).
3585 if (Best->Function)
3586 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003587 return OR_Success;
3588}
3589
3590/// PrintOverloadCandidates - When overload resolution fails, prints
3591/// diagnostic messages containing the candidates in the candidate
3592/// set. If OnlyViable is true, only viable candidates will be printed.
3593void
3594Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3595 bool OnlyViable)
3596{
3597 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3598 LastCand = CandidateSet.end();
3599 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003600 if (Cand->Viable || !OnlyViable) {
3601 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003602 if (Cand->Function->isDeleted() ||
Douglas Gregor98da6ae2009-06-18 16:11:24 +00003603 Cand->Function->getAttr<UnavailableAttr>(Context)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003604 // Deleted or "unavailable" function.
3605 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3606 << Cand->Function->isDeleted();
3607 } else {
3608 // Normal function
3609 // FIXME: Give a better reason!
3610 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3611 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003612 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003613 // Desugar the type of the surrogate down to a function type,
3614 // retaining as many typedefs as possible while still showing
3615 // the function type (and, therefore, its parameter types).
3616 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003617 bool isLValueReference = false;
3618 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003619 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003620 if (const LValueReferenceType *FnTypeRef =
3621 FnType->getAsLValueReferenceType()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003622 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003623 isLValueReference = true;
3624 } else if (const RValueReferenceType *FnTypeRef =
3625 FnType->getAsRValueReferenceType()) {
3626 FnType = FnTypeRef->getPointeeType();
3627 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003628 }
3629 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3630 FnType = FnTypePtr->getPointeeType();
3631 isPointer = true;
3632 }
3633 // Desugar down to a function type.
3634 FnType = QualType(FnType->getAsFunctionType(), 0);
3635 // Reconstruct the pointer/reference as appropriate.
3636 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003637 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3638 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003639
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003640 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003641 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003642 } else {
3643 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003644 // FIXME: Do we want the error message to point at the operator?
3645 // (built-ins won't have a location)
Douglas Gregor70d26122008-11-12 17:17:38 +00003646 QualType FnType
3647 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3648 Cand->BuiltinTypes.ParamTypes,
3649 Cand->Conversions.size(),
3650 false, 0);
3651
Chris Lattner4bfd2232008-11-24 06:25:27 +00003652 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003653 }
3654 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003655 }
3656}
3657
Douglas Gregor45014fd2008-11-10 20:40:00 +00003658/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3659/// an overloaded function (C++ [over.over]), where @p From is an
3660/// expression with overloaded function type and @p ToType is the type
3661/// we're trying to resolve to. For example:
3662///
3663/// @code
3664/// int f(double);
3665/// int f(int);
3666///
3667/// int (*pfd)(double) = f; // selects f(double)
3668/// @endcode
3669///
3670/// This routine returns the resulting FunctionDecl if it could be
3671/// resolved, and NULL otherwise. When @p Complain is true, this
3672/// routine will emit diagnostics if there is an error.
3673FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003674Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003675 bool Complain) {
3676 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003677 bool IsMember = false;
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003678 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003679 FunctionType = ToTypePtr->getPointeeType();
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003680 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3681 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003682 else if (const MemberPointerType *MemTypePtr =
3683 ToType->getAsMemberPointerType()) {
3684 FunctionType = MemTypePtr->getPointeeType();
3685 IsMember = true;
3686 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003687
3688 // We only look at pointers or references to functions.
3689 if (!FunctionType->isFunctionType())
3690 return 0;
3691
3692 // Find the actual overloaded function declaration.
3693 OverloadedFunctionDecl *Ovl = 0;
3694
3695 // C++ [over.over]p1:
3696 // [...] [Note: any redundant set of parentheses surrounding the
3697 // overloaded function name is ignored (5.1). ]
3698 Expr *OvlExpr = From->IgnoreParens();
3699
3700 // C++ [over.over]p1:
3701 // [...] The overloaded function name can be preceded by the &
3702 // operator.
3703 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3704 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3705 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3706 }
3707
3708 // Try to dig out the overloaded function.
3709 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3710 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3711
3712 // If there's no overloaded function declaration, we're done.
3713 if (!Ovl)
3714 return 0;
3715
3716 // Look through all of the overloaded functions, searching for one
3717 // whose type matches exactly.
3718 // FIXME: When templates or using declarations come along, we'll actually
3719 // have to deal with duplicates, partial ordering, etc. For now, we
3720 // can just do a simple search.
3721 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3722 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3723 Fun != Ovl->function_end(); ++Fun) {
3724 // C++ [over.over]p3:
3725 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003726 // targets of type "pointer-to-function" or "reference-to-function."
3727 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003728 // type "pointer-to-member-function."
3729 // Note that according to DR 247, the containing class does not matter.
3730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3731 // Skip non-static functions when converting to pointer, and static
3732 // when converting to member pointer.
3733 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003734 continue;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003735 } else if (IsMember)
3736 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003737
Douglas Gregorb60eb752009-06-25 22:08:12 +00003738 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
3739 if (FunctionType == Context.getCanonicalType(FunDecl->getType()))
3740 return FunDecl;
3741 } else {
3742 unsigned DiagID
3743 = PP.getDiagnostics().getCustomDiagID(Diagnostic::Warning,
3744 "Clang does not yet support templated conversion functions");
3745 Diag(From->getLocStart(), DiagID);
3746 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003747 }
3748
3749 return 0;
3750}
3751
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003752/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003753/// (which eventually refers to the declaration Func) and the call
3754/// arguments Args/NumArgs, attempt to resolve the function call down
3755/// to a specific function. If overload resolution succeeds, returns
3756/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003757/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003758/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003759FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003760 DeclarationName UnqualifiedName,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003761 SourceLocation LParenLoc,
3762 Expr **Args, unsigned NumArgs,
3763 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003764 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003765 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003766 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003767
3768 // Add the functions denoted by Callee to the set of candidate
3769 // functions. While we're doing so, track whether argument-dependent
3770 // lookup still applies, per:
3771 //
3772 // C++0x [basic.lookup.argdep]p3:
3773 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3774 // and let Y be the lookup set produced by argument dependent
3775 // lookup (defined as follows). If X contains
3776 //
3777 // -- a declaration of a class member, or
3778 //
3779 // -- a block-scope function declaration that is not a
3780 // using-declaration, or
3781 //
3782 // -- a declaration that is neither a function or a function
3783 // template
3784 //
3785 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003786 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003787 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3788 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3789 FuncEnd = Ovl->function_end();
3790 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00003791 DeclContext *Ctx = 0;
3792 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
3793 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
3794 Ctx = FunDecl->getDeclContext();
3795 } else {
3796 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
3797 AddTemplateOverloadCandidate(FunTmpl, Args, NumArgs, CandidateSet);
3798 Ctx = FunTmpl->getDeclContext();
3799 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003800
Douglas Gregorb60eb752009-06-25 22:08:12 +00003801
3802 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003803 ArgumentDependentLookup = false;
3804 }
3805 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3806 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3807
3808 if (Func->getDeclContext()->isRecord() ||
3809 Func->getDeclContext()->isFunctionOrMethod())
3810 ArgumentDependentLookup = false;
Douglas Gregorb60eb752009-06-25 22:08:12 +00003811 } else if (FunctionTemplateDecl *FuncTemplate
3812 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
3813 AddTemplateOverloadCandidate(FuncTemplate, Args, NumArgs, CandidateSet);
3814
3815 if (FuncTemplate->getDeclContext()->isRecord())
3816 ArgumentDependentLookup = false;
3817 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003818
3819 if (Callee)
3820 UnqualifiedName = Callee->getDeclName();
3821
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003822 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003823 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003824 CandidateSet);
3825
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003826 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00003827 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003828 case OR_Success:
3829 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003830
3831 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00003832 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003833 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00003834 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003835 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3836 break;
3837
3838 case OR_Ambiguous:
3839 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003840 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003841 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3842 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00003843
3844 case OR_Deleted:
3845 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3846 << Best->Function->isDeleted()
3847 << UnqualifiedName
3848 << Fn->getSourceRange();
3849 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3850 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003851 }
3852
3853 // Overload resolution failed. Destroy all of the subexpressions and
3854 // return NULL.
3855 Fn->Destroy(Context);
3856 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3857 Args[Arg]->Destroy(Context);
3858 return 0;
3859}
3860
Douglas Gregorc78182d2009-03-13 23:49:33 +00003861/// \brief Create a unary operation that may resolve to an overloaded
3862/// operator.
3863///
3864/// \param OpLoc The location of the operator itself (e.g., '*').
3865///
3866/// \param OpcIn The UnaryOperator::Opcode that describes this
3867/// operator.
3868///
3869/// \param Functions The set of non-member functions that will be
3870/// considered by overload resolution. The caller needs to build this
3871/// set based on the context using, e.g.,
3872/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3873/// set should not contain any member functions; those will be added
3874/// by CreateOverloadedUnaryOp().
3875///
3876/// \param input The input argument.
3877Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3878 unsigned OpcIn,
3879 FunctionSet &Functions,
3880 ExprArg input) {
3881 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3882 Expr *Input = (Expr *)input.get();
3883
3884 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3885 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3886 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3887
3888 Expr *Args[2] = { Input, 0 };
3889 unsigned NumArgs = 1;
3890
3891 // For post-increment and post-decrement, add the implicit '0' as
3892 // the second argument, so that we know this is a post-increment or
3893 // post-decrement.
3894 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3895 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3896 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3897 SourceLocation());
3898 NumArgs = 2;
3899 }
3900
3901 if (Input->isTypeDependent()) {
3902 OverloadedFunctionDecl *Overloads
3903 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3904 for (FunctionSet::iterator Func = Functions.begin(),
3905 FuncEnd = Functions.end();
3906 Func != FuncEnd; ++Func)
3907 Overloads->addOverload(*Func);
3908
3909 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3910 OpLoc, false, false);
3911
3912 input.release();
3913 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3914 &Args[0], NumArgs,
3915 Context.DependentTy,
3916 OpLoc));
3917 }
3918
3919 // Build an empty overload set.
3920 OverloadCandidateSet CandidateSet;
3921
3922 // Add the candidates from the given function set.
3923 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3924
3925 // Add operator candidates that are member functions.
3926 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3927
3928 // Add builtin operator candidates.
3929 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3930
3931 // Perform overload resolution.
3932 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00003933 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00003934 case OR_Success: {
3935 // We found a built-in operator or an overloaded operator.
3936 FunctionDecl *FnDecl = Best->Function;
3937
3938 if (FnDecl) {
3939 // We matched an overloaded operator. Build a call to that
3940 // operator.
3941
3942 // Convert the arguments.
3943 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3944 if (PerformObjectArgumentInitialization(Input, Method))
3945 return ExprError();
3946 } else {
3947 // Convert the arguments.
3948 if (PerformCopyInitialization(Input,
3949 FnDecl->getParamDecl(0)->getType(),
3950 "passing"))
3951 return ExprError();
3952 }
3953
3954 // Determine the result type
3955 QualType ResultTy
3956 = FnDecl->getType()->getAsFunctionType()->getResultType();
3957 ResultTy = ResultTy.getNonReferenceType();
3958
3959 // Build the actual expression node.
3960 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3961 SourceLocation());
3962 UsualUnaryConversions(FnExpr);
3963
3964 input.release();
3965 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3966 &Input, 1, ResultTy,
3967 OpLoc));
3968 } else {
3969 // We matched a built-in operator. Convert the arguments, then
3970 // break out so that we will build the appropriate built-in
3971 // operator node.
3972 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3973 Best->Conversions[0], "passing"))
3974 return ExprError();
3975
3976 break;
3977 }
3978 }
3979
3980 case OR_No_Viable_Function:
3981 // No viable function; fall through to handling this as a
3982 // built-in operator, which will produce an error message for us.
3983 break;
3984
3985 case OR_Ambiguous:
3986 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3987 << UnaryOperator::getOpcodeStr(Opc)
3988 << Input->getSourceRange();
3989 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3990 return ExprError();
3991
3992 case OR_Deleted:
3993 Diag(OpLoc, diag::err_ovl_deleted_oper)
3994 << Best->Function->isDeleted()
3995 << UnaryOperator::getOpcodeStr(Opc)
3996 << Input->getSourceRange();
3997 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3998 return ExprError();
3999 }
4000
4001 // Either we found no viable overloaded operator or we matched a
4002 // built-in operator. In either case, fall through to trying to
4003 // build a built-in operation.
4004 input.release();
4005 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4006}
4007
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004008/// \brief Create a binary operation that may resolve to an overloaded
4009/// operator.
4010///
4011/// \param OpLoc The location of the operator itself (e.g., '+').
4012///
4013/// \param OpcIn The BinaryOperator::Opcode that describes this
4014/// operator.
4015///
4016/// \param Functions The set of non-member functions that will be
4017/// considered by overload resolution. The caller needs to build this
4018/// set based on the context using, e.g.,
4019/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4020/// set should not contain any member functions; those will be added
4021/// by CreateOverloadedBinOp().
4022///
4023/// \param LHS Left-hand argument.
4024/// \param RHS Right-hand argument.
4025Sema::OwningExprResult
4026Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4027 unsigned OpcIn,
4028 FunctionSet &Functions,
4029 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004030 Expr *Args[2] = { LHS, RHS };
4031
4032 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4033 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4034 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4035
4036 // If either side is type-dependent, create an appropriate dependent
4037 // expression.
4038 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
4039 // .* cannot be overloaded.
4040 if (Opc == BinaryOperator::PtrMemD)
4041 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
4042 Context.DependentTy, OpLoc));
4043
4044 OverloadedFunctionDecl *Overloads
4045 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4046 for (FunctionSet::iterator Func = Functions.begin(),
4047 FuncEnd = Functions.end();
4048 Func != FuncEnd; ++Func)
4049 Overloads->addOverload(*Func);
4050
4051 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4052 OpLoc, false, false);
4053
4054 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4055 Args, 2,
4056 Context.DependentTy,
4057 OpLoc));
4058 }
4059
4060 // If this is the .* operator, which is not overloadable, just
4061 // create a built-in binary operator.
4062 if (Opc == BinaryOperator::PtrMemD)
4063 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4064
4065 // If this is one of the assignment operators, we only perform
4066 // overload resolution if the left-hand side is a class or
4067 // enumeration type (C++ [expr.ass]p3).
4068 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4069 !LHS->getType()->isOverloadableType())
4070 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4071
Douglas Gregorc78182d2009-03-13 23:49:33 +00004072 // Build an empty overload set.
4073 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004074
4075 // Add the candidates from the given function set.
4076 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4077
4078 // Add operator candidates that are member functions.
4079 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4080
4081 // Add builtin operator candidates.
4082 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4083
4084 // Perform overload resolution.
4085 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004086 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004087 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004088 // We found a built-in operator or an overloaded operator.
4089 FunctionDecl *FnDecl = Best->Function;
4090
4091 if (FnDecl) {
4092 // We matched an overloaded operator. Build a call to that
4093 // operator.
4094
4095 // Convert the arguments.
4096 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4097 if (PerformObjectArgumentInitialization(LHS, Method) ||
4098 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
4099 "passing"))
4100 return ExprError();
4101 } else {
4102 // Convert the arguments.
4103 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
4104 "passing") ||
4105 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
4106 "passing"))
4107 return ExprError();
4108 }
4109
4110 // Determine the result type
4111 QualType ResultTy
4112 = FnDecl->getType()->getAsFunctionType()->getResultType();
4113 ResultTy = ResultTy.getNonReferenceType();
4114
4115 // Build the actual expression node.
4116 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4117 SourceLocation());
4118 UsualUnaryConversions(FnExpr);
4119
4120 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4121 Args, 2, ResultTy,
4122 OpLoc));
4123 } else {
4124 // We matched a built-in operator. Convert the arguments, then
4125 // break out so that we will build the appropriate built-in
4126 // operator node.
4127 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4128 Best->Conversions[0], "passing") ||
4129 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4130 Best->Conversions[1], "passing"))
4131 return ExprError();
4132
4133 break;
4134 }
4135 }
4136
4137 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004138 // For class as left operand for assignment or compound assigment operator
4139 // do not fall through to handling in built-in, but report that no overloaded
4140 // assignment operator found
4141 if (LHS->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4142 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4143 << BinaryOperator::getOpcodeStr(Opc)
4144 << LHS->getSourceRange() << RHS->getSourceRange();
4145 return ExprError();
4146 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004147 // No viable function; fall through to handling this as a
4148 // built-in operator, which will produce an error message for us.
4149 break;
4150
4151 case OR_Ambiguous:
4152 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4153 << BinaryOperator::getOpcodeStr(Opc)
4154 << LHS->getSourceRange() << RHS->getSourceRange();
4155 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4156 return ExprError();
4157
4158 case OR_Deleted:
4159 Diag(OpLoc, diag::err_ovl_deleted_oper)
4160 << Best->Function->isDeleted()
4161 << BinaryOperator::getOpcodeStr(Opc)
4162 << LHS->getSourceRange() << RHS->getSourceRange();
4163 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4164 return ExprError();
4165 }
4166
4167 // Either we found no viable overloaded operator or we matched a
4168 // built-in operator. In either case, try to build a built-in
4169 // operation.
4170 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4171}
4172
Douglas Gregor3257fb52008-12-22 05:46:06 +00004173/// BuildCallToMemberFunction - Build a call to a member
4174/// function. MemExpr is the expression that refers to the member
4175/// function (and includes the object parameter), Args/NumArgs are the
4176/// arguments to the function call (not including the object
4177/// parameter). The caller needs to validate that the member
4178/// expression refers to a member function or an overloaded member
4179/// function.
4180Sema::ExprResult
4181Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4182 SourceLocation LParenLoc, Expr **Args,
4183 unsigned NumArgs, SourceLocation *CommaLocs,
4184 SourceLocation RParenLoc) {
4185 // Dig out the member expression. This holds both the object
4186 // argument and the member function we're referring to.
4187 MemberExpr *MemExpr = 0;
4188 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4189 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4190 else
4191 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4192 assert(MemExpr && "Building member call without member expression");
4193
4194 // Extract the object argument.
4195 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004196
Douglas Gregor3257fb52008-12-22 05:46:06 +00004197 CXXMethodDecl *Method = 0;
4198 if (OverloadedFunctionDecl *Ovl
4199 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
4200 // Add overload candidates
4201 OverloadCandidateSet CandidateSet;
4202 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4203 FuncEnd = Ovl->function_end();
4204 Func != FuncEnd; ++Func) {
4205 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
4206 Method = cast<CXXMethodDecl>(*Func);
4207 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4208 /*SuppressUserConversions=*/false);
4209 }
4210
4211 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004212 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004213 case OR_Success:
4214 Method = cast<CXXMethodDecl>(Best->Function);
4215 break;
4216
4217 case OR_No_Viable_Function:
4218 Diag(MemExpr->getSourceRange().getBegin(),
4219 diag::err_ovl_no_viable_member_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004220 << Ovl->getDeclName() << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004221 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4222 // FIXME: Leaking incoming expressions!
4223 return true;
4224
4225 case OR_Ambiguous:
4226 Diag(MemExpr->getSourceRange().getBegin(),
4227 diag::err_ovl_ambiguous_member_call)
4228 << Ovl->getDeclName() << MemExprE->getSourceRange();
4229 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4230 // FIXME: Leaking incoming expressions!
4231 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004232
4233 case OR_Deleted:
4234 Diag(MemExpr->getSourceRange().getBegin(),
4235 diag::err_ovl_deleted_member_call)
4236 << Best->Function->isDeleted()
4237 << Ovl->getDeclName() << MemExprE->getSourceRange();
4238 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4239 // FIXME: Leaking incoming expressions!
4240 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004241 }
4242
4243 FixOverloadedFunctionReference(MemExpr, Method);
4244 } else {
4245 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4246 }
4247
4248 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004249 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004250 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4251 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004252 Method->getResultType().getNonReferenceType(),
4253 RParenLoc));
4254
4255 // Convert the object argument (for a non-static member function call).
4256 if (!Method->isStatic() &&
4257 PerformObjectArgumentInitialization(ObjectArg, Method))
4258 return true;
4259 MemExpr->setBase(ObjectArg);
4260
4261 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004262 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004263 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4264 RParenLoc))
4265 return true;
4266
Sebastian Redl8b769972009-01-19 00:08:26 +00004267 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004268}
4269
Douglas Gregor10f3c502008-11-19 21:05:33 +00004270/// BuildCallToObjectOfClassType - Build a call to an object of class
4271/// type (C++ [over.call.object]), which can end up invoking an
4272/// overloaded function call operator (@c operator()) or performing a
4273/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004274Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004275Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4276 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004277 Expr **Args, unsigned NumArgs,
4278 SourceLocation *CommaLocs,
4279 SourceLocation RParenLoc) {
4280 assert(Object->getType()->isRecordType() && "Requires object type argument");
4281 const RecordType *Record = Object->getType()->getAsRecordType();
4282
4283 // C++ [over.call.object]p1:
4284 // If the primary-expression E in the function call syntax
4285 // evaluates to a class object of type “cv T”, then the set of
4286 // candidate functions includes at least the function call
4287 // operators of T. The function call operators of T are obtained by
4288 // ordinary lookup of the name operator() in the context of
4289 // (E).operator().
4290 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004291 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004292 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004293 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004294 Oper != OperEnd; ++Oper)
4295 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4296 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004297
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004298 // C++ [over.call.object]p2:
4299 // In addition, for each conversion function declared in T of the
4300 // form
4301 //
4302 // operator conversion-type-id () cv-qualifier;
4303 //
4304 // where cv-qualifier is the same cv-qualification as, or a
4305 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004306 // denotes the type "pointer to function of (P1,...,Pn) returning
4307 // R", or the type "reference to pointer to function of
4308 // (P1,...,Pn) returning R", or the type "reference to function
4309 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004310 // is also considered as a candidate function. Similarly,
4311 // surrogate call functions are added to the set of candidate
4312 // functions for each conversion function declared in an
4313 // accessible base class provided the function is not hidden
4314 // within T by another intervening declaration.
4315 //
4316 // FIXME: Look in base classes for more conversion operators!
4317 OverloadedFunctionDecl *Conversions
4318 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004319 for (OverloadedFunctionDecl::function_iterator
4320 Func = Conversions->function_begin(),
4321 FuncEnd = Conversions->function_end();
4322 Func != FuncEnd; ++Func) {
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004323 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4324
4325 // Strip the reference type (if any) and then the pointer type (if
4326 // any) to get down to what might be a function type.
4327 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4328 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4329 ConvType = ConvPtrType->getPointeeType();
4330
Douglas Gregor4fa58902009-02-26 23:50:07 +00004331 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004332 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4333 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004334
4335 // Perform overload resolution.
4336 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004337 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004338 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004339 // Overload resolution succeeded; we'll build the appropriate call
4340 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004341 break;
4342
4343 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004344 Diag(Object->getSourceRange().getBegin(),
4345 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004346 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004347 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004348 break;
4349
4350 case OR_Ambiguous:
4351 Diag(Object->getSourceRange().getBegin(),
4352 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004353 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004354 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4355 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004356
4357 case OR_Deleted:
4358 Diag(Object->getSourceRange().getBegin(),
4359 diag::err_ovl_deleted_object_call)
4360 << Best->Function->isDeleted()
4361 << Object->getType() << Object->getSourceRange();
4362 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4363 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004364 }
4365
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004366 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004367 // We had an error; delete all of the subexpressions and return
4368 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004369 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004370 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004371 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004372 return true;
4373 }
4374
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004375 if (Best->Function == 0) {
4376 // Since there is no function declaration, this is one of the
4377 // surrogate candidates. Dig out the conversion function.
4378 CXXConversionDecl *Conv
4379 = cast<CXXConversionDecl>(
4380 Best->Conversions[0].UserDefined.ConversionFunction);
4381
4382 // We selected one of the surrogate functions that converts the
4383 // object parameter to a function pointer. Perform the conversion
4384 // on the object argument, then let ActOnCallExpr finish the job.
4385 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004386 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004387 Conv->getConversionType().getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +00004388 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004389 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4390 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4391 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004392 }
4393
4394 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4395 // that calls this method, using Object for the implicit object
4396 // parameter and passing along the remaining arguments.
4397 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004398 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004399
4400 unsigned NumArgsInProto = Proto->getNumArgs();
4401 unsigned NumArgsToCheck = NumArgs;
4402
4403 // Build the full argument list for the method call (the
4404 // implicit object parameter is placed at the beginning of the
4405 // list).
4406 Expr **MethodArgs;
4407 if (NumArgs < NumArgsInProto) {
4408 NumArgsToCheck = NumArgsInProto;
4409 MethodArgs = new Expr*[NumArgsInProto + 1];
4410 } else {
4411 MethodArgs = new Expr*[NumArgs + 1];
4412 }
4413 MethodArgs[0] = Object;
4414 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4415 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4416
Ted Kremenek0c97e042009-02-07 01:47:29 +00004417 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4418 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004419 UsualUnaryConversions(NewFn);
4420
4421 // Once we've built TheCall, all of the expressions are properly
4422 // owned.
4423 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004424 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004425 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4426 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004427 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004428 delete [] MethodArgs;
4429
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004430 // We may have default arguments. If so, we need to allocate more
4431 // slots in the call for them.
4432 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004433 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004434 else if (NumArgs > NumArgsInProto)
4435 NumArgsToCheck = NumArgsInProto;
4436
Chris Lattner81f00ed2009-04-12 08:11:20 +00004437 bool IsError = false;
4438
Douglas Gregor10f3c502008-11-19 21:05:33 +00004439 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004440 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004441 TheCall->setArg(0, Object);
4442
Chris Lattner81f00ed2009-04-12 08:11:20 +00004443
Douglas Gregor10f3c502008-11-19 21:05:33 +00004444 // Check the argument types.
4445 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004446 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004447 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004448 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004449
4450 // Pass the argument.
4451 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004452 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004453 } else {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004454 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004455 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004456
4457 TheCall->setArg(i + 1, Arg);
4458 }
4459
4460 // If this is a variadic call, handle args passed through "...".
4461 if (Proto->isVariadic()) {
4462 // Promote the arguments (C99 6.5.2.2p7).
4463 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4464 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004465 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004466 TheCall->setArg(i + 1, Arg);
4467 }
4468 }
4469
Chris Lattner81f00ed2009-04-12 08:11:20 +00004470 if (IsError) return true;
4471
Sebastian Redl8b769972009-01-19 00:08:26 +00004472 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004473}
4474
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004475/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4476/// (if one exists), where @c Base is an expression of class type and
4477/// @c Member is the name of the member we're trying to find.
4478Action::ExprResult
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004479Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004480 SourceLocation MemberLoc,
4481 IdentifierInfo &Member) {
4482 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4483
4484 // C++ [over.ref]p1:
4485 //
4486 // [...] An expression x->m is interpreted as (x.operator->())->m
4487 // for a class object x of type T if T::operator->() exists and if
4488 // the operator is selected as the best match function by the
4489 // overload resolution mechanism (13.3).
4490 // FIXME: look in base classes.
4491 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4492 OverloadCandidateSet CandidateSet;
4493 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004494
4495 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004496 for (llvm::tie(Oper, OperEnd)
4497 = BaseRecord->getDecl()->lookup(Context, OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004498 Oper != OperEnd; ++Oper)
4499 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004500 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004501
Ted Kremenek0c97e042009-02-07 01:47:29 +00004502 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004503
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004504 // Perform overload resolution.
4505 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004506 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004507 case OR_Success:
4508 // Overload resolution succeeded; we'll build the call below.
4509 break;
4510
4511 case OR_No_Viable_Function:
4512 if (CandidateSet.empty())
4513 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004514 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004515 else
4516 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Chris Lattner4a526112009-02-17 07:29:20 +00004517 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004518 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004519 return true;
4520
4521 case OR_Ambiguous:
4522 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004523 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004524 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004525 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004526
4527 case OR_Deleted:
4528 Diag(OpLoc, diag::err_ovl_deleted_oper)
4529 << Best->Function->isDeleted()
4530 << "operator->" << BasePtr->getSourceRange();
4531 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4532 return true;
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004533 }
4534
4535 // Convert the object parameter.
4536 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004537 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004538 return true;
Douglas Gregor9c690e92008-11-21 03:04:22 +00004539
4540 // No concerns about early exits now.
4541 BasePtr.take();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004542
4543 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004544 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4545 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004546 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004547 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004548 Method->getResultType().getNonReferenceType(),
4549 OpLoc);
Sebastian Redl8b769972009-01-19 00:08:26 +00004550 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
Chris Lattner5261d0c2009-03-28 19:18:32 +00004551 MemberLoc, Member, DeclPtrTy()).release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004552}
4553
Douglas Gregor45014fd2008-11-10 20:40:00 +00004554/// FixOverloadedFunctionReference - E is an expression that refers to
4555/// a C++ overloaded function (possibly with some parentheses and
4556/// perhaps a '&' around it). We have resolved the overloaded function
4557/// to the function declaration Fn, so patch up the expression E to
4558/// refer (possibly indirectly) to Fn.
4559void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4560 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4561 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4562 E->setType(PE->getSubExpr()->getType());
4563 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4564 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4565 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004566 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4567 if (Method->isStatic()) {
4568 // Do nothing: static member functions aren't any different
4569 // from non-member functions.
4570 }
4571 else if (QualifiedDeclRefExpr *DRE
4572 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4573 // We have taken the address of a pointer to member
4574 // function. Perform the computation here so that we get the
4575 // appropriate pointer to member type.
4576 DRE->setDecl(Fn);
4577 DRE->setType(Fn->getType());
4578 QualType ClassType
4579 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4580 E->setType(Context.getMemberPointerType(Fn->getType(),
4581 ClassType.getTypePtr()));
4582 return;
4583 }
4584 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004585 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004586 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004587 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4588 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4589 "Expected overloaded function");
4590 DR->setDecl(Fn);
4591 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004592 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4593 MemExpr->setMemberDecl(Fn);
4594 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004595 } else {
4596 assert(false && "Invalid reference to overloaded function");
4597 }
4598}
4599
Douglas Gregord2baafd2008-10-21 16:13:35 +00004600} // end namespace clang