blob: 25af89fd4543e1ffa4594597a79bc03eb54ffae1 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor94b1dd22008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000026#include <cstdio>
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000027
28namespace clang {
29
30/// GetConversionCategory - Retrieve the implicit conversion
31/// category corresponding to the given implicit conversion kind.
32ImplicitConversionCategory
33GetConversionCategory(ImplicitConversionKind Kind) {
34 static const ImplicitConversionCategory
35 Category[(int)ICK_Num_Conversion_Kinds] = {
36 ICC_Identity,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Qualification_Adjustment,
41 ICC_Promotion,
42 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000043 ICC_Promotion,
44 ICC_Conversion,
45 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000046 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000051 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000052 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000053 ICC_Conversion
54 };
55 return Category[(int)Kind];
56}
57
58/// GetConversionRank - Retrieve the implicit conversion rank
59/// corresponding to the given implicit conversion kind.
60ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
61 static const ImplicitConversionRank
62 Rank[(int)ICK_Num_Conversion_Kinds] = {
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Promotion,
69 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000070 ICR_Promotion,
71 ICR_Conversion,
72 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000073 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000078 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000079 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000080 ICR_Conversion
81 };
82 return Rank[(int)Kind];
83}
84
85/// GetImplicitConversionName - Return the name of this kind of
86/// implicit conversion.
87const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
88 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
89 "No conversion",
90 "Lvalue-to-rvalue",
91 "Array-to-pointer",
92 "Function-to-pointer",
93 "Qualification",
94 "Integral promotion",
95 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000096 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000097 "Integral conversion",
98 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000099 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000101 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000102 "Pointer conversion",
103 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000104 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000105 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000106 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000107 };
108 return Name[Kind];
109}
110
Douglas Gregor60d62c22008-10-31 16:23:19 +0000111/// StandardConversionSequence - Set the standard conversion
112/// sequence to the identity conversion.
113void StandardConversionSequence::setAsIdentityConversion() {
114 First = ICK_Identity;
115 Second = ICK_Identity;
116 Third = ICK_Identity;
117 Deprecated = false;
118 ReferenceBinding = false;
119 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000120 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000121 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000122}
123
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000124/// getRank - Retrieve the rank of this standard conversion sequence
125/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
126/// implicit conversions.
127ImplicitConversionRank StandardConversionSequence::getRank() const {
128 ImplicitConversionRank Rank = ICR_Exact_Match;
129 if (GetConversionRank(First) > Rank)
130 Rank = GetConversionRank(First);
131 if (GetConversionRank(Second) > Rank)
132 Rank = GetConversionRank(Second);
133 if (GetConversionRank(Third) > Rank)
134 Rank = GetConversionRank(Third);
135 return Rank;
136}
137
138/// isPointerConversionToBool - Determines whether this conversion is
139/// a conversion of a pointer or pointer-to-member to bool. This is
140/// used as part of the ranking of standard conversion sequences
141/// (C++ 13.3.3.2p4).
142bool StandardConversionSequence::isPointerConversionToBool() const
143{
144 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
146
147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
151 if (ToType->isBooleanType() &&
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
163bool
164StandardConversionSequence::
165isPointerConversionToVoidPointer(ASTContext& Context) const
166{
167 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
168 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
169
170 // Note that FromType has not necessarily been transformed by the
171 // array-to-pointer implicit conversion, so check for its presence
172 // and redo the conversion to get a pointer.
173 if (First == ICK_Array_To_Pointer)
174 FromType = Context.getArrayDecayedType(FromType);
175
176 if (Second == ICK_Pointer_Conversion)
Ted Kremenek6217b802009-07-29 21:53:49 +0000177 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000178 return ToPtrType->getPointeeType()->isVoidType();
179
180 return false;
181}
182
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183/// DebugPrint - Print this standard conversion sequence to standard
184/// error. Useful for debugging overloading issues.
185void StandardConversionSequence::DebugPrint() const {
186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
188 fprintf(stderr, "%s", GetImplicitConversionName(First));
189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
194 fprintf(stderr, " -> ");
195 }
196 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
199 fprintf(stderr, " (by copy constructor)");
200 } else if (DirectBinding) {
201 fprintf(stderr, " (direct reference binding)");
202 } else if (ReferenceBinding) {
203 fprintf(stderr, " (reference binding)");
204 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
210 fprintf(stderr, " -> ");
211 }
212 fprintf(stderr, "%s", GetImplicitConversionName(Third));
213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
217 fprintf(stderr, "No conversions required");
218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
224 if (Before.First || Before.Second || Before.Third) {
225 Before.DebugPrint();
226 fprintf(stderr, " -> ");
227 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000228 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000229 if (After.First || After.Second || After.Third) {
230 fprintf(stderr, " -> ");
231 After.DebugPrint();
232 }
233}
234
235/// DebugPrint - Print this implicit conversion sequence to standard
236/// error. Useful for debugging overloading issues.
237void ImplicitConversionSequence::DebugPrint() const {
238 switch (ConversionKind) {
239 case StandardConversion:
240 fprintf(stderr, "Standard conversion: ");
241 Standard.DebugPrint();
242 break;
243 case UserDefinedConversion:
244 fprintf(stderr, "User-defined conversion: ");
245 UserDefined.DebugPrint();
246 break;
247 case EllipsisConversion:
248 fprintf(stderr, "Ellipsis conversion");
249 break;
250 case BadConversion:
251 fprintf(stderr, "Bad conversion");
252 break;
253 }
254
255 fprintf(stderr, "\n");
256}
257
258// IsOverload - Determine whether the given New declaration is an
259// overload of the Old declaration. This routine returns false if New
260// and Old cannot be overloaded, e.g., if they are functions with the
261// same signature (C++ 1.3.10) or if the Old declaration isn't a
262// function (or overload set). When it does return false and Old is an
263// OverloadedFunctionDecl, MatchedDecl will be set to point to the
264// FunctionDecl that New cannot be overloaded with.
265//
266// Example: Given the following input:
267//
268// void f(int, float); // #1
269// void f(int, int); // #2
270// int f(int, int); // #3
271//
272// When we process #1, there is no previous declaration of "f",
273// so IsOverload will not be used.
274//
275// When we process #2, Old is a FunctionDecl for #1. By comparing the
276// parameter types, we see that #1 and #2 are overloaded (since they
277// have different signatures), so this routine returns false;
278// MatchedDecl is unchanged.
279//
280// When we process #3, Old is an OverloadedFunctionDecl containing #1
281// and #2. We compare the signatures of #3 to #1 (they're overloaded,
282// so we do nothing) and then #3 to #2. Since the signatures of #3 and
283// #2 are identical (return types of functions are not part of the
284// signature), IsOverload returns false and MatchedDecl will be set to
285// point to the FunctionDecl for #2.
286bool
287Sema::IsOverload(FunctionDecl *New, Decl* OldD,
288 OverloadedFunctionDecl::function_iterator& MatchedDecl)
289{
290 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
291 // Is this new function an overload of every function in the
292 // overload set?
293 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
294 FuncEnd = Ovl->function_end();
295 for (; Func != FuncEnd; ++Func) {
296 if (!IsOverload(New, *Func, MatchedDecl)) {
297 MatchedDecl = Func;
298 return false;
299 }
300 }
301
302 // This function overloads every function in the overload set.
303 return true;
Douglas Gregore53060f2009-06-25 22:08:12 +0000304 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
305 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
306 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000307 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
308 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
309
310 // C++ [temp.fct]p2:
311 // A function template can be overloaded with other function templates
312 // and with normal (non-template) functions.
313 if ((OldTemplate == 0) != (NewTemplate == 0))
314 return true;
315
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000316 // Is the function New an overload of the function Old?
317 QualType OldQType = Context.getCanonicalType(Old->getType());
318 QualType NewQType = Context.getCanonicalType(New->getType());
319
320 // Compare the signatures (C++ 1.3.10) of the two functions to
321 // determine whether they are overloads. If we find any mismatch
322 // in the signature, they are overloads.
323
324 // If either of these functions is a K&R-style function (no
325 // prototype), then we consider them to have matching signatures.
Douglas Gregor72564e72009-02-26 23:50:07 +0000326 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
327 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000328 return false;
329
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000330 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
331 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000332
333 // The signature of a function includes the types of its
334 // parameters (C++ 1.3.10), which includes the presence or absence
335 // of the ellipsis; see C++ DR 357).
336 if (OldQType != NewQType &&
337 (OldType->getNumArgs() != NewType->getNumArgs() ||
338 OldType->isVariadic() != NewType->isVariadic() ||
339 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
340 NewType->arg_type_begin())))
341 return true;
342
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000343 // C++ [temp.over.link]p4:
344 // The signature of a function template consists of its function
345 // signature, its return type and its template parameter list. The names
346 // of the template parameters are significant only for establishing the
347 // relationship between the template parameters and the rest of the
348 // signature.
349 //
350 // We check the return type and template parameter lists for function
351 // templates first; the remaining checks follow.
352 if (NewTemplate &&
353 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
354 OldTemplate->getTemplateParameters(),
355 false, false, SourceLocation()) ||
356 OldType->getResultType() != NewType->getResultType()))
357 return true;
358
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000359 // If the function is a class member, its signature includes the
360 // cv-qualifiers (if any) on the function itself.
361 //
362 // As part of this, also check whether one of the member functions
363 // is static, in which case they are not overloads (C++
364 // 13.1p2). While not part of the definition of the signature,
365 // this check is important to determine whether these functions
366 // can be overloaded.
367 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
368 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
369 if (OldMethod && NewMethod &&
370 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000371 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000372 return true;
373
374 // The signatures match; this is not an overload.
375 return false;
376 } else {
377 // (C++ 13p1):
378 // Only function declarations can be overloaded; object and type
379 // declarations cannot be overloaded.
380 return false;
381 }
382}
383
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000384/// TryImplicitConversion - Attempt to perform an implicit conversion
385/// from the given expression (Expr) to the given type (ToType). This
386/// function returns an implicit conversion sequence that can be used
387/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000388///
389/// void f(float f);
390/// void g(int i) { f(i); }
391///
392/// this routine would produce an implicit conversion sequence to
393/// describe the initialization of f from i, which will be a standard
394/// conversion sequence containing an lvalue-to-rvalue conversion (C++
395/// 4.1) followed by a floating-integral conversion (C++ 4.9).
396//
397/// Note that this routine only determines how the conversion can be
398/// performed; it does not actually perform the conversion. As such,
399/// it will not produce any diagnostics if no conversion is available,
400/// but will instead return an implicit conversion sequence of kind
401/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000402///
403/// If @p SuppressUserConversions, then user-defined conversions are
404/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000405/// If @p AllowExplicit, then explicit user-defined conversions are
406/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000407/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
408/// no matter its actual lvalueness.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000409ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000410Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000411 bool SuppressUserConversions,
Sebastian Redle2b68332009-04-12 17:16:29 +0000412 bool AllowExplicit, bool ForceRValue)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000413{
414 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000415 if (IsStandardConversion(From, ToType, ICS.Standard))
416 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000417 else if (getLangOptions().CPlusPlus &&
418 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redle2b68332009-04-12 17:16:29 +0000419 !SuppressUserConversions, AllowExplicit,
420 ForceRValue)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000421 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000422 // C++ [over.ics.user]p4:
423 // A conversion of an expression of class type to the same class
424 // type is given Exact Match rank, and a conversion of an
425 // expression of class type to a base class of that type is
426 // given Conversion rank, in spite of the fact that a copy
427 // constructor (i.e., a user-defined conversion function) is
428 // called for those cases.
429 if (CXXConstructorDecl *Constructor
430 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000431 QualType FromCanon
432 = Context.getCanonicalType(From->getType().getUnqualifiedType());
433 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
434 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000435 // Turn this into a "standard" conversion sequence, so that it
436 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000437 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
438 ICS.Standard.setAsIdentityConversion();
439 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
440 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000441 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000442 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000443 ICS.Standard.Second = ICK_Derived_To_Base;
444 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000445 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000446
447 // C++ [over.best.ics]p4:
448 // However, when considering the argument of a user-defined
449 // conversion function that is a candidate by 13.3.1.3 when
450 // invoked for the copying of the temporary in the second step
451 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
452 // 13.3.1.6 in all cases, only standard conversion sequences and
453 // ellipsis conversion sequences are allowed.
454 if (SuppressUserConversions &&
455 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
456 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000457 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000458 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000459
460 return ICS;
461}
462
463/// IsStandardConversion - Determines whether there is a standard
464/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
465/// expression From to the type ToType. Standard conversion sequences
466/// only consider non-class types; for conversions that involve class
467/// types, use TryImplicitConversion. If a conversion exists, SCS will
468/// contain the standard conversion sequence required to perform this
469/// conversion and this routine will return true. Otherwise, this
470/// routine will return false and the value of SCS is unspecified.
471bool
472Sema::IsStandardConversion(Expr* From, QualType ToType,
473 StandardConversionSequence &SCS)
474{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000475 QualType FromType = From->getType();
476
Douglas Gregor60d62c22008-10-31 16:23:19 +0000477 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000478 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000479 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000480 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000481 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000482 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483
Douglas Gregorf9201e02009-02-11 23:02:49 +0000484 // There are no standard conversions for class types in C++, so
485 // abort early. When overloading in C, however, we do permit
486 if (FromType->isRecordType() || ToType->isRecordType()) {
487 if (getLangOptions().CPlusPlus)
488 return false;
489
490 // When we're overloading in C, we allow, as standard conversions,
491 }
492
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000493 // The first conversion can be an lvalue-to-rvalue conversion,
494 // array-to-pointer conversion, or function-to-pointer conversion
495 // (C++ 4p1).
496
497 // Lvalue-to-rvalue conversion (C++ 4.1):
498 // An lvalue (3.10) of a non-function, non-array type T can be
499 // converted to an rvalue.
500 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
501 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000502 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000503 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000504 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505
506 // If T is a non-class type, the type of the rvalue is the
507 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000508 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
509 // just strip the qualifiers because they don't matter.
510
511 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor60d62c22008-10-31 16:23:19 +0000512 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000513 } else if (FromType->isArrayType()) {
514 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000515 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516
517 // An lvalue or rvalue of type "array of N T" or "array of unknown
518 // bound of T" can be converted to an rvalue of type "pointer to
519 // T" (C++ 4.2p1).
520 FromType = Context.getArrayDecayedType(FromType);
521
522 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
523 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000524 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000525
526 // For the purpose of ranking in overload resolution
527 // (13.3.3.1.1), this conversion is considered an
528 // array-to-pointer conversion followed by a qualification
529 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000530 SCS.Second = ICK_Identity;
531 SCS.Third = ICK_Qualification;
532 SCS.ToTypePtr = ToType.getAsOpaquePtr();
533 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000535 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
536 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000537 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000538
539 // An lvalue of function type T can be converted to an rvalue of
540 // type "pointer to T." The result is a pointer to the
541 // function. (C++ 4.3p1).
542 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000543 } else if (FunctionDecl *Fn
Douglas Gregor904eed32008-11-10 20:40:00 +0000544 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000545 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000546 SCS.First = ICK_Function_To_Pointer;
547
548 // We were able to resolve the address of the overloaded function,
549 // so we can convert to the type of that function.
550 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000551 if (ToType->isLValueReferenceType())
552 FromType = Context.getLValueReferenceType(FromType);
553 else if (ToType->isRValueReferenceType())
554 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000555 else if (ToType->isMemberPointerType()) {
556 // Resolve address only succeeds if both sides are member pointers,
557 // but it doesn't have to be the same class. See DR 247.
558 // Note that this means that the type of &Derived::fn can be
559 // Ret (Base::*)(Args) if the fn overload actually found is from the
560 // base class, even if it was brought into the derived class via a
561 // using declaration. The standard isn't clear on this issue at all.
562 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
563 FromType = Context.getMemberPointerType(FromType,
564 Context.getTypeDeclType(M->getParent()).getTypePtr());
565 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000566 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000567 } else {
568 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000569 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000570 }
571
572 // The second conversion can be an integral promotion, floating
573 // point promotion, integral conversion, floating point conversion,
574 // floating-integral conversion, pointer conversion,
575 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000576 // For overloading in C, this can also be a "compatible-type"
577 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000578 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000579 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000580 // The unqualified versions of the types are the same: there's no
581 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000582 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000583 } else if (IsIntegralPromotion(From, FromType, ToType)) {
584 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000585 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000586 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000587 } else if (IsFloatingPointPromotion(FromType, ToType)) {
588 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000589 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000590 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000591 } else if (IsComplexPromotion(FromType, ToType)) {
592 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000593 SCS.Second = ICK_Complex_Promotion;
594 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000595 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000596 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000597 // Integral conversions (C++ 4.7).
598 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000599 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000600 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000601 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
602 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000603 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000605 } else if (FromType->isComplexType() && ToType->isComplexType()) {
606 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000607 SCS.Second = ICK_Complex_Conversion;
608 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000609 } else if ((FromType->isFloatingType() &&
610 ToType->isIntegralType() && (!ToType->isBooleanType() &&
611 !ToType->isEnumeralType())) ||
612 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
613 ToType->isFloatingType())) {
614 // Floating-integral conversions (C++ 4.9).
615 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000616 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000617 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000618 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
619 (ToType->isComplexType() && FromType->isArithmeticType())) {
620 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000621 SCS.Second = ICK_Complex_Real;
622 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000623 } else if (IsPointerConversion(From, FromType, ToType, FromType,
624 IncompatibleObjC)) {
625 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000626 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000627 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000628 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
629 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000630 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000631 } else if (ToType->isBooleanType() &&
632 (FromType->isArithmeticType() ||
633 FromType->isEnumeralType() ||
634 FromType->isPointerType() ||
635 FromType->isBlockPointerType() ||
636 FromType->isMemberPointerType() ||
637 FromType->isNullPtrType())) {
638 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000639 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000640 FromType = Context.BoolTy;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000641 } else if (!getLangOptions().CPlusPlus &&
642 Context.typesAreCompatible(ToType, FromType)) {
643 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000644 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000645 } else {
646 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000647 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000648 }
649
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000650 QualType CanonFrom;
651 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000652 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000653 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000654 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000655 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000656 CanonFrom = Context.getCanonicalType(FromType);
657 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000658 } else {
659 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000660 SCS.Third = ICK_Identity;
661
662 // C++ [over.best.ics]p6:
663 // [...] Any difference in top-level cv-qualification is
664 // subsumed by the initialization itself and does not constitute
665 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000666 CanonFrom = Context.getCanonicalType(FromType);
667 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000668 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000669 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
670 FromType = ToType;
671 CanonFrom = CanonTo;
672 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000673 }
674
675 // If we have not converted the argument type to the parameter type,
676 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000677 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000678 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000679
Douglas Gregor60d62c22008-10-31 16:23:19 +0000680 SCS.ToTypePtr = FromType.getAsOpaquePtr();
681 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000682}
683
684/// IsIntegralPromotion - Determines whether the conversion from the
685/// expression From (whose potentially-adjusted type is FromType) to
686/// ToType is an integral promotion (C++ 4.5). If so, returns true and
687/// sets PromotedType to the promoted type.
688bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
689{
690 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000691 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000692 if (!To) {
693 return false;
694 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000695
696 // An rvalue of type char, signed char, unsigned char, short int, or
697 // unsigned short int can be converted to an rvalue of type int if
698 // int can represent all the values of the source type; otherwise,
699 // the source rvalue can be converted to an rvalue of type unsigned
700 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000701 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000702 if (// We can promote any signed, promotable integer type to an int
703 (FromType->isSignedIntegerType() ||
704 // We can promote any unsigned integer type whose size is
705 // less than int to an int.
706 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000707 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000708 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000709 }
710
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000711 return To->getKind() == BuiltinType::UInt;
712 }
713
714 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
715 // can be converted to an rvalue of the first of the following types
716 // that can represent all the values of its underlying type: int,
717 // unsigned int, long, or unsigned long (C++ 4.5p2).
718 if ((FromType->isEnumeralType() || FromType->isWideCharType())
719 && ToType->isIntegerType()) {
720 // Determine whether the type we're converting from is signed or
721 // unsigned.
722 bool FromIsSigned;
723 uint64_t FromSize = Context.getTypeSize(FromType);
724 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
725 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
726 FromIsSigned = UnderlyingType->isSignedIntegerType();
727 } else {
728 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
729 FromIsSigned = true;
730 }
731
732 // The types we'll try to promote to, in the appropriate
733 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000734 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000735 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000736 Context.LongTy, Context.UnsignedLongTy ,
737 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000738 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000739 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000740 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
741 if (FromSize < ToSize ||
742 (FromSize == ToSize &&
743 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
744 // We found the type that we can promote to. If this is the
745 // type we wanted, we have a promotion. Otherwise, no
746 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000747 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000748 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
749 }
750 }
751 }
752
753 // An rvalue for an integral bit-field (9.6) can be converted to an
754 // rvalue of type int if int can represent all the values of the
755 // bit-field; otherwise, it can be converted to unsigned int if
756 // unsigned int can represent all the values of the bit-field. If
757 // the bit-field is larger yet, no integral promotion applies to
758 // it. If the bit-field has an enumerated type, it is treated as any
759 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000760 // FIXME: We should delay checking of bit-fields until we actually perform the
761 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000762 using llvm::APSInt;
763 if (From)
764 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000765 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000766 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
767 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
768 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
769 ToSize = Context.getTypeSize(ToType);
Douglas Gregor86f19402008-12-20 23:49:58 +0000770
771 // Are we promoting to an int from a bitfield that fits in an int?
772 if (BitWidth < ToSize ||
773 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
774 return To->getKind() == BuiltinType::Int;
775 }
776
777 // Are we promoting to an unsigned int from an unsigned bitfield
778 // that fits into an unsigned int?
779 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
780 return To->getKind() == BuiltinType::UInt;
781 }
782
783 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000784 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000785 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000786
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000787 // An rvalue of type bool can be converted to an rvalue of type int,
788 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000789 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000790 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000791 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000792
793 return false;
794}
795
796/// IsFloatingPointPromotion - Determines whether the conversion from
797/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
798/// returns true and sets PromotedType to the promoted type.
799bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
800{
801 /// An rvalue of type float can be converted to an rvalue of type
802 /// double. (C++ 4.6p1).
803 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000804 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000805 if (FromBuiltin->getKind() == BuiltinType::Float &&
806 ToBuiltin->getKind() == BuiltinType::Double)
807 return true;
808
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000809 // C99 6.3.1.5p1:
810 // When a float is promoted to double or long double, or a
811 // double is promoted to long double [...].
812 if (!getLangOptions().CPlusPlus &&
813 (FromBuiltin->getKind() == BuiltinType::Float ||
814 FromBuiltin->getKind() == BuiltinType::Double) &&
815 (ToBuiltin->getKind() == BuiltinType::LongDouble))
816 return true;
817 }
818
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000819 return false;
820}
821
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000822/// \brief Determine if a conversion is a complex promotion.
823///
824/// A complex promotion is defined as a complex -> complex conversion
825/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000826/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000827bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
828 const ComplexType *FromComplex = FromType->getAsComplexType();
829 if (!FromComplex)
830 return false;
831
832 const ComplexType *ToComplex = ToType->getAsComplexType();
833 if (!ToComplex)
834 return false;
835
836 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000837 ToComplex->getElementType()) ||
838 IsIntegralPromotion(0, FromComplex->getElementType(),
839 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000840}
841
Douglas Gregorcb7de522008-11-26 23:31:11 +0000842/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
843/// the pointer type FromPtr to a pointer to type ToPointee, with the
844/// same type qualifiers as FromPtr has on its pointee type. ToType,
845/// if non-empty, will be a pointer to ToType that may or may not have
846/// the right set of qualifiers on its pointee.
847static QualType
848BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
849 QualType ToPointee, QualType ToType,
850 ASTContext &Context) {
851 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
852 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
853 unsigned Quals = CanonFromPointee.getCVRQualifiers();
854
855 // Exact qualifier match -> return the pointer type we're converting to.
856 if (CanonToPointee.getCVRQualifiers() == Quals) {
857 // ToType is exactly what we need. Return it.
858 if (ToType.getTypePtr())
859 return ToType;
860
861 // Build a pointer to ToPointee. It has the right qualifiers
862 // already.
863 return Context.getPointerType(ToPointee);
864 }
865
866 // Just build a canonical type that has the right qualifiers.
867 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
868}
869
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000870/// IsPointerConversion - Determines whether the conversion of the
871/// expression From, which has the (possibly adjusted) type FromType,
872/// can be converted to the type ToType via a pointer conversion (C++
873/// 4.10). If so, returns true and places the converted type (that
874/// might differ from ToType in its cv-qualifiers at some level) into
875/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000876///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000877/// This routine also supports conversions to and from block pointers
878/// and conversions with Objective-C's 'id', 'id<protocols...>', and
879/// pointers to interfaces. FIXME: Once we've determined the
880/// appropriate overloading rules for Objective-C, we may want to
881/// split the Objective-C checks into a different routine; however,
882/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000883/// conversions, so for now they live here. IncompatibleObjC will be
884/// set if the conversion is an allowed Objective-C conversion that
885/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000886bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000887 QualType& ConvertedType,
888 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000889{
Douglas Gregor45920e82008-12-19 17:40:08 +0000890 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000891 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
892 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000893
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000894 // Conversion from a null pointer constant to any Objective-C pointer type.
Steve Narofff4954562009-07-16 15:41:00 +0000895 if (ToType->isObjCObjectPointerType() &&
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000896 From->isNullPointerConstant(Context)) {
897 ConvertedType = ToType;
898 return true;
899 }
900
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000901 // Blocks: Block pointers can be converted to void*.
902 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000903 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000904 ConvertedType = ToType;
905 return true;
906 }
907 // Blocks: A null pointer constant can be converted to a block
908 // pointer type.
909 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
910 ConvertedType = ToType;
911 return true;
912 }
913
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000914 // If the left-hand-side is nullptr_t, the right side can be a null
915 // pointer constant.
916 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
917 ConvertedType = ToType;
918 return true;
919 }
920
Ted Kremenek6217b802009-07-29 21:53:49 +0000921 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000922 if (!ToTypePtr)
923 return false;
924
925 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
926 if (From->isNullPointerConstant(Context)) {
927 ConvertedType = ToType;
928 return true;
929 }
Sebastian Redl07779722008-10-31 14:43:28 +0000930
Douglas Gregorcb7de522008-11-26 23:31:11 +0000931 // Beyond this point, both types need to be pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +0000932 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +0000933 if (!FromTypePtr)
934 return false;
935
936 QualType FromPointeeType = FromTypePtr->getPointeeType();
937 QualType ToPointeeType = ToTypePtr->getPointeeType();
938
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000939 // An rvalue of type "pointer to cv T," where T is an object type,
940 // can be converted to an rvalue of type "pointer to cv void" (C++
941 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +0000942 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000943 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
944 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000945 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000946 return true;
947 }
948
Douglas Gregorf9201e02009-02-11 23:02:49 +0000949 // When we're overloading in C, we allow a special kind of pointer
950 // conversion for compatible-but-not-identical pointee types.
951 if (!getLangOptions().CPlusPlus &&
952 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
954 ToPointeeType,
955 ToType, Context);
956 return true;
957 }
958
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000959 // C++ [conv.ptr]p3:
960 //
961 // An rvalue of type "pointer to cv D," where D is a class type,
962 // can be converted to an rvalue of type "pointer to cv B," where
963 // B is a base class (clause 10) of D. If B is an inaccessible
964 // (clause 11) or ambiguous (10.2) base class of D, a program that
965 // necessitates this conversion is ill-formed. The result of the
966 // conversion is a pointer to the base class sub-object of the
967 // derived class object. The null pointer value is converted to
968 // the null pointer value of the destination type.
969 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000970 // Note that we do not check for ambiguity or inaccessibility
971 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +0000972 if (getLangOptions().CPlusPlus &&
973 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorcb7de522008-11-26 23:31:11 +0000974 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000975 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
976 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000977 ToType, Context);
978 return true;
979 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000980
Douglas Gregorc7887512008-12-19 19:13:09 +0000981 return false;
982}
983
984/// isObjCPointerConversion - Determines whether this is an
985/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
986/// with the same arguments and return values.
987bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
988 QualType& ConvertedType,
989 bool &IncompatibleObjC) {
990 if (!getLangOptions().ObjC1)
991 return false;
992
Steve Naroff14108da2009-07-10 23:34:53 +0000993 // First, we handle all conversions on ObjC object pointer types.
994 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
995 const ObjCObjectPointerType *FromObjCPtr =
996 FromType->getAsObjCObjectPointerType();
Douglas Gregorc7887512008-12-19 19:13:09 +0000997
Steve Naroff14108da2009-07-10 23:34:53 +0000998 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +0000999 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001000 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001001 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001002 ConvertedType = ToType;
1003 return true;
1004 }
1005 // Conversions with Objective-C's id<...>.
1006 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1007 ToObjCPtr->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00001008 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1009 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001010 ConvertedType = ToType;
1011 return true;
1012 }
1013 // Objective C++: We're able to convert from a pointer to an
1014 // interface to a pointer to a different interface.
1015 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1016 ConvertedType = ToType;
1017 return true;
1018 }
1019
1020 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1021 // Okay: this is some kind of implicit downcast of Objective-C
1022 // interfaces, which is permitted. However, we're going to
1023 // complain about it.
1024 IncompatibleObjC = true;
1025 ConvertedType = FromType;
1026 return true;
1027 }
1028 }
1029 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001030 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001031 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001032 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001033 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001034 ToPointeeType = ToBlockPtr->getPointeeType();
1035 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001036 return false;
1037
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001038 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001039 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001040 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001041 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001042 FromPointeeType = FromBlockPtr->getPointeeType();
1043 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001044 return false;
1045
Douglas Gregorc7887512008-12-19 19:13:09 +00001046 // If we have pointers to pointers, recursively check whether this
1047 // is an Objective-C conversion.
1048 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1049 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1050 IncompatibleObjC)) {
1051 // We always complain about this conversion.
1052 IncompatibleObjC = true;
1053 ConvertedType = ToType;
1054 return true;
1055 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001056 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001057 // differences in the argument and result types are in Objective-C
1058 // pointer conversions. If so, we permit the conversion (but
1059 // complain about it).
Douglas Gregor72564e72009-02-26 23:50:07 +00001060 const FunctionProtoType *FromFunctionType
1061 = FromPointeeType->getAsFunctionProtoType();
1062 const FunctionProtoType *ToFunctionType
1063 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregorc7887512008-12-19 19:13:09 +00001064 if (FromFunctionType && ToFunctionType) {
1065 // If the function types are exactly the same, this isn't an
1066 // Objective-C pointer conversion.
1067 if (Context.getCanonicalType(FromPointeeType)
1068 == Context.getCanonicalType(ToPointeeType))
1069 return false;
1070
1071 // Perform the quick checks that will tell us whether these
1072 // function types are obviously different.
1073 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1074 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1075 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1076 return false;
1077
1078 bool HasObjCConversion = false;
1079 if (Context.getCanonicalType(FromFunctionType->getResultType())
1080 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1081 // Okay, the types match exactly. Nothing to do.
1082 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1083 ToFunctionType->getResultType(),
1084 ConvertedType, IncompatibleObjC)) {
1085 // Okay, we have an Objective-C pointer conversion.
1086 HasObjCConversion = true;
1087 } else {
1088 // Function types are too different. Abort.
1089 return false;
1090 }
1091
1092 // Check argument types.
1093 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1094 ArgIdx != NumArgs; ++ArgIdx) {
1095 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1096 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1097 if (Context.getCanonicalType(FromArgType)
1098 == Context.getCanonicalType(ToArgType)) {
1099 // Okay, the types match exactly. Nothing to do.
1100 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1101 ConvertedType, IncompatibleObjC)) {
1102 // Okay, we have an Objective-C pointer conversion.
1103 HasObjCConversion = true;
1104 } else {
1105 // Argument types are too different. Abort.
1106 return false;
1107 }
1108 }
1109
1110 if (HasObjCConversion) {
1111 // We had an Objective-C conversion. Allow this pointer
1112 // conversion, but complain about it.
1113 ConvertedType = ToType;
1114 IncompatibleObjC = true;
1115 return true;
1116 }
1117 }
1118
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001119 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001120}
1121
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001122/// CheckPointerConversion - Check the pointer conversion from the
1123/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001124/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001125/// conversions for which IsPointerConversion has already returned
1126/// true. It returns true and produces a diagnostic if there was an
1127/// error, or returns false otherwise.
1128bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1129 QualType FromType = From->getType();
1130
Ted Kremenek6217b802009-07-29 21:53:49 +00001131 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1132 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001133 QualType FromPointeeType = FromPtrType->getPointeeType(),
1134 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001135
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001136 if (FromPointeeType->isRecordType() &&
1137 ToPointeeType->isRecordType()) {
1138 // We must have a derived-to-base conversion. Check an
1139 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001140 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1141 From->getExprLoc(),
1142 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001143 }
1144 }
Steve Naroff14108da2009-07-10 23:34:53 +00001145 if (const ObjCObjectPointerType *FromPtrType =
1146 FromType->getAsObjCObjectPointerType())
1147 if (const ObjCObjectPointerType *ToPtrType =
1148 ToType->getAsObjCObjectPointerType()) {
1149 // Objective-C++ conversions are always okay.
1150 // FIXME: We should have a different class of conversions for the
1151 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001152 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001153 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001154
Steve Naroff14108da2009-07-10 23:34:53 +00001155 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001156 return false;
1157}
1158
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001159/// IsMemberPointerConversion - Determines whether the conversion of the
1160/// expression From, which has the (possibly adjusted) type FromType, can be
1161/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1162/// If so, returns true and places the converted type (that might differ from
1163/// ToType in its cv-qualifiers at some level) into ConvertedType.
1164bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1165 QualType ToType, QualType &ConvertedType)
1166{
Ted Kremenek6217b802009-07-29 21:53:49 +00001167 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001168 if (!ToTypePtr)
1169 return false;
1170
1171 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1172 if (From->isNullPointerConstant(Context)) {
1173 ConvertedType = ToType;
1174 return true;
1175 }
1176
1177 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001178 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001179 if (!FromTypePtr)
1180 return false;
1181
1182 // A pointer to member of B can be converted to a pointer to member of D,
1183 // where D is derived from B (C++ 4.11p2).
1184 QualType FromClass(FromTypePtr->getClass(), 0);
1185 QualType ToClass(ToTypePtr->getClass(), 0);
1186 // FIXME: What happens when these are dependent? Is this function even called?
1187
1188 if (IsDerivedFrom(ToClass, FromClass)) {
1189 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1190 ToClass.getTypePtr());
1191 return true;
1192 }
1193
1194 return false;
1195}
1196
1197/// CheckMemberPointerConversion - Check the member pointer conversion from the
1198/// expression From to the type ToType. This routine checks for ambiguous or
1199/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1200/// for which IsMemberPointerConversion has already returned true. It returns
1201/// true and produces a diagnostic if there was an error, or returns false
1202/// otherwise.
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001203bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1204 CastExpr::CastKind &Kind) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001205 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001206 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001207 if (!FromPtrType) {
1208 // This must be a null pointer to member pointer conversion
1209 assert(From->isNullPointerConstant(Context) &&
1210 "Expr must be null pointer constant!");
1211 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001212 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001213 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001214
Ted Kremenek6217b802009-07-29 21:53:49 +00001215 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001216 assert(ToPtrType && "No member pointer cast has a target type "
1217 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001218
Sebastian Redl21593ac2009-01-28 18:33:18 +00001219 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1220 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001221
Sebastian Redl21593ac2009-01-28 18:33:18 +00001222 // FIXME: What about dependent types?
1223 assert(FromClass->isRecordType() && "Pointer into non-class.");
1224 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001225
Sebastian Redl21593ac2009-01-28 18:33:18 +00001226 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1227 /*DetectVirtual=*/true);
1228 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1229 assert(DerivationOkay &&
1230 "Should not have been called if derivation isn't OK.");
1231 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001232
Sebastian Redl21593ac2009-01-28 18:33:18 +00001233 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1234 getUnqualifiedType())) {
1235 // Derivation is ambiguous. Redo the check to find the exact paths.
1236 Paths.clear();
1237 Paths.setRecordingPaths(true);
1238 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1239 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1240 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001241
Sebastian Redl21593ac2009-01-28 18:33:18 +00001242 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1243 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1244 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1245 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001246 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001247
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001248 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001249 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1250 << FromClass << ToClass << QualType(VBase, 0)
1251 << From->getSourceRange();
1252 return true;
1253 }
1254
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001255 // Must be a base to derived member conversion.
1256 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001257 return false;
1258}
1259
Douglas Gregor98cd5992008-10-21 23:43:52 +00001260/// IsQualificationConversion - Determines whether the conversion from
1261/// an rvalue of type FromType to ToType is a qualification conversion
1262/// (C++ 4.4).
1263bool
1264Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1265{
1266 FromType = Context.getCanonicalType(FromType);
1267 ToType = Context.getCanonicalType(ToType);
1268
1269 // If FromType and ToType are the same type, this is not a
1270 // qualification conversion.
1271 if (FromType == ToType)
1272 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001273
Douglas Gregor98cd5992008-10-21 23:43:52 +00001274 // (C++ 4.4p4):
1275 // A conversion can add cv-qualifiers at levels other than the first
1276 // in multi-level pointers, subject to the following rules: [...]
1277 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001278 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001279 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001280 // Within each iteration of the loop, we check the qualifiers to
1281 // determine if this still looks like a qualification
1282 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001283 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001284 // until there are no more pointers or pointers-to-members left to
1285 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001286 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001287
1288 // -- for every j > 0, if const is in cv 1,j then const is in cv
1289 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001290 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001291 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001292
Douglas Gregor98cd5992008-10-21 23:43:52 +00001293 // -- if the cv 1,j and cv 2,j are different, then const is in
1294 // every cv for 0 < k < j.
1295 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001296 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001297 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001298
Douglas Gregor98cd5992008-10-21 23:43:52 +00001299 // Keep track of whether all prior cv-qualifiers in the "to" type
1300 // include const.
1301 PreviousToQualsIncludeConst
1302 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001303 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001304
1305 // We are left with FromType and ToType being the pointee types
1306 // after unwrapping the original FromType and ToType the same number
1307 // of types. If we unwrapped any pointers, and if FromType and
1308 // ToType have the same unqualified type (since we checked
1309 // qualifiers above), then this is a qualification conversion.
1310 return UnwrappedAnyPointer &&
1311 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1312}
1313
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001314/// \brief Given a function template or function, extract the function template
1315/// declaration (if any) and the underlying function declaration.
1316template<typename T>
1317static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1318 FunctionTemplateDecl *&FunctionTemplate) {
1319 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1320 if (FunctionTemplate)
1321 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1322 else
1323 Function = cast<T>(Orig);
1324}
1325
1326
Douglas Gregor734d9862009-01-30 23:27:23 +00001327/// Determines whether there is a user-defined conversion sequence
1328/// (C++ [over.ics.user]) that converts expression From to the type
1329/// ToType. If such a conversion exists, User will contain the
1330/// user-defined conversion sequence that performs such a conversion
1331/// and this routine will return true. Otherwise, this routine returns
1332/// false and User is unspecified.
1333///
1334/// \param AllowConversionFunctions true if the conversion should
1335/// consider conversion functions at all. If false, only constructors
1336/// will be considered.
1337///
1338/// \param AllowExplicit true if the conversion should consider C++0x
1339/// "explicit" conversion functions as well as non-explicit conversion
1340/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001341///
1342/// \param ForceRValue true if the expression should be treated as an rvalue
1343/// for overload resolution.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001344bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001345 UserDefinedConversionSequence& User,
Douglas Gregor734d9862009-01-30 23:27:23 +00001346 bool AllowConversionFunctions,
Sebastian Redle2b68332009-04-12 17:16:29 +00001347 bool AllowExplicit, bool ForceRValue)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001348{
1349 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00001350 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001351 if (CXXRecordDecl *ToRecordDecl
1352 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1353 // C++ [over.match.ctor]p1:
1354 // When objects of class type are direct-initialized (8.5), or
1355 // copy-initialized from an expression of the same or a
1356 // derived class type (8.5), overload resolution selects the
1357 // constructor. [...] For copy-initialization, the candidate
1358 // functions are all the converting constructors (12.3.1) of
1359 // that class. The argument list is the expression-list within
1360 // the parentheses of the initializer.
1361 DeclarationName ConstructorName
1362 = Context.DeclarationNames.getCXXConstructorName(
1363 Context.getCanonicalType(ToType).getUnqualifiedType());
1364 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001365 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001366 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001367 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001368 // Find the constructor (which may be a template).
1369 CXXConstructorDecl *Constructor = 0;
1370 FunctionTemplateDecl *ConstructorTmpl
1371 = dyn_cast<FunctionTemplateDecl>(*Con);
1372 if (ConstructorTmpl)
1373 Constructor
1374 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1375 else
1376 Constructor = cast<CXXConstructorDecl>(*Con);
1377
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001378 if (!Constructor->isInvalidDecl() &&
Douglas Gregordec06662009-08-21 18:42:58 +00001379 Constructor->isConvertingConstructor()) {
1380 if (ConstructorTmpl)
1381 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1382 1, CandidateSet,
1383 /*SuppressUserConversions=*/true,
1384 ForceRValue);
1385 else
1386 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1387 /*SuppressUserConversions=*/true, ForceRValue);
1388 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001389 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001390 }
1391 }
1392
Douglas Gregor734d9862009-01-30 23:27:23 +00001393 if (!AllowConversionFunctions) {
1394 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001395 } else if (RequireCompleteType(From->getLocStart(), From->getType(), 0,
1396 From->getSourceRange())) {
1397 // No conversion functions from incomplete types.
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001398 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001399 = From->getType()->getAs<RecordType>()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001400 if (CXXRecordDecl *FromRecordDecl
1401 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1402 // Add all of the conversion functions as candidates.
1403 // FIXME: Look for conversions in base classes!
1404 OverloadedFunctionDecl *Conversions
1405 = FromRecordDecl->getConversionFunctions();
1406 for (OverloadedFunctionDecl::function_iterator Func
1407 = Conversions->function_begin();
1408 Func != Conversions->function_end(); ++Func) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001409 CXXConversionDecl *Conv;
1410 FunctionTemplateDecl *ConvTemplate;
1411 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1412 if (ConvTemplate)
1413 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1414 else
1415 Conv = dyn_cast<CXXConversionDecl>(*Func);
1416
1417 if (AllowExplicit || !Conv->isExplicit()) {
1418 if (ConvTemplate)
1419 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1420 CandidateSet);
1421 else
1422 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1423 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001424 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001425 }
1426 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001427
1428 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001429 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001430 case OR_Success:
1431 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001432 if (CXXConstructorDecl *Constructor
1433 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1434 // C++ [over.ics.user]p1:
1435 // If the user-defined conversion is specified by a
1436 // constructor (12.3.1), the initial standard conversion
1437 // sequence converts the source type to the type required by
1438 // the argument of the constructor.
1439 //
1440 // FIXME: What about ellipsis conversions?
1441 QualType ThisType = Constructor->getThisType(Context);
1442 User.Before = Best->Conversions[0].Standard;
1443 User.ConversionFunction = Constructor;
1444 User.After.setAsIdentityConversion();
1445 User.After.FromTypePtr
Ted Kremenek6217b802009-07-29 21:53:49 +00001446 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor60d62c22008-10-31 16:23:19 +00001447 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1448 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001449 } else if (CXXConversionDecl *Conversion
1450 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1451 // C++ [over.ics.user]p1:
1452 //
1453 // [...] If the user-defined conversion is specified by a
1454 // conversion function (12.3.2), the initial standard
1455 // conversion sequence converts the source type to the
1456 // implicit object parameter of the conversion function.
1457 User.Before = Best->Conversions[0].Standard;
1458 User.ConversionFunction = Conversion;
1459
1460 // C++ [over.ics.user]p2:
1461 // The second standard conversion sequence converts the
1462 // result of the user-defined conversion to the target type
1463 // for the sequence. Since an implicit conversion sequence
1464 // is an initialization, the special rules for
1465 // initialization by user-defined conversion apply when
1466 // selecting the best user-defined conversion for a
1467 // user-defined conversion sequence (see 13.3.3 and
1468 // 13.3.3.1).
1469 User.After = Best->FinalConversion;
1470 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001471 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001472 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001473 return false;
1474 }
1475
1476 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001477 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001478 // No conversion here! We're done.
1479 return false;
1480
1481 case OR_Ambiguous:
1482 // FIXME: See C++ [over.best.ics]p10 for the handling of
1483 // ambiguous conversion sequences.
1484 return false;
1485 }
1486
1487 return false;
1488}
1489
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001490/// CompareImplicitConversionSequences - Compare two implicit
1491/// conversion sequences to determine whether one is better than the
1492/// other or if they are indistinguishable (C++ 13.3.3.2).
1493ImplicitConversionSequence::CompareKind
1494Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1495 const ImplicitConversionSequence& ICS2)
1496{
1497 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1498 // conversion sequences (as defined in 13.3.3.1)
1499 // -- a standard conversion sequence (13.3.3.1.1) is a better
1500 // conversion sequence than a user-defined conversion sequence or
1501 // an ellipsis conversion sequence, and
1502 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1503 // conversion sequence than an ellipsis conversion sequence
1504 // (13.3.3.1.3).
1505 //
1506 if (ICS1.ConversionKind < ICS2.ConversionKind)
1507 return ImplicitConversionSequence::Better;
1508 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1509 return ImplicitConversionSequence::Worse;
1510
1511 // Two implicit conversion sequences of the same form are
1512 // indistinguishable conversion sequences unless one of the
1513 // following rules apply: (C++ 13.3.3.2p3):
1514 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1515 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1516 else if (ICS1.ConversionKind ==
1517 ImplicitConversionSequence::UserDefinedConversion) {
1518 // User-defined conversion sequence U1 is a better conversion
1519 // sequence than another user-defined conversion sequence U2 if
1520 // they contain the same user-defined conversion function or
1521 // constructor and if the second standard conversion sequence of
1522 // U1 is better than the second standard conversion sequence of
1523 // U2 (C++ 13.3.3.2p3).
1524 if (ICS1.UserDefined.ConversionFunction ==
1525 ICS2.UserDefined.ConversionFunction)
1526 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1527 ICS2.UserDefined.After);
1528 }
1529
1530 return ImplicitConversionSequence::Indistinguishable;
1531}
1532
1533/// CompareStandardConversionSequences - Compare two standard
1534/// conversion sequences to determine whether one is better than the
1535/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1536ImplicitConversionSequence::CompareKind
1537Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1538 const StandardConversionSequence& SCS2)
1539{
1540 // Standard conversion sequence S1 is a better conversion sequence
1541 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1542
1543 // -- S1 is a proper subsequence of S2 (comparing the conversion
1544 // sequences in the canonical form defined by 13.3.3.1.1,
1545 // excluding any Lvalue Transformation; the identity conversion
1546 // sequence is considered to be a subsequence of any
1547 // non-identity conversion sequence) or, if not that,
1548 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1549 // Neither is a proper subsequence of the other. Do nothing.
1550 ;
1551 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1552 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1553 (SCS1.Second == ICK_Identity &&
1554 SCS1.Third == ICK_Identity))
1555 // SCS1 is a proper subsequence of SCS2.
1556 return ImplicitConversionSequence::Better;
1557 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1558 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1559 (SCS2.Second == ICK_Identity &&
1560 SCS2.Third == ICK_Identity))
1561 // SCS2 is a proper subsequence of SCS1.
1562 return ImplicitConversionSequence::Worse;
1563
1564 // -- the rank of S1 is better than the rank of S2 (by the rules
1565 // defined below), or, if not that,
1566 ImplicitConversionRank Rank1 = SCS1.getRank();
1567 ImplicitConversionRank Rank2 = SCS2.getRank();
1568 if (Rank1 < Rank2)
1569 return ImplicitConversionSequence::Better;
1570 else if (Rank2 < Rank1)
1571 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001572
Douglas Gregor57373262008-10-22 14:17:15 +00001573 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1574 // are indistinguishable unless one of the following rules
1575 // applies:
1576
1577 // A conversion that is not a conversion of a pointer, or
1578 // pointer to member, to bool is better than another conversion
1579 // that is such a conversion.
1580 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1581 return SCS2.isPointerConversionToBool()
1582 ? ImplicitConversionSequence::Better
1583 : ImplicitConversionSequence::Worse;
1584
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001585 // C++ [over.ics.rank]p4b2:
1586 //
1587 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001588 // conversion of B* to A* is better than conversion of B* to
1589 // void*, and conversion of A* to void* is better than conversion
1590 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001591 bool SCS1ConvertsToVoid
1592 = SCS1.isPointerConversionToVoidPointer(Context);
1593 bool SCS2ConvertsToVoid
1594 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001595 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1596 // Exactly one of the conversion sequences is a conversion to
1597 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001598 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1599 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001600 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1601 // Neither conversion sequence converts to a void pointer; compare
1602 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001603 if (ImplicitConversionSequence::CompareKind DerivedCK
1604 = CompareDerivedToBaseConversions(SCS1, SCS2))
1605 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001606 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1607 // Both conversion sequences are conversions to void
1608 // pointers. Compare the source types to determine if there's an
1609 // inheritance relationship in their sources.
1610 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1611 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1612
1613 // Adjust the types we're converting from via the array-to-pointer
1614 // conversion, if we need to.
1615 if (SCS1.First == ICK_Array_To_Pointer)
1616 FromType1 = Context.getArrayDecayedType(FromType1);
1617 if (SCS2.First == ICK_Array_To_Pointer)
1618 FromType2 = Context.getArrayDecayedType(FromType2);
1619
1620 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001621 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001622 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001623 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001624
1625 if (IsDerivedFrom(FromPointee2, FromPointee1))
1626 return ImplicitConversionSequence::Better;
1627 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1628 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001629
1630 // Objective-C++: If one interface is more specific than the
1631 // other, it is the better one.
1632 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1633 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1634 if (FromIface1 && FromIface1) {
1635 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1636 return ImplicitConversionSequence::Better;
1637 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1638 return ImplicitConversionSequence::Worse;
1639 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001640 }
Douglas Gregor57373262008-10-22 14:17:15 +00001641
1642 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1643 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001644 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001645 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001646 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001647
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001648 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001649 // C++0x [over.ics.rank]p3b4:
1650 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1651 // implicit object parameter of a non-static member function declared
1652 // without a ref-qualifier, and S1 binds an rvalue reference to an
1653 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001654 // FIXME: We don't know if we're dealing with the implicit object parameter,
1655 // or if the member function in this case has a ref qualifier.
1656 // (Of course, we don't have ref qualifiers yet.)
1657 if (SCS1.RRefBinding != SCS2.RRefBinding)
1658 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1659 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001660
1661 // C++ [over.ics.rank]p3b4:
1662 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1663 // which the references refer are the same type except for
1664 // top-level cv-qualifiers, and the type to which the reference
1665 // initialized by S2 refers is more cv-qualified than the type
1666 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001667 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1668 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001669 T1 = Context.getCanonicalType(T1);
1670 T2 = Context.getCanonicalType(T2);
1671 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1672 if (T2.isMoreQualifiedThan(T1))
1673 return ImplicitConversionSequence::Better;
1674 else if (T1.isMoreQualifiedThan(T2))
1675 return ImplicitConversionSequence::Worse;
1676 }
1677 }
Douglas Gregor57373262008-10-22 14:17:15 +00001678
1679 return ImplicitConversionSequence::Indistinguishable;
1680}
1681
1682/// CompareQualificationConversions - Compares two standard conversion
1683/// sequences to determine whether they can be ranked based on their
1684/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1685ImplicitConversionSequence::CompareKind
1686Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1687 const StandardConversionSequence& SCS2)
1688{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001689 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001690 // -- S1 and S2 differ only in their qualification conversion and
1691 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1692 // cv-qualification signature of type T1 is a proper subset of
1693 // the cv-qualification signature of type T2, and S1 is not the
1694 // deprecated string literal array-to-pointer conversion (4.2).
1695 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1696 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1697 return ImplicitConversionSequence::Indistinguishable;
1698
1699 // FIXME: the example in the standard doesn't use a qualification
1700 // conversion (!)
1701 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1702 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1703 T1 = Context.getCanonicalType(T1);
1704 T2 = Context.getCanonicalType(T2);
1705
1706 // If the types are the same, we won't learn anything by unwrapped
1707 // them.
1708 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1709 return ImplicitConversionSequence::Indistinguishable;
1710
1711 ImplicitConversionSequence::CompareKind Result
1712 = ImplicitConversionSequence::Indistinguishable;
1713 while (UnwrapSimilarPointerTypes(T1, T2)) {
1714 // Within each iteration of the loop, we check the qualifiers to
1715 // determine if this still looks like a qualification
1716 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001717 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001718 // until there are no more pointers or pointers-to-members left
1719 // to unwrap. This essentially mimics what
1720 // IsQualificationConversion does, but here we're checking for a
1721 // strict subset of qualifiers.
1722 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1723 // The qualifiers are the same, so this doesn't tell us anything
1724 // about how the sequences rank.
1725 ;
1726 else if (T2.isMoreQualifiedThan(T1)) {
1727 // T1 has fewer qualifiers, so it could be the better sequence.
1728 if (Result == ImplicitConversionSequence::Worse)
1729 // Neither has qualifiers that are a subset of the other's
1730 // qualifiers.
1731 return ImplicitConversionSequence::Indistinguishable;
1732
1733 Result = ImplicitConversionSequence::Better;
1734 } else if (T1.isMoreQualifiedThan(T2)) {
1735 // T2 has fewer qualifiers, so it could be the better sequence.
1736 if (Result == ImplicitConversionSequence::Better)
1737 // Neither has qualifiers that are a subset of the other's
1738 // qualifiers.
1739 return ImplicitConversionSequence::Indistinguishable;
1740
1741 Result = ImplicitConversionSequence::Worse;
1742 } else {
1743 // Qualifiers are disjoint.
1744 return ImplicitConversionSequence::Indistinguishable;
1745 }
1746
1747 // If the types after this point are equivalent, we're done.
1748 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1749 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001750 }
1751
Douglas Gregor57373262008-10-22 14:17:15 +00001752 // Check that the winning standard conversion sequence isn't using
1753 // the deprecated string literal array to pointer conversion.
1754 switch (Result) {
1755 case ImplicitConversionSequence::Better:
1756 if (SCS1.Deprecated)
1757 Result = ImplicitConversionSequence::Indistinguishable;
1758 break;
1759
1760 case ImplicitConversionSequence::Indistinguishable:
1761 break;
1762
1763 case ImplicitConversionSequence::Worse:
1764 if (SCS2.Deprecated)
1765 Result = ImplicitConversionSequence::Indistinguishable;
1766 break;
1767 }
1768
1769 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001770}
1771
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001772/// CompareDerivedToBaseConversions - Compares two standard conversion
1773/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001774/// various kinds of derived-to-base conversions (C++
1775/// [over.ics.rank]p4b3). As part of these checks, we also look at
1776/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001777ImplicitConversionSequence::CompareKind
1778Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1779 const StandardConversionSequence& SCS2) {
1780 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1781 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1782 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1783 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1784
1785 // Adjust the types we're converting from via the array-to-pointer
1786 // conversion, if we need to.
1787 if (SCS1.First == ICK_Array_To_Pointer)
1788 FromType1 = Context.getArrayDecayedType(FromType1);
1789 if (SCS2.First == ICK_Array_To_Pointer)
1790 FromType2 = Context.getArrayDecayedType(FromType2);
1791
1792 // Canonicalize all of the types.
1793 FromType1 = Context.getCanonicalType(FromType1);
1794 ToType1 = Context.getCanonicalType(ToType1);
1795 FromType2 = Context.getCanonicalType(FromType2);
1796 ToType2 = Context.getCanonicalType(ToType2);
1797
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001798 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001799 //
1800 // If class B is derived directly or indirectly from class A and
1801 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001802 //
1803 // For Objective-C, we let A, B, and C also be Objective-C
1804 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001805
1806 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001807 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001808 SCS2.Second == ICK_Pointer_Conversion &&
1809 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1810 FromType1->isPointerType() && FromType2->isPointerType() &&
1811 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001812 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001813 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001814 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001815 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001816 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001817 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001818 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001819 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001820
1821 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1822 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1823 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1824 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1825
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001826 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001827 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1828 if (IsDerivedFrom(ToPointee1, ToPointee2))
1829 return ImplicitConversionSequence::Better;
1830 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1831 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001832
1833 if (ToIface1 && ToIface2) {
1834 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1835 return ImplicitConversionSequence::Better;
1836 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1837 return ImplicitConversionSequence::Worse;
1838 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001839 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001840
1841 // -- conversion of B* to A* is better than conversion of C* to A*,
1842 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1843 if (IsDerivedFrom(FromPointee2, FromPointee1))
1844 return ImplicitConversionSequence::Better;
1845 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1846 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001847
1848 if (FromIface1 && FromIface2) {
1849 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1850 return ImplicitConversionSequence::Better;
1851 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1852 return ImplicitConversionSequence::Worse;
1853 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001854 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001855 }
1856
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001857 // Compare based on reference bindings.
1858 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1859 SCS1.Second == ICK_Derived_To_Base) {
1860 // -- binding of an expression of type C to a reference of type
1861 // B& is better than binding an expression of type C to a
1862 // reference of type A&,
1863 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1864 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1865 if (IsDerivedFrom(ToType1, ToType2))
1866 return ImplicitConversionSequence::Better;
1867 else if (IsDerivedFrom(ToType2, ToType1))
1868 return ImplicitConversionSequence::Worse;
1869 }
1870
Douglas Gregor225c41e2008-11-03 19:09:14 +00001871 // -- binding of an expression of type B to a reference of type
1872 // A& is better than binding an expression of type C to a
1873 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001874 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1875 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1876 if (IsDerivedFrom(FromType2, FromType1))
1877 return ImplicitConversionSequence::Better;
1878 else if (IsDerivedFrom(FromType1, FromType2))
1879 return ImplicitConversionSequence::Worse;
1880 }
1881 }
1882
1883
1884 // FIXME: conversion of A::* to B::* is better than conversion of
1885 // A::* to C::*,
1886
1887 // FIXME: conversion of B::* to C::* is better than conversion of
1888 // A::* to C::*, and
1889
Douglas Gregor225c41e2008-11-03 19:09:14 +00001890 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1891 SCS1.Second == ICK_Derived_To_Base) {
1892 // -- conversion of C to B is better than conversion of C to A,
1893 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1894 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1895 if (IsDerivedFrom(ToType1, ToType2))
1896 return ImplicitConversionSequence::Better;
1897 else if (IsDerivedFrom(ToType2, ToType1))
1898 return ImplicitConversionSequence::Worse;
1899 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001900
Douglas Gregor225c41e2008-11-03 19:09:14 +00001901 // -- conversion of B to A is better than conversion of C to A.
1902 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1903 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1904 if (IsDerivedFrom(FromType2, FromType1))
1905 return ImplicitConversionSequence::Better;
1906 else if (IsDerivedFrom(FromType1, FromType2))
1907 return ImplicitConversionSequence::Worse;
1908 }
1909 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001910
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001911 return ImplicitConversionSequence::Indistinguishable;
1912}
1913
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001914/// TryCopyInitialization - Try to copy-initialize a value of type
1915/// ToType from the expression From. Return the implicit conversion
1916/// sequence required to pass this argument, which may be a bad
1917/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001918/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00001919/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1920/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001921ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001922Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001923 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001924 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001925 ImplicitConversionSequence ICS;
Sebastian Redle2b68332009-04-12 17:16:29 +00001926 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1927 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001928 return ICS;
1929 } else {
Sebastian Redle2b68332009-04-12 17:16:29 +00001930 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1931 ForceRValue);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001932 }
1933}
1934
Sebastian Redle2b68332009-04-12 17:16:29 +00001935/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1936/// the expression @p From. Returns true (and emits a diagnostic) if there was
1937/// an error, returns false if the initialization succeeded. Elidable should
1938/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1939/// differently in C++0x for this case.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001940bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001941 const char* Flavor, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001942 if (!getLangOptions().CPlusPlus) {
1943 // In C, argument passing is the same as performing an assignment.
1944 QualType FromType = From->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00001945
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001946 AssignConvertType ConvTy =
1947 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00001948 if (ConvTy != Compatible &&
1949 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1950 ConvTy = Compatible;
1951
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001952 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1953 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001954 }
Sebastian Redle2b68332009-04-12 17:16:29 +00001955
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001956 if (ToType->isReferenceType())
1957 return CheckReferenceInit(From, ToType);
1958
Sebastian Redle2b68332009-04-12 17:16:29 +00001959 if (!PerformImplicitConversion(From, ToType, Flavor,
1960 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001961 return false;
Sebastian Redle2b68332009-04-12 17:16:29 +00001962
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001963 return Diag(From->getSourceRange().getBegin(),
1964 diag::err_typecheck_convert_incompatible)
1965 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001966}
1967
Douglas Gregor96176b32008-11-18 23:14:02 +00001968/// TryObjectArgumentInitialization - Try to initialize the object
1969/// parameter of the given member function (@c Method) from the
1970/// expression @p From.
1971ImplicitConversionSequence
1972Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1973 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1974 unsigned MethodQuals = Method->getTypeQualifiers();
1975 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1976
1977 // Set up the conversion sequence as a "bad" conversion, to allow us
1978 // to exit early.
1979 ImplicitConversionSequence ICS;
1980 ICS.Standard.setAsIdentityConversion();
1981 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1982
1983 // We need to have an object of class type.
1984 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001985 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00001986 FromType = PT->getPointeeType();
1987
1988 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00001989
1990 // The implicit object parmeter is has the type "reference to cv X",
1991 // where X is the class of which the function is a member
1992 // (C++ [over.match.funcs]p4). However, when finding an implicit
1993 // conversion sequence for the argument, we are not allowed to
1994 // create temporaries or perform user-defined conversions
1995 // (C++ [over.match.funcs]p5). We perform a simplified version of
1996 // reference binding here, that allows class rvalues to bind to
1997 // non-constant references.
1998
1999 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2000 // with the implicit object parameter (C++ [over.match.funcs]p5).
2001 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2002 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2003 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2004 return ICS;
2005
2006 // Check that we have either the same type or a derived type. It
2007 // affects the conversion rank.
2008 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2009 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2010 ICS.Standard.Second = ICK_Identity;
2011 else if (IsDerivedFrom(FromType, ClassType))
2012 ICS.Standard.Second = ICK_Derived_To_Base;
2013 else
2014 return ICS;
2015
2016 // Success. Mark this as a reference binding.
2017 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2018 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2019 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2020 ICS.Standard.ReferenceBinding = true;
2021 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002022 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002023 return ICS;
2024}
2025
2026/// PerformObjectArgumentInitialization - Perform initialization of
2027/// the implicit object parameter for the given Method with the given
2028/// expression.
2029bool
2030Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002031 QualType FromRecordType, DestType;
2032 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002033 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Anders Carlssona552f7c2009-05-01 18:34:30 +00002034
Ted Kremenek6217b802009-07-29 21:53:49 +00002035 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002036 FromRecordType = PT->getPointeeType();
2037 DestType = Method->getThisType(Context);
2038 } else {
2039 FromRecordType = From->getType();
2040 DestType = ImplicitParamRecordType;
2041 }
2042
Douglas Gregor96176b32008-11-18 23:14:02 +00002043 ImplicitConversionSequence ICS
2044 = TryObjectArgumentInitialization(From, Method);
2045 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2046 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002047 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002048 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2049
Douglas Gregor96176b32008-11-18 23:14:02 +00002050 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002051 CheckDerivedToBaseConversion(FromRecordType,
2052 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002053 From->getSourceRange().getBegin(),
2054 From->getSourceRange()))
2055 return true;
2056
Anders Carlsson116b7d92009-08-07 18:45:49 +00002057 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2058 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002059 return false;
2060}
2061
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002062/// TryContextuallyConvertToBool - Attempt to contextually convert the
2063/// expression From to bool (C++0x [conv]p3).
2064ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2065 return TryImplicitConversion(From, Context.BoolTy, false, true);
2066}
2067
2068/// PerformContextuallyConvertToBool - Perform a contextual conversion
2069/// of the expression From to bool (C++0x [conv]p3).
2070bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2071 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2072 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2073 return false;
2074
2075 return Diag(From->getSourceRange().getBegin(),
2076 diag::err_typecheck_bool_condition)
2077 << From->getType() << From->getSourceRange();
2078}
2079
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002080/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002081/// candidate functions, using the given function call arguments. If
2082/// @p SuppressUserConversions, then don't allow user-defined
2083/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002084/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2085/// hacky way to implement the overloading rules for elidable copy
2086/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002087void
2088Sema::AddOverloadCandidate(FunctionDecl *Function,
2089 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002090 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002091 bool SuppressUserConversions,
2092 bool ForceRValue)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002093{
Douglas Gregor72564e72009-02-26 23:50:07 +00002094 const FunctionProtoType* Proto
2095 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002096 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002097 assert(!isa<CXXConversionDecl>(Function) &&
2098 "Use AddConversionCandidate for conversion functions");
Douglas Gregore53060f2009-06-25 22:08:12 +00002099 assert(!Function->getDescribedFunctionTemplate() &&
2100 "Use AddTemplateOverloadCandidate for function templates");
2101
Douglas Gregor88a35142008-12-22 05:46:06 +00002102 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002103 if (!isa<CXXConstructorDecl>(Method)) {
2104 // If we get here, it's because we're calling a member function
2105 // that is named without a member access expression (e.g.,
2106 // "this->f") that was either written explicitly or created
2107 // implicitly. This can happen with a qualified call to a member
2108 // function, e.g., X::f(). We use a NULL object as the implied
2109 // object argument (C++ [over.call.func]p3).
2110 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2111 SuppressUserConversions, ForceRValue);
2112 return;
2113 }
2114 // We treat a constructor like a non-member function, since its object
2115 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002116 }
2117
2118
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002119 // Add this candidate
2120 CandidateSet.push_back(OverloadCandidate());
2121 OverloadCandidate& Candidate = CandidateSet.back();
2122 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002123 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002124 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002125 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002126
2127 unsigned NumArgsInProto = Proto->getNumArgs();
2128
2129 // (C++ 13.3.2p2): A candidate function having fewer than m
2130 // parameters is viable only if it has an ellipsis in its parameter
2131 // list (8.3.5).
2132 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2133 Candidate.Viable = false;
2134 return;
2135 }
2136
2137 // (C++ 13.3.2p2): A candidate function having more than m parameters
2138 // is viable only if the (m+1)st parameter has a default argument
2139 // (8.3.6). For the purposes of overload resolution, the
2140 // parameter list is truncated on the right, so that there are
2141 // exactly m parameters.
2142 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2143 if (NumArgs < MinRequiredArgs) {
2144 // Not enough arguments.
2145 Candidate.Viable = false;
2146 return;
2147 }
2148
2149 // Determine the implicit conversion sequences for each of the
2150 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002151 Candidate.Conversions.resize(NumArgs);
2152 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2153 if (ArgIdx < NumArgsInProto) {
2154 // (C++ 13.3.2p3): for F to be a viable function, there shall
2155 // exist for each argument an implicit conversion sequence
2156 // (13.3.3.1) that converts that argument to the corresponding
2157 // parameter of F.
2158 QualType ParamType = Proto->getArgType(ArgIdx);
2159 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00002160 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redle2b68332009-04-12 17:16:29 +00002161 SuppressUserConversions, ForceRValue);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002162 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002163 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002164 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002165 break;
2166 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002167 } else {
2168 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2169 // argument for which there is no corresponding parameter is
2170 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2171 Candidate.Conversions[ArgIdx].ConversionKind
2172 = ImplicitConversionSequence::EllipsisConversion;
2173 }
2174 }
2175}
2176
Douglas Gregor063daf62009-03-13 18:40:31 +00002177/// \brief Add all of the function declarations in the given function set to
2178/// the overload canddiate set.
2179void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2180 Expr **Args, unsigned NumArgs,
2181 OverloadCandidateSet& CandidateSet,
2182 bool SuppressUserConversions) {
2183 for (FunctionSet::const_iterator F = Functions.begin(),
2184 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002185 F != FEnd; ++F) {
2186 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2187 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2188 SuppressUserConversions);
2189 else
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002190 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2191 /*FIXME: explicit args */false, 0, 0,
2192 Args, NumArgs, CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002193 SuppressUserConversions);
2194 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002195}
2196
Douglas Gregor96176b32008-11-18 23:14:02 +00002197/// AddMethodCandidate - Adds the given C++ member function to the set
2198/// of candidate functions, using the given function call arguments
2199/// and the object argument (@c Object). For example, in a call
2200/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2201/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2202/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002203/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2204/// a slightly hacky way to implement the overloading rules for elidable copy
2205/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor96176b32008-11-18 23:14:02 +00002206void
2207Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2208 Expr **Args, unsigned NumArgs,
2209 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002210 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor96176b32008-11-18 23:14:02 +00002211{
Douglas Gregor72564e72009-02-26 23:50:07 +00002212 const FunctionProtoType* Proto
2213 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002214 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002215 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor96176b32008-11-18 23:14:02 +00002216 "Use AddConversionCandidate for conversion functions");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002217 assert(!isa<CXXConstructorDecl>(Method) &&
2218 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002219
2220 // Add this candidate
2221 CandidateSet.push_back(OverloadCandidate());
2222 OverloadCandidate& Candidate = CandidateSet.back();
2223 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002224 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002225 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002226
2227 unsigned NumArgsInProto = Proto->getNumArgs();
2228
2229 // (C++ 13.3.2p2): A candidate function having fewer than m
2230 // parameters is viable only if it has an ellipsis in its parameter
2231 // list (8.3.5).
2232 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2233 Candidate.Viable = false;
2234 return;
2235 }
2236
2237 // (C++ 13.3.2p2): A candidate function having more than m parameters
2238 // is viable only if the (m+1)st parameter has a default argument
2239 // (8.3.6). For the purposes of overload resolution, the
2240 // parameter list is truncated on the right, so that there are
2241 // exactly m parameters.
2242 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2243 if (NumArgs < MinRequiredArgs) {
2244 // Not enough arguments.
2245 Candidate.Viable = false;
2246 return;
2247 }
2248
2249 Candidate.Viable = true;
2250 Candidate.Conversions.resize(NumArgs + 1);
2251
Douglas Gregor88a35142008-12-22 05:46:06 +00002252 if (Method->isStatic() || !Object)
2253 // The implicit object argument is ignored.
2254 Candidate.IgnoreObjectArgument = true;
2255 else {
2256 // Determine the implicit conversion sequence for the object
2257 // parameter.
2258 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2259 if (Candidate.Conversions[0].ConversionKind
2260 == ImplicitConversionSequence::BadConversion) {
2261 Candidate.Viable = false;
2262 return;
2263 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002264 }
2265
2266 // Determine the implicit conversion sequences for each of the
2267 // arguments.
2268 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2269 if (ArgIdx < NumArgsInProto) {
2270 // (C++ 13.3.2p3): for F to be a viable function, there shall
2271 // exist for each argument an implicit conversion sequence
2272 // (13.3.3.1) that converts that argument to the corresponding
2273 // parameter of F.
2274 QualType ParamType = Proto->getArgType(ArgIdx);
2275 Candidate.Conversions[ArgIdx + 1]
2276 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redle2b68332009-04-12 17:16:29 +00002277 SuppressUserConversions, ForceRValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00002278 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2279 == ImplicitConversionSequence::BadConversion) {
2280 Candidate.Viable = false;
2281 break;
2282 }
2283 } else {
2284 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2285 // argument for which there is no corresponding parameter is
2286 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2287 Candidate.Conversions[ArgIdx + 1].ConversionKind
2288 = ImplicitConversionSequence::EllipsisConversion;
2289 }
2290 }
2291}
2292
Douglas Gregor6b906862009-08-21 00:16:32 +00002293/// \brief Add a C++ member function template as a candidate to the candidate
2294/// set, using template argument deduction to produce an appropriate member
2295/// function template specialization.
2296void
2297Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2298 bool HasExplicitTemplateArgs,
2299 const TemplateArgument *ExplicitTemplateArgs,
2300 unsigned NumExplicitTemplateArgs,
2301 Expr *Object, Expr **Args, unsigned NumArgs,
2302 OverloadCandidateSet& CandidateSet,
2303 bool SuppressUserConversions,
2304 bool ForceRValue) {
2305 // C++ [over.match.funcs]p7:
2306 // In each case where a candidate is a function template, candidate
2307 // function template specializations are generated using template argument
2308 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2309 // candidate functions in the usual way.113) A given name can refer to one
2310 // or more function templates and also to a set of overloaded non-template
2311 // functions. In such a case, the candidate functions generated from each
2312 // function template are combined with the set of non-template candidate
2313 // functions.
2314 TemplateDeductionInfo Info(Context);
2315 FunctionDecl *Specialization = 0;
2316 if (TemplateDeductionResult Result
2317 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2318 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2319 Args, NumArgs, Specialization, Info)) {
2320 // FIXME: Record what happened with template argument deduction, so
2321 // that we can give the user a beautiful diagnostic.
2322 (void)Result;
2323 return;
2324 }
2325
2326 // Add the function template specialization produced by template argument
2327 // deduction as a candidate.
2328 assert(Specialization && "Missing member function template specialization?");
2329 assert(isa<CXXMethodDecl>(Specialization) &&
2330 "Specialization is not a member function?");
2331 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2332 CandidateSet, SuppressUserConversions, ForceRValue);
2333}
2334
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002335/// \brief Add a C++ function template specialization as a candidate
2336/// in the candidate set, using template argument deduction to produce
2337/// an appropriate function template specialization.
Douglas Gregore53060f2009-06-25 22:08:12 +00002338void
2339Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002340 bool HasExplicitTemplateArgs,
2341 const TemplateArgument *ExplicitTemplateArgs,
2342 unsigned NumExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002343 Expr **Args, unsigned NumArgs,
2344 OverloadCandidateSet& CandidateSet,
2345 bool SuppressUserConversions,
2346 bool ForceRValue) {
2347 // C++ [over.match.funcs]p7:
2348 // In each case where a candidate is a function template, candidate
2349 // function template specializations are generated using template argument
2350 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2351 // candidate functions in the usual way.113) A given name can refer to one
2352 // or more function templates and also to a set of overloaded non-template
2353 // functions. In such a case, the candidate functions generated from each
2354 // function template are combined with the set of non-template candidate
2355 // functions.
2356 TemplateDeductionInfo Info(Context);
2357 FunctionDecl *Specialization = 0;
2358 if (TemplateDeductionResult Result
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002359 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2360 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2361 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002362 // FIXME: Record what happened with template argument deduction, so
2363 // that we can give the user a beautiful diagnostic.
2364 (void)Result;
2365 return;
2366 }
2367
2368 // Add the function template specialization produced by template argument
2369 // deduction as a candidate.
2370 assert(Specialization && "Missing function template specialization?");
2371 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2372 SuppressUserConversions, ForceRValue);
2373}
2374
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002375/// AddConversionCandidate - Add a C++ conversion function as a
2376/// candidate in the candidate set (C++ [over.match.conv],
2377/// C++ [over.match.copy]). From is the expression we're converting from,
2378/// and ToType is the type that we're eventually trying to convert to
2379/// (which may or may not be the same type as the type that the
2380/// conversion function produces).
2381void
2382Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2383 Expr *From, QualType ToType,
2384 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002385 assert(!Conversion->getDescribedFunctionTemplate() &&
2386 "Conversion function templates use AddTemplateConversionCandidate");
2387
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002388 // Add this candidate
2389 CandidateSet.push_back(OverloadCandidate());
2390 OverloadCandidate& Candidate = CandidateSet.back();
2391 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002392 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002393 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002394 Candidate.FinalConversion.setAsIdentityConversion();
2395 Candidate.FinalConversion.FromTypePtr
2396 = Conversion->getConversionType().getAsOpaquePtr();
2397 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2398
Douglas Gregor96176b32008-11-18 23:14:02 +00002399 // Determine the implicit conversion sequence for the implicit
2400 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002401 Candidate.Viable = true;
2402 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002403 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002404
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002405 if (Candidate.Conversions[0].ConversionKind
2406 == ImplicitConversionSequence::BadConversion) {
2407 Candidate.Viable = false;
2408 return;
2409 }
2410
2411 // To determine what the conversion from the result of calling the
2412 // conversion function to the type we're eventually trying to
2413 // convert to (ToType), we need to synthesize a call to the
2414 // conversion function and attempt copy initialization from it. This
2415 // makes sure that we get the right semantics with respect to
2416 // lvalues/rvalues and the type. Fortunately, we can allocate this
2417 // call on the stack and we don't need its arguments to be
2418 // well-formed.
2419 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2420 SourceLocation());
2421 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002422 CastExpr::CK_Unknown,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002423 &ConversionRef, false);
Ted Kremenek668bf912009-02-09 20:51:47 +00002424
2425 // Note that it is safe to allocate CallExpr on the stack here because
2426 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2427 // allocator).
2428 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002429 Conversion->getConversionType().getNonReferenceType(),
2430 SourceLocation());
2431 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2432 switch (ICS.ConversionKind) {
2433 case ImplicitConversionSequence::StandardConversion:
2434 Candidate.FinalConversion = ICS.Standard;
2435 break;
2436
2437 case ImplicitConversionSequence::BadConversion:
2438 Candidate.Viable = false;
2439 break;
2440
2441 default:
2442 assert(false &&
2443 "Can only end up with a standard conversion sequence or failure");
2444 }
2445}
2446
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002447/// \brief Adds a conversion function template specialization
2448/// candidate to the overload set, using template argument deduction
2449/// to deduce the template arguments of the conversion function
2450/// template from the type that we are converting to (C++
2451/// [temp.deduct.conv]).
2452void
2453Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2454 Expr *From, QualType ToType,
2455 OverloadCandidateSet &CandidateSet) {
2456 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2457 "Only conversion function templates permitted here");
2458
2459 TemplateDeductionInfo Info(Context);
2460 CXXConversionDecl *Specialization = 0;
2461 if (TemplateDeductionResult Result
2462 = DeduceTemplateArguments(FunctionTemplate, ToType,
2463 Specialization, Info)) {
2464 // FIXME: Record what happened with template argument deduction, so
2465 // that we can give the user a beautiful diagnostic.
2466 (void)Result;
2467 return;
2468 }
2469
2470 // Add the conversion function template specialization produced by
2471 // template argument deduction as a candidate.
2472 assert(Specialization && "Missing function template specialization?");
2473 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2474}
2475
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002476/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2477/// converts the given @c Object to a function pointer via the
2478/// conversion function @c Conversion, and then attempts to call it
2479/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2480/// the type of function that we'll eventually be calling.
2481void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor72564e72009-02-26 23:50:07 +00002482 const FunctionProtoType *Proto,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002483 Expr *Object, Expr **Args, unsigned NumArgs,
2484 OverloadCandidateSet& CandidateSet) {
2485 CandidateSet.push_back(OverloadCandidate());
2486 OverloadCandidate& Candidate = CandidateSet.back();
2487 Candidate.Function = 0;
2488 Candidate.Surrogate = Conversion;
2489 Candidate.Viable = true;
2490 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002491 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002492 Candidate.Conversions.resize(NumArgs + 1);
2493
2494 // Determine the implicit conversion sequence for the implicit
2495 // object parameter.
2496 ImplicitConversionSequence ObjectInit
2497 = TryObjectArgumentInitialization(Object, Conversion);
2498 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2499 Candidate.Viable = false;
2500 return;
2501 }
2502
2503 // The first conversion is actually a user-defined conversion whose
2504 // first conversion is ObjectInit's standard conversion (which is
2505 // effectively a reference binding). Record it as such.
2506 Candidate.Conversions[0].ConversionKind
2507 = ImplicitConversionSequence::UserDefinedConversion;
2508 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2509 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2510 Candidate.Conversions[0].UserDefined.After
2511 = Candidate.Conversions[0].UserDefined.Before;
2512 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2513
2514 // Find the
2515 unsigned NumArgsInProto = Proto->getNumArgs();
2516
2517 // (C++ 13.3.2p2): A candidate function having fewer than m
2518 // parameters is viable only if it has an ellipsis in its parameter
2519 // list (8.3.5).
2520 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2521 Candidate.Viable = false;
2522 return;
2523 }
2524
2525 // Function types don't have any default arguments, so just check if
2526 // we have enough arguments.
2527 if (NumArgs < NumArgsInProto) {
2528 // Not enough arguments.
2529 Candidate.Viable = false;
2530 return;
2531 }
2532
2533 // Determine the implicit conversion sequences for each of the
2534 // arguments.
2535 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2536 if (ArgIdx < NumArgsInProto) {
2537 // (C++ 13.3.2p3): for F to be a viable function, there shall
2538 // exist for each argument an implicit conversion sequence
2539 // (13.3.3.1) that converts that argument to the corresponding
2540 // parameter of F.
2541 QualType ParamType = Proto->getArgType(ArgIdx);
2542 Candidate.Conversions[ArgIdx + 1]
2543 = TryCopyInitialization(Args[ArgIdx], ParamType,
2544 /*SuppressUserConversions=*/false);
2545 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2546 == ImplicitConversionSequence::BadConversion) {
2547 Candidate.Viable = false;
2548 break;
2549 }
2550 } else {
2551 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2552 // argument for which there is no corresponding parameter is
2553 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2554 Candidate.Conversions[ArgIdx + 1].ConversionKind
2555 = ImplicitConversionSequence::EllipsisConversion;
2556 }
2557 }
2558}
2559
Mike Stump390b4cc2009-05-16 07:39:55 +00002560// FIXME: This will eventually be removed, once we've migrated all of the
2561// operator overloading logic over to the scheme used by binary operators, which
2562// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002563void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002564 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002565 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002566 OverloadCandidateSet& CandidateSet,
2567 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002568
2569 FunctionSet Functions;
2570
2571 QualType T1 = Args[0]->getType();
2572 QualType T2;
2573 if (NumArgs > 1)
2574 T2 = Args[1]->getType();
2575
2576 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002577 if (S)
2578 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002579 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2580 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2581 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2582 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2583}
2584
2585/// \brief Add overload candidates for overloaded operators that are
2586/// member functions.
2587///
2588/// Add the overloaded operator candidates that are member functions
2589/// for the operator Op that was used in an operator expression such
2590/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2591/// CandidateSet will store the added overload candidates. (C++
2592/// [over.match.oper]).
2593void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2594 SourceLocation OpLoc,
2595 Expr **Args, unsigned NumArgs,
2596 OverloadCandidateSet& CandidateSet,
2597 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002598 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2599
2600 // C++ [over.match.oper]p3:
2601 // For a unary operator @ with an operand of a type whose
2602 // cv-unqualified version is T1, and for a binary operator @ with
2603 // a left operand of a type whose cv-unqualified version is T1 and
2604 // a right operand of a type whose cv-unqualified version is T2,
2605 // three sets of candidate functions, designated member
2606 // candidates, non-member candidates and built-in candidates, are
2607 // constructed as follows:
2608 QualType T1 = Args[0]->getType();
2609 QualType T2;
2610 if (NumArgs > 1)
2611 T2 = Args[1]->getType();
2612
2613 // -- If T1 is a class type, the set of member candidates is the
2614 // result of the qualified lookup of T1::operator@
2615 // (13.3.1.1.1); otherwise, the set of member candidates is
2616 // empty.
Douglas Gregor063daf62009-03-13 18:40:31 +00002617 // FIXME: Lookup in base classes, too!
Ted Kremenek6217b802009-07-29 21:53:49 +00002618 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002619 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002620 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002621 Oper != OperEnd; ++Oper)
2622 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2623 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002624 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002625 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002626}
2627
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002628/// AddBuiltinCandidate - Add a candidate for a built-in
2629/// operator. ResultTy and ParamTys are the result and parameter types
2630/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002631/// arguments being passed to the candidate. IsAssignmentOperator
2632/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002633/// operator. NumContextualBoolArguments is the number of arguments
2634/// (at the beginning of the argument list) that will be contextually
2635/// converted to bool.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002636void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2637 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002638 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002639 bool IsAssignmentOperator,
2640 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002641 // Add this candidate
2642 CandidateSet.push_back(OverloadCandidate());
2643 OverloadCandidate& Candidate = CandidateSet.back();
2644 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002645 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002646 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002647 Candidate.BuiltinTypes.ResultTy = ResultTy;
2648 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2649 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2650
2651 // Determine the implicit conversion sequences for each of the
2652 // arguments.
2653 Candidate.Viable = true;
2654 Candidate.Conversions.resize(NumArgs);
2655 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002656 // C++ [over.match.oper]p4:
2657 // For the built-in assignment operators, conversions of the
2658 // left operand are restricted as follows:
2659 // -- no temporaries are introduced to hold the left operand, and
2660 // -- no user-defined conversions are applied to the left
2661 // operand to achieve a type match with the left-most
2662 // parameter of a built-in candidate.
2663 //
2664 // We block these conversions by turning off user-defined
2665 // conversions, since that is the only way that initialization of
2666 // a reference to a non-class type can occur from something that
2667 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002668 if (ArgIdx < NumContextualBoolArguments) {
2669 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2670 "Contextual conversion to bool requires bool type");
2671 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2672 } else {
2673 Candidate.Conversions[ArgIdx]
2674 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2675 ArgIdx == 0 && IsAssignmentOperator);
2676 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002677 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002678 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002679 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002680 break;
2681 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002682 }
2683}
2684
2685/// BuiltinCandidateTypeSet - A set of types that will be used for the
2686/// candidate operator functions for built-in operators (C++
2687/// [over.built]). The types are separated into pointer types and
2688/// enumeration types.
2689class BuiltinCandidateTypeSet {
2690 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002691 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002692
2693 /// PointerTypes - The set of pointer types that will be used in the
2694 /// built-in candidates.
2695 TypeSet PointerTypes;
2696
Sebastian Redl78eb8742009-04-19 21:53:20 +00002697 /// MemberPointerTypes - The set of member pointer types that will be
2698 /// used in the built-in candidates.
2699 TypeSet MemberPointerTypes;
2700
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002701 /// EnumerationTypes - The set of enumeration types that will be
2702 /// used in the built-in candidates.
2703 TypeSet EnumerationTypes;
2704
Douglas Gregor5842ba92009-08-24 15:23:48 +00002705 /// Sema - The semantic analysis instance where we are building the
2706 /// candidate type set.
2707 Sema &SemaRef;
2708
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002709 /// Context - The AST context in which we will build the type sets.
2710 ASTContext &Context;
2711
Sebastian Redl78eb8742009-04-19 21:53:20 +00002712 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2713 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002714
2715public:
2716 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002717 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002718
Douglas Gregor5842ba92009-08-24 15:23:48 +00002719 BuiltinCandidateTypeSet(Sema &SemaRef)
2720 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002721
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002722 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2723 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002724
2725 /// pointer_begin - First pointer type found;
2726 iterator pointer_begin() { return PointerTypes.begin(); }
2727
Sebastian Redl78eb8742009-04-19 21:53:20 +00002728 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002729 iterator pointer_end() { return PointerTypes.end(); }
2730
Sebastian Redl78eb8742009-04-19 21:53:20 +00002731 /// member_pointer_begin - First member pointer type found;
2732 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2733
2734 /// member_pointer_end - Past the last member pointer type found;
2735 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2736
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002737 /// enumeration_begin - First enumeration type found;
2738 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2739
Sebastian Redl78eb8742009-04-19 21:53:20 +00002740 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002741 iterator enumeration_end() { return EnumerationTypes.end(); }
2742};
2743
Sebastian Redl78eb8742009-04-19 21:53:20 +00002744/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002745/// the set of pointer types along with any more-qualified variants of
2746/// that type. For example, if @p Ty is "int const *", this routine
2747/// will add "int const *", "int const volatile *", "int const
2748/// restrict *", and "int const volatile restrict *" to the set of
2749/// pointer types. Returns true if the add of @p Ty itself succeeded,
2750/// false otherwise.
Sebastian Redl78eb8742009-04-19 21:53:20 +00002751bool
2752BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002753 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002754 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002755 return false;
2756
Ted Kremenek6217b802009-07-29 21:53:49 +00002757 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002758 QualType PointeeTy = PointerTy->getPointeeType();
2759 // FIXME: Optimize this so that we don't keep trying to add the same types.
2760
Mike Stump390b4cc2009-05-16 07:39:55 +00002761 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2762 // pointer conversions that don't cast away constness?
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002763 if (!PointeeTy.isConstQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002764 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002765 (Context.getPointerType(PointeeTy.withConst()));
2766 if (!PointeeTy.isVolatileQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002767 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002768 (Context.getPointerType(PointeeTy.withVolatile()));
2769 if (!PointeeTy.isRestrictQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002770 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002771 (Context.getPointerType(PointeeTy.withRestrict()));
2772 }
2773
2774 return true;
2775}
2776
Sebastian Redl78eb8742009-04-19 21:53:20 +00002777/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2778/// to the set of pointer types along with any more-qualified variants of
2779/// that type. For example, if @p Ty is "int const *", this routine
2780/// will add "int const *", "int const volatile *", "int const
2781/// restrict *", and "int const volatile restrict *" to the set of
2782/// pointer types. Returns true if the add of @p Ty itself succeeded,
2783/// false otherwise.
2784bool
2785BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2786 QualType Ty) {
2787 // Insert this type.
2788 if (!MemberPointerTypes.insert(Ty))
2789 return false;
2790
Ted Kremenek6217b802009-07-29 21:53:49 +00002791 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl78eb8742009-04-19 21:53:20 +00002792 QualType PointeeTy = PointerTy->getPointeeType();
2793 const Type *ClassTy = PointerTy->getClass();
2794 // FIXME: Optimize this so that we don't keep trying to add the same types.
2795
2796 if (!PointeeTy.isConstQualified())
2797 AddMemberPointerWithMoreQualifiedTypeVariants
2798 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2799 if (!PointeeTy.isVolatileQualified())
2800 AddMemberPointerWithMoreQualifiedTypeVariants
2801 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2802 if (!PointeeTy.isRestrictQualified())
2803 AddMemberPointerWithMoreQualifiedTypeVariants
2804 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2805 }
2806
2807 return true;
2808}
2809
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002810/// AddTypesConvertedFrom - Add each of the types to which the type @p
2811/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00002812/// primarily interested in pointer types and enumeration types. We also
2813/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002814/// AllowUserConversions is true if we should look at the conversion
2815/// functions of a class type, and AllowExplicitConversions if we
2816/// should also include the explicit conversion functions of a class
2817/// type.
2818void
2819BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2820 bool AllowUserConversions,
2821 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002822 // Only deal with canonical types.
2823 Ty = Context.getCanonicalType(Ty);
2824
2825 // Look through reference types; they aren't part of the type of an
2826 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00002827 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002828 Ty = RefTy->getPointeeType();
2829
2830 // We don't care about qualifiers on the type.
2831 Ty = Ty.getUnqualifiedType();
2832
Ted Kremenek6217b802009-07-29 21:53:49 +00002833 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002834 QualType PointeeTy = PointerTy->getPointeeType();
2835
2836 // Insert our type, and its more-qualified variants, into the set
2837 // of types.
Sebastian Redl78eb8742009-04-19 21:53:20 +00002838 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002839 return;
2840
2841 // Add 'cv void*' to our set of types.
2842 if (!Ty->isVoidType()) {
2843 QualType QualVoid
2844 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl78eb8742009-04-19 21:53:20 +00002845 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002846 }
2847
2848 // If this is a pointer to a class type, add pointers to its bases
2849 // (with the same level of cv-qualification as the original
2850 // derived class, of course).
Ted Kremenek6217b802009-07-29 21:53:49 +00002851 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002852 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2853 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2854 Base != ClassDecl->bases_end(); ++Base) {
2855 QualType BaseTy = Context.getCanonicalType(Base->getType());
2856 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2857
2858 // Add the pointer type, recursively, so that we get all of
2859 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002860 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002861 }
2862 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00002863 } else if (Ty->isMemberPointerType()) {
2864 // Member pointers are far easier, since the pointee can't be converted.
2865 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2866 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002867 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00002868 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002869 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002870 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002871 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2872 // No conversion functions in incomplete types.
2873 return;
2874 }
2875
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002876 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2877 // FIXME: Visit conversion functions in the base classes, too.
2878 OverloadedFunctionDecl *Conversions
2879 = ClassDecl->getConversionFunctions();
2880 for (OverloadedFunctionDecl::function_iterator Func
2881 = Conversions->function_begin();
2882 Func != Conversions->function_end(); ++Func) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002883 CXXConversionDecl *Conv;
2884 FunctionTemplateDecl *ConvTemplate;
2885 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2886
2887 // Skip conversion function templates; they don't tell us anything
2888 // about which builtin types we can convert to.
2889 if (ConvTemplate)
2890 continue;
2891
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002892 if (AllowExplicitConversions || !Conv->isExplicit())
2893 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002894 }
2895 }
2896 }
2897}
2898
Douglas Gregor19b7b152009-08-24 13:43:27 +00002899/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2900/// the volatile- and non-volatile-qualified assignment operators for the
2901/// given type to the candidate set.
2902static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2903 QualType T,
2904 Expr **Args,
2905 unsigned NumArgs,
2906 OverloadCandidateSet &CandidateSet) {
2907 QualType ParamTypes[2];
2908
2909 // T& operator=(T&, T)
2910 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2911 ParamTypes[1] = T;
2912 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2913 /*IsAssignmentOperator=*/true);
2914
2915 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2916 // volatile T& operator=(volatile T&, T)
2917 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2918 ParamTypes[1] = T;
2919 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2920 /*IsAssignmentOperator=*/true);
2921 }
2922}
2923
Douglas Gregor74253732008-11-19 15:42:04 +00002924/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2925/// operator overloads to the candidate set (C++ [over.built]), based
2926/// on the operator @p Op and the arguments given. For example, if the
2927/// operator is a binary '+', this routine might add "int
2928/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002929void
Douglas Gregor74253732008-11-19 15:42:04 +00002930Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2931 Expr **Args, unsigned NumArgs,
2932 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002933 // The set of "promoted arithmetic types", which are the arithmetic
2934 // types are that preserved by promotion (C++ [over.built]p2). Note
2935 // that the first few of these types are the promoted integral
2936 // types; these types need to be first.
2937 // FIXME: What about complex?
2938 const unsigned FirstIntegralType = 0;
2939 const unsigned LastIntegralType = 13;
2940 const unsigned FirstPromotedIntegralType = 7,
2941 LastPromotedIntegralType = 13;
2942 const unsigned FirstPromotedArithmeticType = 7,
2943 LastPromotedArithmeticType = 16;
2944 const unsigned NumArithmeticTypes = 16;
2945 QualType ArithmeticTypes[NumArithmeticTypes] = {
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002946 Context.BoolTy, Context.CharTy, Context.WCharTy,
Douglas Gregor19b7b152009-08-24 13:43:27 +00002947// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002948 Context.SignedCharTy, Context.ShortTy,
2949 Context.UnsignedCharTy, Context.UnsignedShortTy,
2950 Context.IntTy, Context.LongTy, Context.LongLongTy,
2951 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2952 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2953 };
2954
2955 // Find all of the types that the arguments can convert to, but only
2956 // if the operator we're looking at has built-in operator candidates
2957 // that make use of these types.
Douglas Gregor5842ba92009-08-24 15:23:48 +00002958 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002959 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2960 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002961 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002962 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002963 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002964 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00002965 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002966 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2967 true,
2968 (Op == OO_Exclaim ||
2969 Op == OO_AmpAmp ||
2970 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002971 }
2972
2973 bool isComparison = false;
2974 switch (Op) {
2975 case OO_None:
2976 case NUM_OVERLOADED_OPERATORS:
2977 assert(false && "Expected an overloaded operator");
2978 break;
2979
Douglas Gregor74253732008-11-19 15:42:04 +00002980 case OO_Star: // '*' is either unary or binary
2981 if (NumArgs == 1)
2982 goto UnaryStar;
2983 else
2984 goto BinaryStar;
2985 break;
2986
2987 case OO_Plus: // '+' is either unary or binary
2988 if (NumArgs == 1)
2989 goto UnaryPlus;
2990 else
2991 goto BinaryPlus;
2992 break;
2993
2994 case OO_Minus: // '-' is either unary or binary
2995 if (NumArgs == 1)
2996 goto UnaryMinus;
2997 else
2998 goto BinaryMinus;
2999 break;
3000
3001 case OO_Amp: // '&' is either unary or binary
3002 if (NumArgs == 1)
3003 goto UnaryAmp;
3004 else
3005 goto BinaryAmp;
3006
3007 case OO_PlusPlus:
3008 case OO_MinusMinus:
3009 // C++ [over.built]p3:
3010 //
3011 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3012 // is either volatile or empty, there exist candidate operator
3013 // functions of the form
3014 //
3015 // VQ T& operator++(VQ T&);
3016 // T operator++(VQ T&, int);
3017 //
3018 // C++ [over.built]p4:
3019 //
3020 // For every pair (T, VQ), where T is an arithmetic type other
3021 // than bool, and VQ is either volatile or empty, there exist
3022 // candidate operator functions of the form
3023 //
3024 // VQ T& operator--(VQ T&);
3025 // T operator--(VQ T&, int);
3026 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3027 Arith < NumArithmeticTypes; ++Arith) {
3028 QualType ArithTy = ArithmeticTypes[Arith];
3029 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003030 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003031
3032 // Non-volatile version.
3033 if (NumArgs == 1)
3034 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3035 else
3036 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3037
3038 // Volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003039 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00003040 if (NumArgs == 1)
3041 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3042 else
3043 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3044 }
3045
3046 // C++ [over.built]p5:
3047 //
3048 // For every pair (T, VQ), where T is a cv-qualified or
3049 // cv-unqualified object type, and VQ is either volatile or
3050 // empty, there exist candidate operator functions of the form
3051 //
3052 // T*VQ& operator++(T*VQ&);
3053 // T*VQ& operator--(T*VQ&);
3054 // T* operator++(T*VQ&, int);
3055 // T* operator--(T*VQ&, int);
3056 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3057 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3058 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003059 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003060 continue;
3061
3062 QualType ParamTypes[2] = {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003063 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003064 };
3065
3066 // Without volatile
3067 if (NumArgs == 1)
3068 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3069 else
3070 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3071
3072 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3073 // With volatile
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003074 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00003075 if (NumArgs == 1)
3076 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3077 else
3078 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3079 }
3080 }
3081 break;
3082
3083 UnaryStar:
3084 // C++ [over.built]p6:
3085 // For every cv-qualified or cv-unqualified object type T, there
3086 // exist candidate operator functions of the form
3087 //
3088 // T& operator*(T*);
3089 //
3090 // C++ [over.built]p7:
3091 // For every function type T, there exist candidate operator
3092 // functions of the form
3093 // T& operator*(T*);
3094 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3095 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3096 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003097 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003098 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003099 &ParamTy, Args, 1, CandidateSet);
3100 }
3101 break;
3102
3103 UnaryPlus:
3104 // C++ [over.built]p8:
3105 // For every type T, there exist candidate operator functions of
3106 // the form
3107 //
3108 // T* operator+(T*);
3109 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3110 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3111 QualType ParamTy = *Ptr;
3112 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3113 }
3114
3115 // Fall through
3116
3117 UnaryMinus:
3118 // C++ [over.built]p9:
3119 // For every promoted arithmetic type T, there exist candidate
3120 // operator functions of the form
3121 //
3122 // T operator+(T);
3123 // T operator-(T);
3124 for (unsigned Arith = FirstPromotedArithmeticType;
3125 Arith < LastPromotedArithmeticType; ++Arith) {
3126 QualType ArithTy = ArithmeticTypes[Arith];
3127 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3128 }
3129 break;
3130
3131 case OO_Tilde:
3132 // C++ [over.built]p10:
3133 // For every promoted integral type T, there exist candidate
3134 // operator functions of the form
3135 //
3136 // T operator~(T);
3137 for (unsigned Int = FirstPromotedIntegralType;
3138 Int < LastPromotedIntegralType; ++Int) {
3139 QualType IntTy = ArithmeticTypes[Int];
3140 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3141 }
3142 break;
3143
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003144 case OO_New:
3145 case OO_Delete:
3146 case OO_Array_New:
3147 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003148 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003149 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003150 break;
3151
3152 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003153 UnaryAmp:
3154 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003155 // C++ [over.match.oper]p3:
3156 // -- For the operator ',', the unary operator '&', or the
3157 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003158 break;
3159
Douglas Gregor19b7b152009-08-24 13:43:27 +00003160 case OO_EqualEqual:
3161 case OO_ExclaimEqual:
3162 // C++ [over.match.oper]p16:
3163 // For every pointer to member type T, there exist candidate operator
3164 // functions of the form
3165 //
3166 // bool operator==(T,T);
3167 // bool operator!=(T,T);
3168 for (BuiltinCandidateTypeSet::iterator
3169 MemPtr = CandidateTypes.member_pointer_begin(),
3170 MemPtrEnd = CandidateTypes.member_pointer_end();
3171 MemPtr != MemPtrEnd;
3172 ++MemPtr) {
3173 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3174 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3175 }
3176
3177 // Fall through
3178
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003179 case OO_Less:
3180 case OO_Greater:
3181 case OO_LessEqual:
3182 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003183 // C++ [over.built]p15:
3184 //
3185 // For every pointer or enumeration type T, there exist
3186 // candidate operator functions of the form
3187 //
3188 // bool operator<(T, T);
3189 // bool operator>(T, T);
3190 // bool operator<=(T, T);
3191 // bool operator>=(T, T);
3192 // bool operator==(T, T);
3193 // bool operator!=(T, T);
3194 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3195 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3196 QualType ParamTypes[2] = { *Ptr, *Ptr };
3197 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3198 }
3199 for (BuiltinCandidateTypeSet::iterator Enum
3200 = CandidateTypes.enumeration_begin();
3201 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3202 QualType ParamTypes[2] = { *Enum, *Enum };
3203 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3204 }
3205
3206 // Fall through.
3207 isComparison = true;
3208
Douglas Gregor74253732008-11-19 15:42:04 +00003209 BinaryPlus:
3210 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003211 if (!isComparison) {
3212 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3213
3214 // C++ [over.built]p13:
3215 //
3216 // For every cv-qualified or cv-unqualified object type T
3217 // there exist candidate operator functions of the form
3218 //
3219 // T* operator+(T*, ptrdiff_t);
3220 // T& operator[](T*, ptrdiff_t); [BELOW]
3221 // T* operator-(T*, ptrdiff_t);
3222 // T* operator+(ptrdiff_t, T*);
3223 // T& operator[](ptrdiff_t, T*); [BELOW]
3224 //
3225 // C++ [over.built]p14:
3226 //
3227 // For every T, where T is a pointer to object type, there
3228 // exist candidate operator functions of the form
3229 //
3230 // ptrdiff_t operator-(T, T);
3231 for (BuiltinCandidateTypeSet::iterator Ptr
3232 = CandidateTypes.pointer_begin();
3233 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3234 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3235
3236 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3237 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3238
3239 if (Op == OO_Plus) {
3240 // T* operator+(ptrdiff_t, T*);
3241 ParamTypes[0] = ParamTypes[1];
3242 ParamTypes[1] = *Ptr;
3243 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3244 } else {
3245 // ptrdiff_t operator-(T, T);
3246 ParamTypes[1] = *Ptr;
3247 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3248 Args, 2, CandidateSet);
3249 }
3250 }
3251 }
3252 // Fall through
3253
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003254 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003255 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003256 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003257 // C++ [over.built]p12:
3258 //
3259 // For every pair of promoted arithmetic types L and R, there
3260 // exist candidate operator functions of the form
3261 //
3262 // LR operator*(L, R);
3263 // LR operator/(L, R);
3264 // LR operator+(L, R);
3265 // LR operator-(L, R);
3266 // bool operator<(L, R);
3267 // bool operator>(L, R);
3268 // bool operator<=(L, R);
3269 // bool operator>=(L, R);
3270 // bool operator==(L, R);
3271 // bool operator!=(L, R);
3272 //
3273 // where LR is the result of the usual arithmetic conversions
3274 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003275 //
3276 // C++ [over.built]p24:
3277 //
3278 // For every pair of promoted arithmetic types L and R, there exist
3279 // candidate operator functions of the form
3280 //
3281 // LR operator?(bool, L, R);
3282 //
3283 // where LR is the result of the usual arithmetic conversions
3284 // between types L and R.
3285 // Our candidates ignore the first parameter.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003286 for (unsigned Left = FirstPromotedArithmeticType;
3287 Left < LastPromotedArithmeticType; ++Left) {
3288 for (unsigned Right = FirstPromotedArithmeticType;
3289 Right < LastPromotedArithmeticType; ++Right) {
3290 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003291 QualType Result
3292 = isComparison
3293 ? Context.BoolTy
3294 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003295 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3296 }
3297 }
3298 break;
3299
3300 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003301 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003302 case OO_Caret:
3303 case OO_Pipe:
3304 case OO_LessLess:
3305 case OO_GreaterGreater:
3306 // C++ [over.built]p17:
3307 //
3308 // For every pair of promoted integral types L and R, there
3309 // exist candidate operator functions of the form
3310 //
3311 // LR operator%(L, R);
3312 // LR operator&(L, R);
3313 // LR operator^(L, R);
3314 // LR operator|(L, R);
3315 // L operator<<(L, R);
3316 // L operator>>(L, R);
3317 //
3318 // where LR is the result of the usual arithmetic conversions
3319 // between types L and R.
3320 for (unsigned Left = FirstPromotedIntegralType;
3321 Left < LastPromotedIntegralType; ++Left) {
3322 for (unsigned Right = FirstPromotedIntegralType;
3323 Right < LastPromotedIntegralType; ++Right) {
3324 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3325 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3326 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003327 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003328 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3329 }
3330 }
3331 break;
3332
3333 case OO_Equal:
3334 // C++ [over.built]p20:
3335 //
3336 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003337 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003338 // empty, there exist candidate operator functions of the form
3339 //
3340 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003341 for (BuiltinCandidateTypeSet::iterator
3342 Enum = CandidateTypes.enumeration_begin(),
3343 EnumEnd = CandidateTypes.enumeration_end();
3344 Enum != EnumEnd; ++Enum)
3345 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3346 CandidateSet);
3347 for (BuiltinCandidateTypeSet::iterator
3348 MemPtr = CandidateTypes.member_pointer_begin(),
3349 MemPtrEnd = CandidateTypes.member_pointer_end();
3350 MemPtr != MemPtrEnd; ++MemPtr)
3351 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3352 CandidateSet);
3353 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003354
3355 case OO_PlusEqual:
3356 case OO_MinusEqual:
3357 // C++ [over.built]p19:
3358 //
3359 // For every pair (T, VQ), where T is any type and VQ is either
3360 // volatile or empty, there exist candidate operator functions
3361 // of the form
3362 //
3363 // T*VQ& operator=(T*VQ&, T*);
3364 //
3365 // C++ [over.built]p21:
3366 //
3367 // For every pair (T, VQ), where T is a cv-qualified or
3368 // cv-unqualified object type and VQ is either volatile or
3369 // empty, there exist candidate operator functions of the form
3370 //
3371 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3372 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3373 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3374 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3375 QualType ParamTypes[2];
3376 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3377
3378 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003379 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003380 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3381 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003382
Douglas Gregor74253732008-11-19 15:42:04 +00003383 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3384 // volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003385 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003386 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3387 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003388 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003389 }
3390 // Fall through.
3391
3392 case OO_StarEqual:
3393 case OO_SlashEqual:
3394 // C++ [over.built]p18:
3395 //
3396 // For every triple (L, VQ, R), where L is an arithmetic type,
3397 // VQ is either volatile or empty, and R is a promoted
3398 // arithmetic type, there exist candidate operator functions of
3399 // the form
3400 //
3401 // VQ L& operator=(VQ L&, R);
3402 // VQ L& operator*=(VQ L&, R);
3403 // VQ L& operator/=(VQ L&, R);
3404 // VQ L& operator+=(VQ L&, R);
3405 // VQ L& operator-=(VQ L&, R);
3406 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3407 for (unsigned Right = FirstPromotedArithmeticType;
3408 Right < LastPromotedArithmeticType; ++Right) {
3409 QualType ParamTypes[2];
3410 ParamTypes[1] = ArithmeticTypes[Right];
3411
3412 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003413 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003414 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3415 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003416
3417 // Add this built-in operator as a candidate (VQ is 'volatile').
3418 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003419 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003420 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3421 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003422 }
3423 }
3424 break;
3425
3426 case OO_PercentEqual:
3427 case OO_LessLessEqual:
3428 case OO_GreaterGreaterEqual:
3429 case OO_AmpEqual:
3430 case OO_CaretEqual:
3431 case OO_PipeEqual:
3432 // C++ [over.built]p22:
3433 //
3434 // For every triple (L, VQ, R), where L is an integral type, VQ
3435 // is either volatile or empty, and R is a promoted integral
3436 // type, there exist candidate operator functions of the form
3437 //
3438 // VQ L& operator%=(VQ L&, R);
3439 // VQ L& operator<<=(VQ L&, R);
3440 // VQ L& operator>>=(VQ L&, R);
3441 // VQ L& operator&=(VQ L&, R);
3442 // VQ L& operator^=(VQ L&, R);
3443 // VQ L& operator|=(VQ L&, R);
3444 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3445 for (unsigned Right = FirstPromotedIntegralType;
3446 Right < LastPromotedIntegralType; ++Right) {
3447 QualType ParamTypes[2];
3448 ParamTypes[1] = ArithmeticTypes[Right];
3449
3450 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003451 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003452 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3453
3454 // Add this built-in operator as a candidate (VQ is 'volatile').
3455 ParamTypes[0] = ArithmeticTypes[Left];
3456 ParamTypes[0].addVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003457 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003458 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3459 }
3460 }
3461 break;
3462
Douglas Gregor74253732008-11-19 15:42:04 +00003463 case OO_Exclaim: {
3464 // C++ [over.operator]p23:
3465 //
3466 // There also exist candidate operator functions of the form
3467 //
3468 // bool operator!(bool);
3469 // bool operator&&(bool, bool); [BELOW]
3470 // bool operator||(bool, bool); [BELOW]
3471 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003472 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3473 /*IsAssignmentOperator=*/false,
3474 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003475 break;
3476 }
3477
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003478 case OO_AmpAmp:
3479 case OO_PipePipe: {
3480 // C++ [over.operator]p23:
3481 //
3482 // There also exist candidate operator functions of the form
3483 //
Douglas Gregor74253732008-11-19 15:42:04 +00003484 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003485 // bool operator&&(bool, bool);
3486 // bool operator||(bool, bool);
3487 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003488 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3489 /*IsAssignmentOperator=*/false,
3490 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003491 break;
3492 }
3493
3494 case OO_Subscript:
3495 // C++ [over.built]p13:
3496 //
3497 // For every cv-qualified or cv-unqualified object type T there
3498 // exist candidate operator functions of the form
3499 //
3500 // T* operator+(T*, ptrdiff_t); [ABOVE]
3501 // T& operator[](T*, ptrdiff_t);
3502 // T* operator-(T*, ptrdiff_t); [ABOVE]
3503 // T* operator+(ptrdiff_t, T*); [ABOVE]
3504 // T& operator[](ptrdiff_t, T*);
3505 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3506 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3507 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00003508 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003509 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003510
3511 // T& operator[](T*, ptrdiff_t)
3512 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3513
3514 // T& operator[](ptrdiff_t, T*);
3515 ParamTypes[0] = ParamTypes[1];
3516 ParamTypes[1] = *Ptr;
3517 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3518 }
3519 break;
3520
3521 case OO_ArrowStar:
3522 // FIXME: No support for pointer-to-members yet.
3523 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003524
3525 case OO_Conditional:
3526 // Note that we don't consider the first argument, since it has been
3527 // contextually converted to bool long ago. The candidates below are
3528 // therefore added as binary.
3529 //
3530 // C++ [over.built]p24:
3531 // For every type T, where T is a pointer or pointer-to-member type,
3532 // there exist candidate operator functions of the form
3533 //
3534 // T operator?(bool, T, T);
3535 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003536 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3537 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3538 QualType ParamTypes[2] = { *Ptr, *Ptr };
3539 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3540 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00003541 for (BuiltinCandidateTypeSet::iterator Ptr =
3542 CandidateTypes.member_pointer_begin(),
3543 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3544 QualType ParamTypes[2] = { *Ptr, *Ptr };
3545 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3546 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003547 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003548 }
3549}
3550
Douglas Gregorfa047642009-02-04 00:32:51 +00003551/// \brief Add function candidates found via argument-dependent lookup
3552/// to the set of overloading candidates.
3553///
3554/// This routine performs argument-dependent name lookup based on the
3555/// given function name (which may also be an operator name) and adds
3556/// all of the overload candidates found by ADL to the overload
3557/// candidate set (C++ [basic.lookup.argdep]).
3558void
3559Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3560 Expr **Args, unsigned NumArgs,
3561 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003562 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00003563
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003564 // Record all of the function candidates that we've already
3565 // added to the overload set, so that we don't add those same
3566 // candidates a second time.
3567 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3568 CandEnd = CandidateSet.end();
3569 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003570 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003571 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003572 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3573 Functions.insert(FunTmpl);
3574 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003575
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003576 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00003577
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003578 // Erase all of the candidates we already knew about.
3579 // FIXME: This is suboptimal. Is there a better way?
3580 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3581 CandEnd = CandidateSet.end();
3582 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003583 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003584 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003585 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3586 Functions.erase(FunTmpl);
3587 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003588
3589 // For each of the ADL candidates we found, add it to the overload
3590 // set.
3591 for (FunctionSet::iterator Func = Functions.begin(),
3592 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00003593 Func != FuncEnd; ++Func) {
3594 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3595 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3596 else
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003597 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3598 /*FIXME: explicit args */false, 0, 0,
3599 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00003600 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003601}
3602
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003603/// isBetterOverloadCandidate - Determines whether the first overload
3604/// candidate is a better candidate than the second (C++ 13.3.3p1).
3605bool
3606Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3607 const OverloadCandidate& Cand2)
3608{
3609 // Define viable functions to be better candidates than non-viable
3610 // functions.
3611 if (!Cand2.Viable)
3612 return Cand1.Viable;
3613 else if (!Cand1.Viable)
3614 return false;
3615
Douglas Gregor88a35142008-12-22 05:46:06 +00003616 // C++ [over.match.best]p1:
3617 //
3618 // -- if F is a static member function, ICS1(F) is defined such
3619 // that ICS1(F) is neither better nor worse than ICS1(G) for
3620 // any function G, and, symmetrically, ICS1(G) is neither
3621 // better nor worse than ICS1(F).
3622 unsigned StartArg = 0;
3623 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3624 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003625
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003626 // C++ [over.match.best]p1:
3627 // A viable function F1 is defined to be a better function than another
3628 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3629 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003630 unsigned NumArgs = Cand1.Conversions.size();
3631 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3632 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003633 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003634 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3635 Cand2.Conversions[ArgIdx])) {
3636 case ImplicitConversionSequence::Better:
3637 // Cand1 has a better conversion sequence.
3638 HasBetterConversion = true;
3639 break;
3640
3641 case ImplicitConversionSequence::Worse:
3642 // Cand1 can't be better than Cand2.
3643 return false;
3644
3645 case ImplicitConversionSequence::Indistinguishable:
3646 // Do nothing.
3647 break;
3648 }
3649 }
3650
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003651 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3652 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003653 if (HasBetterConversion)
3654 return true;
3655
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003656 // - F1 is a non-template function and F2 is a function template
3657 // specialization, or, if not that,
3658 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3659 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3660 return true;
3661
3662 // -- F1 and F2 are function template specializations, and the function
3663 // template for F1 is more specialized than the template for F2
3664 // according to the partial ordering rules described in 14.5.5.2, or,
3665 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00003666 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3667 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003668 if (FunctionTemplateDecl *BetterTemplate
3669 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3670 Cand2.Function->getPrimaryTemplate(),
3671 true))
3672 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003673
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003674 // -- the context is an initialization by user-defined conversion
3675 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3676 // from the return type of F1 to the destination type (i.e.,
3677 // the type of the entity being initialized) is a better
3678 // conversion sequence than the standard conversion sequence
3679 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003680 if (Cand1.Function && Cand2.Function &&
3681 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003682 isa<CXXConversionDecl>(Cand2.Function)) {
3683 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3684 Cand2.FinalConversion)) {
3685 case ImplicitConversionSequence::Better:
3686 // Cand1 has a better conversion sequence.
3687 return true;
3688
3689 case ImplicitConversionSequence::Worse:
3690 // Cand1 can't be better than Cand2.
3691 return false;
3692
3693 case ImplicitConversionSequence::Indistinguishable:
3694 // Do nothing
3695 break;
3696 }
3697 }
3698
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003699 return false;
3700}
3701
Douglas Gregore0762c92009-06-19 23:52:42 +00003702/// \brief Computes the best viable function (C++ 13.3.3)
3703/// within an overload candidate set.
3704///
3705/// \param CandidateSet the set of candidate functions.
3706///
3707/// \param Loc the location of the function name (or operator symbol) for
3708/// which overload resolution occurs.
3709///
3710/// \param Best f overload resolution was successful or found a deleted
3711/// function, Best points to the candidate function found.
3712///
3713/// \returns The result of overload resolution.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003714Sema::OverloadingResult
3715Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregore0762c92009-06-19 23:52:42 +00003716 SourceLocation Loc,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003717 OverloadCandidateSet::iterator& Best)
3718{
3719 // Find the best viable function.
3720 Best = CandidateSet.end();
3721 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3722 Cand != CandidateSet.end(); ++Cand) {
3723 if (Cand->Viable) {
3724 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3725 Best = Cand;
3726 }
3727 }
3728
3729 // If we didn't find any viable functions, abort.
3730 if (Best == CandidateSet.end())
3731 return OR_No_Viable_Function;
3732
3733 // Make sure that this function is better than every other viable
3734 // function. If not, we have an ambiguity.
3735 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3736 Cand != CandidateSet.end(); ++Cand) {
3737 if (Cand->Viable &&
3738 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003739 !isBetterOverloadCandidate(*Best, *Cand)) {
3740 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003741 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003742 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003743 }
3744
3745 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003746 if (Best->Function &&
3747 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003748 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003749 return OR_Deleted;
3750
Douglas Gregore0762c92009-06-19 23:52:42 +00003751 // C++ [basic.def.odr]p2:
3752 // An overloaded function is used if it is selected by overload resolution
3753 // when referred to from a potentially-evaluated expression. [Note: this
3754 // covers calls to named functions (5.2.2), operator overloading
3755 // (clause 13), user-defined conversions (12.3.2), allocation function for
3756 // placement new (5.3.4), as well as non-default initialization (8.5).
3757 if (Best->Function)
3758 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003759 return OR_Success;
3760}
3761
3762/// PrintOverloadCandidates - When overload resolution fails, prints
3763/// diagnostic messages containing the candidates in the candidate
3764/// set. If OnlyViable is true, only viable candidates will be printed.
3765void
3766Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3767 bool OnlyViable)
3768{
3769 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3770 LastCand = CandidateSet.end();
3771 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003772 if (Cand->Viable || !OnlyViable) {
3773 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003774 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003775 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003776 // Deleted or "unavailable" function.
3777 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3778 << Cand->Function->isDeleted();
3779 } else {
3780 // Normal function
3781 // FIXME: Give a better reason!
3782 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3783 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003784 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003785 // Desugar the type of the surrogate down to a function type,
3786 // retaining as many typedefs as possible while still showing
3787 // the function type (and, therefore, its parameter types).
3788 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003789 bool isLValueReference = false;
3790 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00003791 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003792 if (const LValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00003793 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003794 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003795 isLValueReference = true;
3796 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00003797 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003798 FnType = FnTypeRef->getPointeeType();
3799 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00003800 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003801 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003802 FnType = FnTypePtr->getPointeeType();
3803 isPointer = true;
3804 }
3805 // Desugar down to a function type.
3806 FnType = QualType(FnType->getAsFunctionType(), 0);
3807 // Reconstruct the pointer/reference as appropriate.
3808 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003809 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3810 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00003811
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003812 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003813 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003814 } else {
3815 // FIXME: We need to get the identifier in here
Mike Stump390b4cc2009-05-16 07:39:55 +00003816 // FIXME: Do we want the error message to point at the operator?
3817 // (built-ins won't have a location)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003818 QualType FnType
3819 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3820 Cand->BuiltinTypes.ParamTypes,
3821 Cand->Conversions.size(),
3822 false, 0);
3823
Chris Lattnerd1625842008-11-24 06:25:27 +00003824 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003825 }
3826 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003827 }
3828}
3829
Douglas Gregor904eed32008-11-10 20:40:00 +00003830/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3831/// an overloaded function (C++ [over.over]), where @p From is an
3832/// expression with overloaded function type and @p ToType is the type
3833/// we're trying to resolve to. For example:
3834///
3835/// @code
3836/// int f(double);
3837/// int f(int);
3838///
3839/// int (*pfd)(double) = f; // selects f(double)
3840/// @endcode
3841///
3842/// This routine returns the resulting FunctionDecl if it could be
3843/// resolved, and NULL otherwise. When @p Complain is true, this
3844/// routine will emit diagnostics if there is an error.
3845FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00003846Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003847 bool Complain) {
3848 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003849 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00003850 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00003851 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003852 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00003853 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00003854 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00003855 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00003856 FunctionType = MemTypePtr->getPointeeType();
3857 IsMember = true;
3858 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003859
3860 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00003861 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00003862 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00003863 return 0;
3864
3865 // Find the actual overloaded function declaration.
3866 OverloadedFunctionDecl *Ovl = 0;
3867
3868 // C++ [over.over]p1:
3869 // [...] [Note: any redundant set of parentheses surrounding the
3870 // overloaded function name is ignored (5.1). ]
3871 Expr *OvlExpr = From->IgnoreParens();
3872
3873 // C++ [over.over]p1:
3874 // [...] The overloaded function name can be preceded by the &
3875 // operator.
3876 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3877 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3878 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3879 }
3880
3881 // Try to dig out the overloaded function.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003882 FunctionTemplateDecl *FunctionTemplate = 0;
3883 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003884 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor83314aa2009-07-08 20:55:45 +00003885 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3886 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003887
Douglas Gregor83314aa2009-07-08 20:55:45 +00003888 // If there's no overloaded function declaration or function template,
3889 // we're done.
3890 if (!Ovl && !FunctionTemplate)
Douglas Gregor904eed32008-11-10 20:40:00 +00003891 return 0;
3892
Douglas Gregor83314aa2009-07-08 20:55:45 +00003893 OverloadIterator Fun;
3894 if (Ovl)
3895 Fun = Ovl;
3896 else
3897 Fun = FunctionTemplate;
3898
Douglas Gregor904eed32008-11-10 20:40:00 +00003899 // Look through all of the overloaded functions, searching for one
3900 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00003901 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3902
3903 bool FoundNonTemplateFunction = false;
Douglas Gregor83314aa2009-07-08 20:55:45 +00003904 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003905 // C++ [over.over]p3:
3906 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00003907 // targets of type "pointer-to-function" or "reference-to-function."
3908 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00003909 // type "pointer-to-member-function."
3910 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003911
3912 if (FunctionTemplateDecl *FunctionTemplate
3913 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregor00aeb522009-07-08 23:33:52 +00003914 if (CXXMethodDecl *Method
3915 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3916 // Skip non-static function templates when converting to pointer, and
3917 // static when converting to member pointer.
3918 if (Method->isStatic() == IsMember)
3919 continue;
3920 } else if (IsMember)
3921 continue;
3922
3923 // C++ [over.over]p2:
3924 // If the name is a function template, template argument deduction is
3925 // done (14.8.2.2), and if the argument deduction succeeds, the
3926 // resulting template argument list is used to generate a single
3927 // function template specialization, which is added to the set of
3928 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003929 FunctionDecl *Specialization = 0;
3930 TemplateDeductionInfo Info(Context);
3931 if (TemplateDeductionResult Result
3932 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3933 /*FIXME:*/0, /*FIXME:*/0,
3934 FunctionType, Specialization, Info)) {
3935 // FIXME: make a note of the failed deduction for diagnostics.
3936 (void)Result;
3937 } else {
3938 assert(FunctionType
3939 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00003940 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003941 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00003942 }
3943 }
3944
Sebastian Redl33b399a2009-02-04 21:23:32 +00003945 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3946 // Skip non-static functions when converting to pointer, and static
3947 // when converting to member pointer.
3948 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00003949 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00003950 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00003951 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00003952
Douglas Gregore53060f2009-06-25 22:08:12 +00003953 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregor00aeb522009-07-08 23:33:52 +00003954 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003955 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00003956 FoundNonTemplateFunction = true;
3957 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00003958 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003959 }
3960
Douglas Gregor00aeb522009-07-08 23:33:52 +00003961 // If there were 0 or 1 matches, we're done.
3962 if (Matches.empty())
3963 return 0;
3964 else if (Matches.size() == 1)
3965 return *Matches.begin();
3966
3967 // C++ [over.over]p4:
3968 // If more than one function is selected, [...]
3969 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003970 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor00aeb522009-07-08 23:33:52 +00003971 if (FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003972 // [...] any function template specializations in the set are
3973 // eliminated if the set also contains a non-template function, [...]
3974 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregor00aeb522009-07-08 23:33:52 +00003975 if ((*M)->getPrimaryTemplate() == 0)
3976 RemainingMatches.push_back(*M);
3977 } else {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003978 // [...] and any given function template specialization F1 is
3979 // eliminated if the set contains a second function template
3980 // specialization whose function template is more specialized
3981 // than the function template of F1 according to the partial
3982 // ordering rules of 14.5.5.2.
3983
3984 // The algorithm specified above is quadratic. We instead use a
3985 // two-pass algorithm (similar to the one used to identify the
3986 // best viable function in an overload set) that identifies the
3987 // best function template (if it exists).
3988 MatchIter Best = Matches.begin();
3989 MatchIter M = Best, MEnd = Matches.end();
3990 // Find the most specialized function.
3991 for (++M; M != MEnd; ++M)
3992 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
3993 (*Best)->getPrimaryTemplate(),
3994 false)
3995 == (*M)->getPrimaryTemplate())
3996 Best = M;
3997
3998 // Determine whether this function template is more specialized
3999 // that all of the others.
4000 bool Ambiguous = false;
4001 for (M = Matches.begin(); M != MEnd; ++M) {
4002 if (M != Best &&
4003 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4004 (*Best)->getPrimaryTemplate(),
4005 false)
4006 != (*Best)->getPrimaryTemplate()) {
4007 Ambiguous = true;
4008 break;
4009 }
4010 }
4011
4012 // If one function template was more specialized than all of the
4013 // others, return it.
4014 if (!Ambiguous)
4015 return *Best;
4016
4017 // We could not find a most-specialized function template, which
4018 // is equivalent to having a set of function templates with more
4019 // than one such template. So, we place all of the function
4020 // templates into the set of remaining matches and produce a
4021 // diagnostic below. FIXME: we could perform the quadratic
4022 // algorithm here, pruning the result set to limit the number of
4023 // candidates output later.
4024 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregor00aeb522009-07-08 23:33:52 +00004025 }
4026
4027 // [...] After such eliminations, if any, there shall remain exactly one
4028 // selected function.
4029 if (RemainingMatches.size() == 1)
4030 return RemainingMatches.front();
4031
4032 // FIXME: We should probably return the same thing that BestViableFunction
4033 // returns (even if we issue the diagnostics here).
4034 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4035 << RemainingMatches[0]->getDeclName();
4036 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4037 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00004038 return 0;
4039}
4040
Douglas Gregorf6b89692008-11-26 05:54:23 +00004041/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00004042/// (which eventually refers to the declaration Func) and the call
4043/// arguments Args/NumArgs, attempt to resolve the function call down
4044/// to a specific function. If overload resolution succeeds, returns
4045/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00004046/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00004047/// arguments and Fn, and returns NULL.
Douglas Gregorfa047642009-02-04 00:32:51 +00004048FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor17330012009-02-04 15:01:18 +00004049 DeclarationName UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004050 bool HasExplicitTemplateArgs,
4051 const TemplateArgument *ExplicitTemplateArgs,
4052 unsigned NumExplicitTemplateArgs,
Douglas Gregor0a396682008-11-26 06:01:48 +00004053 SourceLocation LParenLoc,
4054 Expr **Args, unsigned NumArgs,
4055 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004056 SourceLocation RParenLoc,
Douglas Gregor17330012009-02-04 15:01:18 +00004057 bool &ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00004058 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00004059
4060 // Add the functions denoted by Callee to the set of candidate
4061 // functions. While we're doing so, track whether argument-dependent
4062 // lookup still applies, per:
4063 //
4064 // C++0x [basic.lookup.argdep]p3:
4065 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4066 // and let Y be the lookup set produced by argument dependent
4067 // lookup (defined as follows). If X contains
4068 //
4069 // -- a declaration of a class member, or
4070 //
4071 // -- a block-scope function declaration that is not a
4072 // using-declaration, or
4073 //
4074 // -- a declaration that is neither a function or a function
4075 // template
4076 //
4077 // then Y is empty.
Douglas Gregorfa047642009-02-04 00:32:51 +00004078 if (OverloadedFunctionDecl *Ovl
Douglas Gregor17330012009-02-04 15:01:18 +00004079 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4080 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4081 FuncEnd = Ovl->function_end();
4082 Func != FuncEnd; ++Func) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004083 DeclContext *Ctx = 0;
4084 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004085 if (HasExplicitTemplateArgs)
4086 continue;
4087
Douglas Gregore53060f2009-06-25 22:08:12 +00004088 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4089 Ctx = FunDecl->getDeclContext();
4090 } else {
4091 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004092 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4093 ExplicitTemplateArgs,
4094 NumExplicitTemplateArgs,
4095 Args, NumArgs, CandidateSet);
Douglas Gregore53060f2009-06-25 22:08:12 +00004096 Ctx = FunTmpl->getDeclContext();
4097 }
Douglas Gregor17330012009-02-04 15:01:18 +00004098
Douglas Gregore53060f2009-06-25 22:08:12 +00004099
4100 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor17330012009-02-04 15:01:18 +00004101 ArgumentDependentLookup = false;
4102 }
4103 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004104 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor17330012009-02-04 15:01:18 +00004105 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4106
4107 if (Func->getDeclContext()->isRecord() ||
4108 Func->getDeclContext()->isFunctionOrMethod())
4109 ArgumentDependentLookup = false;
Douglas Gregore53060f2009-06-25 22:08:12 +00004110 } else if (FunctionTemplateDecl *FuncTemplate
4111 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004112 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4113 ExplicitTemplateArgs,
4114 NumExplicitTemplateArgs,
4115 Args, NumArgs, CandidateSet);
Douglas Gregore53060f2009-06-25 22:08:12 +00004116
4117 if (FuncTemplate->getDeclContext()->isRecord())
4118 ArgumentDependentLookup = false;
4119 }
Douglas Gregor17330012009-02-04 15:01:18 +00004120
4121 if (Callee)
4122 UnqualifiedName = Callee->getDeclName();
4123
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004124 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregorfa047642009-02-04 00:32:51 +00004125 if (ArgumentDependentLookup)
Douglas Gregor17330012009-02-04 15:01:18 +00004126 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004127 CandidateSet);
4128
Douglas Gregorf6b89692008-11-26 05:54:23 +00004129 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004130 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00004131 case OR_Success:
4132 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004133
4134 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00004135 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00004136 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004137 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004138 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4139 break;
4140
4141 case OR_Ambiguous:
4142 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00004143 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004144 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4145 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004146
4147 case OR_Deleted:
4148 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4149 << Best->Function->isDeleted()
4150 << UnqualifiedName
4151 << Fn->getSourceRange();
4152 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4153 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004154 }
4155
4156 // Overload resolution failed. Destroy all of the subexpressions and
4157 // return NULL.
4158 Fn->Destroy(Context);
4159 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4160 Args[Arg]->Destroy(Context);
4161 return 0;
4162}
4163
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004164/// \brief Create a unary operation that may resolve to an overloaded
4165/// operator.
4166///
4167/// \param OpLoc The location of the operator itself (e.g., '*').
4168///
4169/// \param OpcIn The UnaryOperator::Opcode that describes this
4170/// operator.
4171///
4172/// \param Functions The set of non-member functions that will be
4173/// considered by overload resolution. The caller needs to build this
4174/// set based on the context using, e.g.,
4175/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4176/// set should not contain any member functions; those will be added
4177/// by CreateOverloadedUnaryOp().
4178///
4179/// \param input The input argument.
4180Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4181 unsigned OpcIn,
4182 FunctionSet &Functions,
4183 ExprArg input) {
4184 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4185 Expr *Input = (Expr *)input.get();
4186
4187 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4188 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4189 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4190
4191 Expr *Args[2] = { Input, 0 };
4192 unsigned NumArgs = 1;
4193
4194 // For post-increment and post-decrement, add the implicit '0' as
4195 // the second argument, so that we know this is a post-increment or
4196 // post-decrement.
4197 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4198 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4199 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4200 SourceLocation());
4201 NumArgs = 2;
4202 }
4203
4204 if (Input->isTypeDependent()) {
4205 OverloadedFunctionDecl *Overloads
4206 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4207 for (FunctionSet::iterator Func = Functions.begin(),
4208 FuncEnd = Functions.end();
4209 Func != FuncEnd; ++Func)
4210 Overloads->addOverload(*Func);
4211
4212 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4213 OpLoc, false, false);
4214
4215 input.release();
4216 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4217 &Args[0], NumArgs,
4218 Context.DependentTy,
4219 OpLoc));
4220 }
4221
4222 // Build an empty overload set.
4223 OverloadCandidateSet CandidateSet;
4224
4225 // Add the candidates from the given function set.
4226 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4227
4228 // Add operator candidates that are member functions.
4229 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4230
4231 // Add builtin operator candidates.
4232 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4233
4234 // Perform overload resolution.
4235 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004236 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004237 case OR_Success: {
4238 // We found a built-in operator or an overloaded operator.
4239 FunctionDecl *FnDecl = Best->Function;
4240
4241 if (FnDecl) {
4242 // We matched an overloaded operator. Build a call to that
4243 // operator.
4244
4245 // Convert the arguments.
4246 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4247 if (PerformObjectArgumentInitialization(Input, Method))
4248 return ExprError();
4249 } else {
4250 // Convert the arguments.
4251 if (PerformCopyInitialization(Input,
4252 FnDecl->getParamDecl(0)->getType(),
4253 "passing"))
4254 return ExprError();
4255 }
4256
4257 // Determine the result type
4258 QualType ResultTy
4259 = FnDecl->getType()->getAsFunctionType()->getResultType();
4260 ResultTy = ResultTy.getNonReferenceType();
4261
4262 // Build the actual expression node.
4263 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4264 SourceLocation());
4265 UsualUnaryConversions(FnExpr);
4266
4267 input.release();
Anders Carlsson2d46eb22009-08-16 04:11:06 +00004268
4269 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4270 &Input, 1, ResultTy, OpLoc);
4271 return MaybeBindToTemporary(CE);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004272 } else {
4273 // We matched a built-in operator. Convert the arguments, then
4274 // break out so that we will build the appropriate built-in
4275 // operator node.
4276 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4277 Best->Conversions[0], "passing"))
4278 return ExprError();
4279
4280 break;
4281 }
4282 }
4283
4284 case OR_No_Viable_Function:
4285 // No viable function; fall through to handling this as a
4286 // built-in operator, which will produce an error message for us.
4287 break;
4288
4289 case OR_Ambiguous:
4290 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4291 << UnaryOperator::getOpcodeStr(Opc)
4292 << Input->getSourceRange();
4293 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4294 return ExprError();
4295
4296 case OR_Deleted:
4297 Diag(OpLoc, diag::err_ovl_deleted_oper)
4298 << Best->Function->isDeleted()
4299 << UnaryOperator::getOpcodeStr(Opc)
4300 << Input->getSourceRange();
4301 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4302 return ExprError();
4303 }
4304
4305 // Either we found no viable overloaded operator or we matched a
4306 // built-in operator. In either case, fall through to trying to
4307 // build a built-in operation.
4308 input.release();
4309 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4310}
4311
Douglas Gregor063daf62009-03-13 18:40:31 +00004312/// \brief Create a binary operation that may resolve to an overloaded
4313/// operator.
4314///
4315/// \param OpLoc The location of the operator itself (e.g., '+').
4316///
4317/// \param OpcIn The BinaryOperator::Opcode that describes this
4318/// operator.
4319///
4320/// \param Functions The set of non-member functions that will be
4321/// considered by overload resolution. The caller needs to build this
4322/// set based on the context using, e.g.,
4323/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4324/// set should not contain any member functions; those will be added
4325/// by CreateOverloadedBinOp().
4326///
4327/// \param LHS Left-hand argument.
4328/// \param RHS Right-hand argument.
4329Sema::OwningExprResult
4330Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4331 unsigned OpcIn,
4332 FunctionSet &Functions,
4333 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004334 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004335 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00004336
4337 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4338 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4339 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4340
4341 // If either side is type-dependent, create an appropriate dependent
4342 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004343 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004344 // .* cannot be overloaded.
4345 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004346 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor063daf62009-03-13 18:40:31 +00004347 Context.DependentTy, OpLoc));
4348
4349 OverloadedFunctionDecl *Overloads
4350 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4351 for (FunctionSet::iterator Func = Functions.begin(),
4352 FuncEnd = Functions.end();
4353 Func != FuncEnd; ++Func)
4354 Overloads->addOverload(*Func);
4355
4356 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4357 OpLoc, false, false);
4358
4359 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4360 Args, 2,
4361 Context.DependentTy,
4362 OpLoc));
4363 }
4364
4365 // If this is the .* operator, which is not overloadable, just
4366 // create a built-in binary operator.
4367 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004368 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004369
4370 // If this is one of the assignment operators, we only perform
4371 // overload resolution if the left-hand side is a class or
4372 // enumeration type (C++ [expr.ass]p3).
4373 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004374 !Args[0]->getType()->isOverloadableType())
4375 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004376
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004377 // Build an empty overload set.
4378 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00004379
4380 // Add the candidates from the given function set.
4381 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4382
4383 // Add operator candidates that are member functions.
4384 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4385
4386 // Add builtin operator candidates.
4387 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4388
4389 // Perform overload resolution.
4390 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004391 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004392 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00004393 // We found a built-in operator or an overloaded operator.
4394 FunctionDecl *FnDecl = Best->Function;
4395
4396 if (FnDecl) {
4397 // We matched an overloaded operator. Build a call to that
4398 // operator.
4399
4400 // Convert the arguments.
4401 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004402 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4403 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004404 "passing"))
4405 return ExprError();
4406 } else {
4407 // Convert the arguments.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004408 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004409 "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004410 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004411 "passing"))
4412 return ExprError();
4413 }
4414
4415 // Determine the result type
4416 QualType ResultTy
4417 = FnDecl->getType()->getAsFunctionType()->getResultType();
4418 ResultTy = ResultTy.getNonReferenceType();
4419
4420 // Build the actual expression node.
4421 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00004422 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004423 UsualUnaryConversions(FnExpr);
4424
Anders Carlsson2d46eb22009-08-16 04:11:06 +00004425 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4426 Args, 2, ResultTy, OpLoc);
4427 return MaybeBindToTemporary(CE);
Douglas Gregor063daf62009-03-13 18:40:31 +00004428 } else {
4429 // We matched a built-in operator. Convert the arguments, then
4430 // break out so that we will build the appropriate built-in
4431 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004432 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor063daf62009-03-13 18:40:31 +00004433 Best->Conversions[0], "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004434 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor063daf62009-03-13 18:40:31 +00004435 Best->Conversions[1], "passing"))
4436 return ExprError();
4437
4438 break;
4439 }
4440 }
4441
4442 case OR_No_Viable_Function:
Sebastian Redl8593c782009-05-21 11:50:50 +00004443 // For class as left operand for assignment or compound assigment operator
4444 // do not fall through to handling in built-in, but report that no overloaded
4445 // assignment operator found
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004446 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00004447 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4448 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004449 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl8593c782009-05-21 11:50:50 +00004450 return ExprError();
4451 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004452 // No viable function; fall through to handling this as a
4453 // built-in operator, which will produce an error message for us.
4454 break;
4455
4456 case OR_Ambiguous:
4457 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4458 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004459 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00004460 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4461 return ExprError();
4462
4463 case OR_Deleted:
4464 Diag(OpLoc, diag::err_ovl_deleted_oper)
4465 << Best->Function->isDeleted()
4466 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004467 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00004468 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4469 return ExprError();
4470 }
4471
4472 // Either we found no viable overloaded operator or we matched a
4473 // built-in operator. In either case, try to build a built-in
4474 // operation.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004475 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004476}
4477
Douglas Gregor88a35142008-12-22 05:46:06 +00004478/// BuildCallToMemberFunction - Build a call to a member
4479/// function. MemExpr is the expression that refers to the member
4480/// function (and includes the object parameter), Args/NumArgs are the
4481/// arguments to the function call (not including the object
4482/// parameter). The caller needs to validate that the member
4483/// expression refers to a member function or an overloaded member
4484/// function.
4485Sema::ExprResult
4486Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4487 SourceLocation LParenLoc, Expr **Args,
4488 unsigned NumArgs, SourceLocation *CommaLocs,
4489 SourceLocation RParenLoc) {
4490 // Dig out the member expression. This holds both the object
4491 // argument and the member function we're referring to.
4492 MemberExpr *MemExpr = 0;
4493 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4494 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4495 else
4496 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4497 assert(MemExpr && "Building member call without member expression");
4498
4499 // Extract the object argument.
4500 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004501
Douglas Gregor88a35142008-12-22 05:46:06 +00004502 CXXMethodDecl *Method = 0;
Douglas Gregor6b906862009-08-21 00:16:32 +00004503 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4504 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004505 // Add overload candidates
4506 OverloadCandidateSet CandidateSet;
Douglas Gregor6b906862009-08-21 00:16:32 +00004507 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4508
Douglas Gregordec06662009-08-21 18:42:58 +00004509 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4510 Func != FuncEnd; ++Func) {
4511 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4512 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4513 /*SuppressUserConversions=*/false);
4514 else
4515 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4516 /*FIXME:*/false, /*FIXME:*/0,
4517 /*FIXME:*/0, ObjectArg, Args, NumArgs,
4518 CandidateSet,
4519 /*SuppressUsedConversions=*/false);
4520 }
Douglas Gregor6b906862009-08-21 00:16:32 +00004521
Douglas Gregor88a35142008-12-22 05:46:06 +00004522 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004523 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004524 case OR_Success:
4525 Method = cast<CXXMethodDecl>(Best->Function);
4526 break;
4527
4528 case OR_No_Viable_Function:
4529 Diag(MemExpr->getSourceRange().getBegin(),
4530 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00004531 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00004532 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4533 // FIXME: Leaking incoming expressions!
4534 return true;
4535
4536 case OR_Ambiguous:
4537 Diag(MemExpr->getSourceRange().getBegin(),
4538 diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00004539 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00004540 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4541 // FIXME: Leaking incoming expressions!
4542 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004543
4544 case OR_Deleted:
4545 Diag(MemExpr->getSourceRange().getBegin(),
4546 diag::err_ovl_deleted_member_call)
4547 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00004548 << DeclName << MemExprE->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004549 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4550 // FIXME: Leaking incoming expressions!
4551 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004552 }
4553
4554 FixOverloadedFunctionReference(MemExpr, Method);
4555 } else {
4556 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4557 }
4558
4559 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek8189cde2009-02-07 01:47:29 +00004560 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00004561 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4562 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004563 Method->getResultType().getNonReferenceType(),
4564 RParenLoc));
4565
4566 // Convert the object argument (for a non-static member function call).
4567 if (!Method->isStatic() &&
4568 PerformObjectArgumentInitialization(ObjectArg, Method))
4569 return true;
4570 MemExpr->setBase(ObjectArg);
4571
4572 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00004573 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004574 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4575 RParenLoc))
4576 return true;
4577
Anders Carlssond406bf02009-08-16 01:56:34 +00004578 if (CheckFunctionCall(Method, TheCall.get()))
4579 return true;
Anders Carlsson6f680272009-08-16 03:42:12 +00004580
4581 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00004582}
4583
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004584/// BuildCallToObjectOfClassType - Build a call to an object of class
4585/// type (C++ [over.call.object]), which can end up invoking an
4586/// overloaded function call operator (@c operator()) or performing a
4587/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00004588Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00004589Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4590 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004591 Expr **Args, unsigned NumArgs,
4592 SourceLocation *CommaLocs,
4593 SourceLocation RParenLoc) {
4594 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00004595 const RecordType *Record = Object->getType()->getAs<RecordType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004596
4597 // C++ [over.call.object]p1:
4598 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00004599 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004600 // candidate functions includes at least the function call
4601 // operators of T. The function call operators of T are obtained by
4602 // ordinary lookup of the name operator() in the context of
4603 // (E).operator().
4604 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00004605 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004606 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004607 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004608 Oper != OperEnd; ++Oper)
4609 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4610 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004611
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004612 // C++ [over.call.object]p2:
4613 // In addition, for each conversion function declared in T of the
4614 // form
4615 //
4616 // operator conversion-type-id () cv-qualifier;
4617 //
4618 // where cv-qualifier is the same cv-qualification as, or a
4619 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00004620 // denotes the type "pointer to function of (P1,...,Pn) returning
4621 // R", or the type "reference to pointer to function of
4622 // (P1,...,Pn) returning R", or the type "reference to function
4623 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004624 // is also considered as a candidate function. Similarly,
4625 // surrogate call functions are added to the set of candidate
4626 // functions for each conversion function declared in an
4627 // accessible base class provided the function is not hidden
4628 // within T by another intervening declaration.
Douglas Gregor5842ba92009-08-24 15:23:48 +00004629
4630 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4631 // FIXME: Look in base classes for more conversion operators!
4632 OverloadedFunctionDecl *Conversions
4633 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
4634 for (OverloadedFunctionDecl::function_iterator
4635 Func = Conversions->function_begin(),
4636 FuncEnd = Conversions->function_end();
4637 Func != FuncEnd; ++Func) {
4638 CXXConversionDecl *Conv;
4639 FunctionTemplateDecl *ConvTemplate;
4640 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004641
Douglas Gregor5842ba92009-08-24 15:23:48 +00004642 // Skip over templated conversion functions; they aren't
4643 // surrogates.
4644 if (ConvTemplate)
4645 continue;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004646
Douglas Gregor5842ba92009-08-24 15:23:48 +00004647 // Strip the reference type (if any) and then the pointer type (if
4648 // any) to get down to what might be a function type.
4649 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4650 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4651 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004652
Douglas Gregor5842ba92009-08-24 15:23:48 +00004653 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4654 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4655 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004656 }
Douglas Gregor5842ba92009-08-24 15:23:48 +00004657
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004658 // Perform overload resolution.
4659 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004660 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004661 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004662 // Overload resolution succeeded; we'll build the appropriate call
4663 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004664 break;
4665
4666 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00004667 Diag(Object->getSourceRange().getBegin(),
4668 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004669 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00004670 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004671 break;
4672
4673 case OR_Ambiguous:
4674 Diag(Object->getSourceRange().getBegin(),
4675 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00004676 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004677 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4678 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004679
4680 case OR_Deleted:
4681 Diag(Object->getSourceRange().getBegin(),
4682 diag::err_ovl_deleted_object_call)
4683 << Best->Function->isDeleted()
4684 << Object->getType() << Object->getSourceRange();
4685 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4686 break;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004687 }
4688
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004689 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004690 // We had an error; delete all of the subexpressions and return
4691 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004692 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004693 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004694 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004695 return true;
4696 }
4697
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004698 if (Best->Function == 0) {
4699 // Since there is no function declaration, this is one of the
4700 // surrogate candidates. Dig out the conversion function.
4701 CXXConversionDecl *Conv
4702 = cast<CXXConversionDecl>(
4703 Best->Conversions[0].UserDefined.ConversionFunction);
4704
4705 // We selected one of the surrogate functions that converts the
4706 // object parameter to a function pointer. Perform the conversion
4707 // on the object argument, then let ActOnCallExpr finish the job.
4708 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00004709 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004710 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00004711 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004712 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004713 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4714 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4715 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004716 }
4717
4718 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4719 // that calls this method, using Object for the implicit object
4720 // parameter and passing along the remaining arguments.
4721 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor72564e72009-02-26 23:50:07 +00004722 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004723
4724 unsigned NumArgsInProto = Proto->getNumArgs();
4725 unsigned NumArgsToCheck = NumArgs;
4726
4727 // Build the full argument list for the method call (the
4728 // implicit object parameter is placed at the beginning of the
4729 // list).
4730 Expr **MethodArgs;
4731 if (NumArgs < NumArgsInProto) {
4732 NumArgsToCheck = NumArgsInProto;
4733 MethodArgs = new Expr*[NumArgsInProto + 1];
4734 } else {
4735 MethodArgs = new Expr*[NumArgs + 1];
4736 }
4737 MethodArgs[0] = Object;
4738 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4739 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4740
Ted Kremenek8189cde2009-02-07 01:47:29 +00004741 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4742 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004743 UsualUnaryConversions(NewFn);
4744
4745 // Once we've built TheCall, all of the expressions are properly
4746 // owned.
4747 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004748 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor063daf62009-03-13 18:40:31 +00004749 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4750 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004751 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004752 delete [] MethodArgs;
4753
Douglas Gregor518fda12009-01-13 05:10:00 +00004754 // We may have default arguments. If so, we need to allocate more
4755 // slots in the call for them.
4756 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004757 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00004758 else if (NumArgs > NumArgsInProto)
4759 NumArgsToCheck = NumArgsInProto;
4760
Chris Lattner312531a2009-04-12 08:11:20 +00004761 bool IsError = false;
4762
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004763 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00004764 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004765 TheCall->setArg(0, Object);
4766
Chris Lattner312531a2009-04-12 08:11:20 +00004767
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004768 // Check the argument types.
4769 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004770 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00004771 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004772 Arg = Args[i];
Douglas Gregor518fda12009-01-13 05:10:00 +00004773
4774 // Pass the argument.
4775 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner312531a2009-04-12 08:11:20 +00004776 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor518fda12009-01-13 05:10:00 +00004777 } else {
Anders Carlssonf1480ee2009-08-14 18:30:22 +00004778 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00004779 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004780
4781 TheCall->setArg(i + 1, Arg);
4782 }
4783
4784 // If this is a variadic call, handle args passed through "...".
4785 if (Proto->isVariadic()) {
4786 // Promote the arguments (C99 6.5.2.2p7).
4787 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4788 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00004789 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004790 TheCall->setArg(i + 1, Arg);
4791 }
4792 }
4793
Chris Lattner312531a2009-04-12 08:11:20 +00004794 if (IsError) return true;
4795
Anders Carlssond406bf02009-08-16 01:56:34 +00004796 if (CheckFunctionCall(Method, TheCall.get()))
4797 return true;
4798
Anders Carlssona303f9e2009-08-16 03:53:54 +00004799 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004800}
4801
Douglas Gregor8ba10742008-11-20 16:27:02 +00004802/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4803/// (if one exists), where @c Base is an expression of class type and
4804/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004805Sema::OwningExprResult
4806Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4807 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004808 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4809
4810 // C++ [over.ref]p1:
4811 //
4812 // [...] An expression x->m is interpreted as (x.operator->())->m
4813 // for a class object x of type T if T::operator->() exists and if
4814 // the operator is selected as the best match function by the
4815 // overload resolution mechanism (13.3).
4816 // FIXME: look in base classes.
4817 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4818 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00004819 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004820
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004821 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004822 for (llvm::tie(Oper, OperEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004823 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004824 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004825 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004826
4827 // Perform overload resolution.
4828 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004829 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00004830 case OR_Success:
4831 // Overload resolution succeeded; we'll build the call below.
4832 break;
4833
4834 case OR_No_Viable_Function:
4835 if (CandidateSet.empty())
4836 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004837 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004838 else
4839 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004840 << "operator->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004841 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004842 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004843
4844 case OR_Ambiguous:
4845 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004846 << "operator->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004847 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004848 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004849
4850 case OR_Deleted:
4851 Diag(OpLoc, diag::err_ovl_deleted_oper)
4852 << Best->Function->isDeleted()
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004853 << "operator->" << Base->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004854 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004855 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004856 }
4857
4858 // Convert the object parameter.
4859 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004860 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004861 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004862
4863 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004864 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004865
4866 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004867 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4868 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004869 UsualUnaryConversions(FnExpr);
Douglas Gregor063daf62009-03-13 18:40:31 +00004870 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004871 Method->getResultType().getNonReferenceType(),
4872 OpLoc);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004873 return Owned(Base);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004874}
4875
Douglas Gregor904eed32008-11-10 20:40:00 +00004876/// FixOverloadedFunctionReference - E is an expression that refers to
4877/// a C++ overloaded function (possibly with some parentheses and
4878/// perhaps a '&' around it). We have resolved the overloaded function
4879/// to the function declaration Fn, so patch up the expression E to
4880/// refer (possibly indirectly) to Fn.
4881void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4882 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4883 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4884 E->setType(PE->getSubExpr()->getType());
4885 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4886 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4887 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00004888 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4889 if (Method->isStatic()) {
4890 // Do nothing: static member functions aren't any different
4891 // from non-member functions.
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004892 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregorb86b0572009-02-11 01:18:59 +00004893 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4894 // We have taken the address of a pointer to member
4895 // function. Perform the computation here so that we get the
4896 // appropriate pointer to member type.
4897 DRE->setDecl(Fn);
4898 DRE->setType(Fn->getType());
4899 QualType ClassType
4900 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4901 E->setType(Context.getMemberPointerType(Fn->getType(),
4902 ClassType.getTypePtr()));
4903 return;
4904 }
4905 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004906 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00004907 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor904eed32008-11-10 20:40:00 +00004908 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00004909 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4910 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4911 "Expected overloaded function or function template");
Douglas Gregor904eed32008-11-10 20:40:00 +00004912 DR->setDecl(Fn);
4913 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004914 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4915 MemExpr->setMemberDecl(Fn);
4916 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00004917 } else {
4918 assert(false && "Invalid reference to overloaded function");
4919 }
4920}
4921
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004922} // end namespace clang