blob: 850b5e7d8af8542f785504ecf8c9b85041360c51 [file] [log] [blame]
Douglas Gregord2baafd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor10f3c502008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
Edwin Török0fbc71c2009-08-24 13:25:12 +000026#include <cstdio>
Douglas Gregord2baafd2008-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 Gregore819caf2009-02-12 00:15:05 +000043 ICC_Promotion,
44 ICC_Conversion,
45 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000046 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000051 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000052 ICC_Conversion,
Douglas Gregord2baafd2008-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 Gregore819caf2009-02-12 00:15:05 +000070 ICR_Promotion,
71 ICR_Conversion,
72 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000073 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000078 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000079 ICR_Conversion,
Douglas Gregord2baafd2008-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 Gregore819caf2009-02-12 00:15:05 +000096 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000097 "Integral conversion",
98 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +000099 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000100 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000101 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000102 "Pointer conversion",
103 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000104 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000105 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000106 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000107 };
108 return Name[Kind];
109}
110
Douglas Gregorb72e9da2008-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 Redl9bc16ad2009-03-29 22:46:24 +0000120 RRefBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000121 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000122}
123
Douglas Gregord2baafd2008-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 Gregor80402cf2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-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 Gregor14046502008-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 Kremenekd00cd9e2009-07-29 21:53:49 +0000177 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor14046502008-10-23 00:40:37 +0000178 return ToPtrType->getPointeeType()->isVoidType();
179
180 return false;
181}
182
Douglas Gregord2baafd2008-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 Gregora3b34bb2008-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 Gregord2baafd2008-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 Lattner271d4c22008-11-24 05:29:24 +0000228 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-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 Gregorb60eb752009-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 Gregorbf6bc302009-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 Gregord2baafd2008-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 Gregor4fa58902009-02-26 23:50:07 +0000326 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
327 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000328 return false;
329
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000330 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
331 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregord2baafd2008-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 Gregorbf6bc302009-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 Gregord2baafd2008-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 Gregora7b56a32008-11-21 15:36:28 +0000371 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-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 Gregor81c29152008-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 Gregord2baafd2008-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 Gregora3b34bb2008-11-03 19:09:14 +0000402///
403/// If @p SuppressUserConversions, then user-defined conversions are
404/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000405/// If @p AllowExplicit, then explicit user-defined conversions are
406/// permitted.
Sebastian Redla55834a2009-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 Gregord2baafd2008-10-21 16:13:35 +0000409ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000410Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000411 bool SuppressUserConversions,
Sebastian Redla55834a2009-04-12 17:16:29 +0000412 bool AllowExplicit, bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000413{
414 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000415 if (IsStandardConversion(From, ToType, ICS.Standard))
416 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000417 else if (getLangOptions().CPlusPlus &&
418 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redla55834a2009-04-12 17:16:29 +0000419 !SuppressUserConversions, AllowExplicit,
420 ForceRValue)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000421 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-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 Gregord9176392009-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 Gregora3b34bb2008-11-03 19:09:14 +0000435 // Turn this into a "standard" conversion sequence, so that it
436 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-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 Gregora3b34bb2008-11-03 19:09:14 +0000441 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000442 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000443 ICS.Standard.Second = ICK_Derived_To_Base;
444 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000445 }
Douglas Gregorb206cc42009-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 Gregore640ab62008-11-03 17:51:48 +0000457 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000458 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-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 Gregord2baafd2008-10-21 16:13:35 +0000475 QualType FromType = From->getType();
476
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000477 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000478 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000479 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000480 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000481 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000482 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000483
Douglas Gregorfcb19192009-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 Gregord2baafd2008-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 Gregor45014fd2008-11-10 20:40:00 +0000502 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000503 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000504 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-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 Gregorfcb19192009-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 Gregorb72e9da2008-10-31 16:23:19 +0000512 FromType = FromType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000513 } else if (FromType->isArrayType()) {
514 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000515 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000516
517 // An lvalue or rvalue of type "array of N T" or "array of unknown
518 // bound of T" can be converted to an rvalue of type "pointer to
519 // T" (C++ 4.2p1).
520 FromType = Context.getArrayDecayedType(FromType);
521
522 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
523 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000524 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000525
526 // For the purpose of ranking in overload resolution
527 // (13.3.3.1.1), this conversion is considered an
528 // array-to-pointer conversion followed by a qualification
529 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000530 SCS.Second = ICK_Identity;
531 SCS.Third = ICK_Qualification;
532 SCS.ToTypePtr = ToType.getAsOpaquePtr();
533 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000534 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000535 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
536 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000537 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-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 Stump90fc78e2009-08-04 21:02:39 +0000543 } else if (FunctionDecl *Fn
Douglas Gregor45014fd2008-11-10 20:40:00 +0000544 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000545 // Address of overloaded function (C++ [over.over]).
Douglas Gregor45014fd2008-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 Redlce6fff02009-03-16 23:22:08 +0000551 if (ToType->isLValueReferenceType())
552 FromType = Context.getLValueReferenceType(FromType);
553 else if (ToType->isRValueReferenceType())
554 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000555 else if (ToType->isMemberPointerType()) {
556 // Resolve address only succeeds if both sides are member pointers,
557 // but it doesn't have to be the same class. See DR 247.
558 // Note that this means that the type of &Derived::fn can be
559 // Ret (Base::*)(Args) if the fn overload actually found is from the
560 // base class, even if it was brought into the derived class via a
561 // using declaration. The standard isn't clear on this issue at all.
562 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
563 FromType = Context.getMemberPointerType(FromType,
564 Context.getTypeDeclType(M->getParent()).getTypePtr());
565 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000566 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000567 } else {
568 // We don't require any conversions for the first step.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000569 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-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 Gregorfcb19192009-02-11 23:02:49 +0000576 // For overloading in C, this can also be a "compatible-type"
577 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000578 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000579 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000580 // The unqualified versions of the types are the same: there's no
581 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000582 SCS.Second = ICK_Identity;
Mike Stump90fc78e2009-08-04 21:02:39 +0000583 } else if (IsIntegralPromotion(From, FromType, ToType)) {
584 // Integral promotion (C++ 4.5).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000585 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000586 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000587 } else if (IsFloatingPointPromotion(FromType, ToType)) {
588 // Floating point promotion (C++ 4.6).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000589 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000590 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000591 } else if (IsComplexPromotion(FromType, ToType)) {
592 // Complex promotion (Clang extension)
Douglas Gregore819caf2009-02-12 00:15:05 +0000593 SCS.Second = ICK_Complex_Promotion;
594 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000595 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000596 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000597 // Integral conversions (C++ 4.7).
598 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000599 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000600 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000601 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
602 // Floating point conversions (C++ 4.8).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000603 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000604 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000605 } else if (FromType->isComplexType() && ToType->isComplexType()) {
606 // Complex conversions (C99 6.3.1.6)
Douglas Gregore819caf2009-02-12 00:15:05 +0000607 SCS.Second = ICK_Complex_Conversion;
608 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-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 Gregorb72e9da2008-10-31 16:23:19 +0000616 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000617 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-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 Gregore819caf2009-02-12 00:15:05 +0000621 SCS.Second = ICK_Complex_Real;
622 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000623 } else if (IsPointerConversion(From, FromType, ToType, FromType,
624 IncompatibleObjC)) {
625 // Pointer conversions (C++ 4.10).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000626 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000627 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump90fc78e2009-08-04 21:02:39 +0000628 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
629 // Pointer to member conversions (4.11).
Sebastian Redlba387562009-01-25 19:43:20 +0000630 SCS.Second = ICK_Pointer_Member;
Mike Stump90fc78e2009-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 Gregorb72e9da2008-10-31 16:23:19 +0000639 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000640 FromType = Context.BoolTy;
Mike Stump90fc78e2009-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 Gregorfcb19192009-02-11 23:02:49 +0000644 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000645 } else {
646 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000647 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000648 }
649
Douglas Gregor81c29152008-10-29 00:13:59 +0000650 QualType CanonFrom;
651 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000652 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000653 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000654 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000655 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000656 CanonFrom = Context.getCanonicalType(FromType);
657 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000658 } else {
659 // No conversion required
Douglas Gregorb72e9da2008-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 Gregor81c29152008-10-29 00:13:59 +0000666 CanonFrom = Context.getCanonicalType(FromType);
667 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000668 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000669 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
670 FromType = ToType;
671 CanonFrom = CanonTo;
672 }
Douglas Gregord2baafd2008-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 Gregor81c29152008-10-29 00:13:59 +0000677 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000678 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000679
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000680 SCS.ToTypePtr = FromType.getAsOpaquePtr();
681 return true;
Douglas Gregord2baafd2008-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 Redl12aee862008-11-04 15:59:10 +0000691 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000692 if (!To) {
693 return false;
694 }
Douglas Gregord2baafd2008-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 Redl9ac68aa2008-10-31 14:43:28 +0000701 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-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 Redl9ac68aa2008-10-31 14:43:28 +0000707 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000708 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000709 }
710
Douglas Gregord2baafd2008-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 Gregor6b5e34f2008-12-12 02:00:36 +0000734 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000735 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000736 Context.LongTy, Context.UnsignedLongTy ,
737 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000738 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000739 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-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 Redl9ac68aa2008-10-31 14:43:28 +0000747 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-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 Stumpe127ae32009-05-16 07:39:55 +0000760 // FIXME: We should delay checking of bit-fields until we actually perform the
761 // conversion.
Douglas Gregor531434b2009-05-02 02:18:30 +0000762 using llvm::APSInt;
763 if (From)
764 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000765 APSInt BitWidth;
Douglas Gregor531434b2009-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 Gregor82d44772008-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 Redl9ac68aa2008-10-31 14:43:28 +0000784 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000785 }
Douglas Gregor531434b2009-05-02 02:18:30 +0000786
Douglas Gregord2baafd2008-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 Redl9ac68aa2008-10-31 14:43:28 +0000789 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000790 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000791 }
Douglas Gregord2baafd2008-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 Gregore819caf2009-02-12 00:15:05 +0000804 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000805 if (FromBuiltin->getKind() == BuiltinType::Float &&
806 ToBuiltin->getKind() == BuiltinType::Double)
807 return true;
808
Douglas Gregore819caf2009-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 Gregord2baafd2008-10-21 16:13:35 +0000819 return false;
820}
821
Douglas Gregore819caf2009-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 Gregor4ff48512009-02-12 00:26:06 +0000826/// floating-point or integral promotion.
Douglas Gregore819caf2009-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 Gregor4ff48512009-02-12 00:26:06 +0000837 ToComplex->getElementType()) ||
838 IsIntegralPromotion(0, FromComplex->getElementType(),
839 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000840}
841
Douglas Gregor24a90a52008-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 Gregord2baafd2008-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 Gregor9036ef72008-11-27 00:15:41 +0000876///
Douglas Gregor3f5a00c2008-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 Gregor6fd35572008-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 Gregord2baafd2008-10-21 16:13:35 +0000886bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000887 QualType& ConvertedType,
888 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000889{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000890 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000891 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
892 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000893
Douglas Gregorf1d75712008-12-22 20:51:52 +0000894 // Conversion from a null pointer constant to any Objective-C pointer type.
Steve Naroffad75bd22009-07-16 15:41:00 +0000895 if (ToType->isObjCObjectPointerType() &&
Douglas Gregorf1d75712008-12-22 20:51:52 +0000896 From->isNullPointerConstant(Context)) {
897 ConvertedType = ToType;
898 return true;
899 }
900
Douglas Gregor9036ef72008-11-27 00:15:41 +0000901 // Blocks: Block pointers can be converted to void*.
902 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000903 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor9036ef72008-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 Redl5d0ead72009-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 Kremenekd00cd9e2009-07-29 21:53:49 +0000921 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregord2baafd2008-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 Redl9ac68aa2008-10-31 14:43:28 +0000930
Douglas Gregor24a90a52008-11-26 23:31:11 +0000931 // Beyond this point, both types need to be pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000932 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor24a90a52008-11-26 23:31:11 +0000933 if (!FromTypePtr)
934 return false;
935
936 QualType FromPointeeType = FromTypePtr->getPointeeType();
937 QualType ToPointeeType = ToTypePtr->getPointeeType();
938
Douglas Gregord2baafd2008-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 Gregor26ea1222009-03-24 20:32:41 +0000942 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000943 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
944 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000945 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000946 return true;
947 }
948
Douglas Gregorfcb19192009-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 Gregor14046502008-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 Gregorbb461502008-10-24 04:54:22 +0000970 // Note that we do not check for ambiguity or inaccessibility
971 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000972 if (getLangOptions().CPlusPlus &&
973 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000974 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000975 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
976 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000977 ToType, Context);
978 return true;
979 }
Douglas Gregor14046502008-10-23 00:40:37 +0000980
Douglas Gregor932778b2008-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 Naroff329ec222009-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 Gregor932778b2008-12-19 19:13:09 +0000997
Steve Naroff329ec222009-07-10 23:34:53 +0000998 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff7bffd372009-07-15 18:40:39 +0000999 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff329ec222009-07-10 23:34:53 +00001000 // pointer to any interface (in both directions).
Steve Naroff7bffd372009-07-15 18:40:39 +00001001 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff329ec222009-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 Naroff99eb86b2009-07-23 01:01:38 +00001008 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1009 /*compare=*/false)) {
Steve Naroff329ec222009-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 Gregor80402cf2008-12-23 00:53:59 +00001030 QualType ToPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001031 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001032 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001033 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001034 ToPointeeType = ToBlockPtr->getPointeeType();
1035 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001036 return false;
1037
Douglas Gregor80402cf2008-12-23 00:53:59 +00001038 QualType FromPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001039 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001040 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001041 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001042 FromPointeeType = FromBlockPtr->getPointeeType();
1043 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001044 return false;
1045
Douglas Gregor932778b2008-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 Gregor80402cf2008-12-23 00:53:59 +00001056 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-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 Gregor4fa58902009-02-26 23:50:07 +00001060 const FunctionProtoType *FromFunctionType
1061 = FromPointeeType->getAsFunctionProtoType();
1062 const FunctionProtoType *ToFunctionType
1063 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-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 Redlba387562009-01-25 19:43:20 +00001119 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001120}
1121
Douglas Gregorbb461502008-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 Redl0e35d042009-07-25 15:41:38 +00001124/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregorbb461502008-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 Kremenekd00cd9e2009-07-29 21:53:49 +00001131 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1132 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001133 QualType FromPointeeType = FromPtrType->getPointeeType(),
1134 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001135
Douglas Gregorbb461502008-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 Gregor651d1cc2008-10-24 16:17:19 +00001140 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1141 From->getExprLoc(),
1142 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001143 }
1144 }
Steve Naroff329ec222009-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 Naroff7bffd372009-07-15 18:40:39 +00001152 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff329ec222009-07-10 23:34:53 +00001153 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +00001154
Steve Naroff329ec222009-07-10 23:34:53 +00001155 }
Douglas Gregorbb461502008-10-24 04:54:22 +00001156 return false;
1157}
1158
Sebastian Redlba387562009-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 Kremenekd00cd9e2009-07-29 21:53:49 +00001167 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redlba387562009-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 Kremenekd00cd9e2009-07-29 21:53:49 +00001178 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redlba387562009-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 Carlsson512f4ba2009-08-22 23:33:40 +00001203bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1204 CastExpr::CastKind &Kind) {
Sebastian Redlba387562009-01-25 19:43:20 +00001205 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001206 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson512f4ba2009-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 Redlf41a58c2009-01-28 18:33:18 +00001212 return false;
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001213 }
Sebastian Redlba387562009-01-25 19:43:20 +00001214
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001215 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001216 assert(ToPtrType && "No member pointer cast has a target type "
1217 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001218
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001219 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1220 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001221
Sebastian Redlf41a58c2009-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 Redlba387562009-01-25 19:43:20 +00001225
Sebastian Redlf41a58c2009-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 Redlba387562009-01-25 19:43:20 +00001232
Sebastian Redlf41a58c2009-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 Redlba387562009-01-25 19:43:20 +00001241
Sebastian Redlf41a58c2009-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 Redlba387562009-01-25 19:43:20 +00001246 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001247
Douglas Gregor2e047592009-02-28 01:32:25 +00001248 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-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 Carlsson512f4ba2009-08-22 23:33:40 +00001255 // Must be a base to derived member conversion.
1256 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redlba387562009-01-25 19:43:20 +00001257 return false;
1258}
1259
Douglas Gregor6573cfd2008-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 Redlf41a58c2009-01-28 18:33:18 +00001273
Douglas Gregor6573cfd2008-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 Gregor6573cfd2008-10-21 23:43:52 +00001278 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001279 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-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 Gregorabed2172008-10-22 17:49:05 +00001283 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001284 // until there are no more pointers or pointers-to-members left to
1285 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001286 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-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 Gregore5db4f72008-10-22 00:38:21 +00001290 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001291 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001292
Douglas Gregor6573cfd2008-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 Gregorccc0ccc2008-10-22 14:17:15 +00001296 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001297 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001298
Douglas Gregor6573cfd2008-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 Gregorccc0ccc2008-10-22 14:17:15 +00001303 }
Douglas Gregor6573cfd2008-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 Gregor8c860df2009-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 Gregorb206cc42009-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 Redla55834a2009-04-12 17:16:29 +00001341///
1342/// \param ForceRValue true if the expression should be treated as an rvalue
1343/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001344bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001345 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001346 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001347 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001348{
1349 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001350 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor2e047592009-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 Gregorc55b0b02009-04-09 21:40:53 +00001365 for (llvm::tie(Con, ConEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001366 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001367 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-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 Jahanian625fb9d2009-08-06 17:22:51 +00001378 if (!Constructor->isInvalidDecl() &&
Douglas Gregor050cabf2009-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 Gregor2e047592009-02-28 01:32:25 +00001389 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001390 }
1391 }
1392
Douglas Gregorb206cc42009-01-30 23:27:23 +00001393 if (!AllowConversionFunctions) {
1394 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-02-28 01:32:25 +00001395 } else if (const RecordType *FromRecordType
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001396 = From->getType()->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001397 if (CXXRecordDecl *FromRecordDecl
1398 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1399 // Add all of the conversion functions as candidates.
1400 // FIXME: Look for conversions in base classes!
1401 OverloadedFunctionDecl *Conversions
1402 = FromRecordDecl->getConversionFunctions();
1403 for (OverloadedFunctionDecl::function_iterator Func
1404 = Conversions->function_begin();
1405 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001406 CXXConversionDecl *Conv;
1407 FunctionTemplateDecl *ConvTemplate;
1408 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1409 if (ConvTemplate)
1410 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1411 else
1412 Conv = dyn_cast<CXXConversionDecl>(*Func);
1413
1414 if (AllowExplicit || !Conv->isExplicit()) {
1415 if (ConvTemplate)
1416 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1417 CandidateSet);
1418 else
1419 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1420 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001421 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001422 }
1423 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001424
1425 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001426 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001427 case OR_Success:
1428 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001429 if (CXXConstructorDecl *Constructor
1430 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1431 // C++ [over.ics.user]p1:
1432 // If the user-defined conversion is specified by a
1433 // constructor (12.3.1), the initial standard conversion
1434 // sequence converts the source type to the type required by
1435 // the argument of the constructor.
1436 //
1437 // FIXME: What about ellipsis conversions?
1438 QualType ThisType = Constructor->getThisType(Context);
1439 User.Before = Best->Conversions[0].Standard;
1440 User.ConversionFunction = Constructor;
1441 User.After.setAsIdentityConversion();
1442 User.After.FromTypePtr
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001443 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001444 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1445 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001446 } else if (CXXConversionDecl *Conversion
1447 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1448 // C++ [over.ics.user]p1:
1449 //
1450 // [...] If the user-defined conversion is specified by a
1451 // conversion function (12.3.2), the initial standard
1452 // conversion sequence converts the source type to the
1453 // implicit object parameter of the conversion function.
1454 User.Before = Best->Conversions[0].Standard;
1455 User.ConversionFunction = Conversion;
1456
1457 // C++ [over.ics.user]p2:
1458 // The second standard conversion sequence converts the
1459 // result of the user-defined conversion to the target type
1460 // for the sequence. Since an implicit conversion sequence
1461 // is an initialization, the special rules for
1462 // initialization by user-defined conversion apply when
1463 // selecting the best user-defined conversion for a
1464 // user-defined conversion sequence (see 13.3.3 and
1465 // 13.3.3.1).
1466 User.After = Best->FinalConversion;
1467 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001468 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001469 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001470 return false;
1471 }
1472
1473 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001474 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001475 // No conversion here! We're done.
1476 return false;
1477
1478 case OR_Ambiguous:
1479 // FIXME: See C++ [over.best.ics]p10 for the handling of
1480 // ambiguous conversion sequences.
1481 return false;
1482 }
1483
1484 return false;
1485}
1486
Douglas Gregord2baafd2008-10-21 16:13:35 +00001487/// CompareImplicitConversionSequences - Compare two implicit
1488/// conversion sequences to determine whether one is better than the
1489/// other or if they are indistinguishable (C++ 13.3.3.2).
1490ImplicitConversionSequence::CompareKind
1491Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1492 const ImplicitConversionSequence& ICS2)
1493{
1494 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1495 // conversion sequences (as defined in 13.3.3.1)
1496 // -- a standard conversion sequence (13.3.3.1.1) is a better
1497 // conversion sequence than a user-defined conversion sequence or
1498 // an ellipsis conversion sequence, and
1499 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1500 // conversion sequence than an ellipsis conversion sequence
1501 // (13.3.3.1.3).
1502 //
1503 if (ICS1.ConversionKind < ICS2.ConversionKind)
1504 return ImplicitConversionSequence::Better;
1505 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1506 return ImplicitConversionSequence::Worse;
1507
1508 // Two implicit conversion sequences of the same form are
1509 // indistinguishable conversion sequences unless one of the
1510 // following rules apply: (C++ 13.3.3.2p3):
1511 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1512 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1513 else if (ICS1.ConversionKind ==
1514 ImplicitConversionSequence::UserDefinedConversion) {
1515 // User-defined conversion sequence U1 is a better conversion
1516 // sequence than another user-defined conversion sequence U2 if
1517 // they contain the same user-defined conversion function or
1518 // constructor and if the second standard conversion sequence of
1519 // U1 is better than the second standard conversion sequence of
1520 // U2 (C++ 13.3.3.2p3).
1521 if (ICS1.UserDefined.ConversionFunction ==
1522 ICS2.UserDefined.ConversionFunction)
1523 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1524 ICS2.UserDefined.After);
1525 }
1526
1527 return ImplicitConversionSequence::Indistinguishable;
1528}
1529
1530/// CompareStandardConversionSequences - Compare two standard
1531/// conversion sequences to determine whether one is better than the
1532/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1533ImplicitConversionSequence::CompareKind
1534Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1535 const StandardConversionSequence& SCS2)
1536{
1537 // Standard conversion sequence S1 is a better conversion sequence
1538 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1539
1540 // -- S1 is a proper subsequence of S2 (comparing the conversion
1541 // sequences in the canonical form defined by 13.3.3.1.1,
1542 // excluding any Lvalue Transformation; the identity conversion
1543 // sequence is considered to be a subsequence of any
1544 // non-identity conversion sequence) or, if not that,
1545 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1546 // Neither is a proper subsequence of the other. Do nothing.
1547 ;
1548 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1549 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1550 (SCS1.Second == ICK_Identity &&
1551 SCS1.Third == ICK_Identity))
1552 // SCS1 is a proper subsequence of SCS2.
1553 return ImplicitConversionSequence::Better;
1554 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1555 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1556 (SCS2.Second == ICK_Identity &&
1557 SCS2.Third == ICK_Identity))
1558 // SCS2 is a proper subsequence of SCS1.
1559 return ImplicitConversionSequence::Worse;
1560
1561 // -- the rank of S1 is better than the rank of S2 (by the rules
1562 // defined below), or, if not that,
1563 ImplicitConversionRank Rank1 = SCS1.getRank();
1564 ImplicitConversionRank Rank2 = SCS2.getRank();
1565 if (Rank1 < Rank2)
1566 return ImplicitConversionSequence::Better;
1567 else if (Rank2 < Rank1)
1568 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001569
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001570 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1571 // are indistinguishable unless one of the following rules
1572 // applies:
1573
1574 // A conversion that is not a conversion of a pointer, or
1575 // pointer to member, to bool is better than another conversion
1576 // that is such a conversion.
1577 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1578 return SCS2.isPointerConversionToBool()
1579 ? ImplicitConversionSequence::Better
1580 : ImplicitConversionSequence::Worse;
1581
Douglas Gregor14046502008-10-23 00:40:37 +00001582 // C++ [over.ics.rank]p4b2:
1583 //
1584 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001585 // conversion of B* to A* is better than conversion of B* to
1586 // void*, and conversion of A* to void* is better than conversion
1587 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001588 bool SCS1ConvertsToVoid
1589 = SCS1.isPointerConversionToVoidPointer(Context);
1590 bool SCS2ConvertsToVoid
1591 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001592 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1593 // Exactly one of the conversion sequences is a conversion to
1594 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001595 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1596 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001597 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1598 // Neither conversion sequence converts to a void pointer; compare
1599 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001600 if (ImplicitConversionSequence::CompareKind DerivedCK
1601 = CompareDerivedToBaseConversions(SCS1, SCS2))
1602 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001603 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1604 // Both conversion sequences are conversions to void
1605 // pointers. Compare the source types to determine if there's an
1606 // inheritance relationship in their sources.
1607 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1608 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1609
1610 // Adjust the types we're converting from via the array-to-pointer
1611 // conversion, if we need to.
1612 if (SCS1.First == ICK_Array_To_Pointer)
1613 FromType1 = Context.getArrayDecayedType(FromType1);
1614 if (SCS2.First == ICK_Array_To_Pointer)
1615 FromType2 = Context.getArrayDecayedType(FromType2);
1616
1617 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001618 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001619 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001620 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001621
1622 if (IsDerivedFrom(FromPointee2, FromPointee1))
1623 return ImplicitConversionSequence::Better;
1624 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1625 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001626
1627 // Objective-C++: If one interface is more specific than the
1628 // other, it is the better one.
1629 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1630 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1631 if (FromIface1 && FromIface1) {
1632 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1633 return ImplicitConversionSequence::Better;
1634 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1635 return ImplicitConversionSequence::Worse;
1636 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001637 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001638
1639 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1640 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001641 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001642 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001643 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001644
Douglas Gregor0e343382008-10-29 14:50:44 +00001645 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001646 // C++0x [over.ics.rank]p3b4:
1647 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1648 // implicit object parameter of a non-static member function declared
1649 // without a ref-qualifier, and S1 binds an rvalue reference to an
1650 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001651 // FIXME: We don't know if we're dealing with the implicit object parameter,
1652 // or if the member function in this case has a ref qualifier.
1653 // (Of course, we don't have ref qualifiers yet.)
1654 if (SCS1.RRefBinding != SCS2.RRefBinding)
1655 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1656 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001657
1658 // C++ [over.ics.rank]p3b4:
1659 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1660 // which the references refer are the same type except for
1661 // top-level cv-qualifiers, and the type to which the reference
1662 // initialized by S2 refers is more cv-qualified than the type
1663 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001664 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1665 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001666 T1 = Context.getCanonicalType(T1);
1667 T2 = Context.getCanonicalType(T2);
1668 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1669 if (T2.isMoreQualifiedThan(T1))
1670 return ImplicitConversionSequence::Better;
1671 else if (T1.isMoreQualifiedThan(T2))
1672 return ImplicitConversionSequence::Worse;
1673 }
1674 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001675
1676 return ImplicitConversionSequence::Indistinguishable;
1677}
1678
1679/// CompareQualificationConversions - Compares two standard conversion
1680/// sequences to determine whether they can be ranked based on their
1681/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1682ImplicitConversionSequence::CompareKind
1683Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1684 const StandardConversionSequence& SCS2)
1685{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001686 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001687 // -- S1 and S2 differ only in their qualification conversion and
1688 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1689 // cv-qualification signature of type T1 is a proper subset of
1690 // the cv-qualification signature of type T2, and S1 is not the
1691 // deprecated string literal array-to-pointer conversion (4.2).
1692 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1693 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1694 return ImplicitConversionSequence::Indistinguishable;
1695
1696 // FIXME: the example in the standard doesn't use a qualification
1697 // conversion (!)
1698 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1699 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1700 T1 = Context.getCanonicalType(T1);
1701 T2 = Context.getCanonicalType(T2);
1702
1703 // If the types are the same, we won't learn anything by unwrapped
1704 // them.
1705 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1706 return ImplicitConversionSequence::Indistinguishable;
1707
1708 ImplicitConversionSequence::CompareKind Result
1709 = ImplicitConversionSequence::Indistinguishable;
1710 while (UnwrapSimilarPointerTypes(T1, T2)) {
1711 // Within each iteration of the loop, we check the qualifiers to
1712 // determine if this still looks like a qualification
1713 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001714 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001715 // until there are no more pointers or pointers-to-members left
1716 // to unwrap. This essentially mimics what
1717 // IsQualificationConversion does, but here we're checking for a
1718 // strict subset of qualifiers.
1719 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1720 // The qualifiers are the same, so this doesn't tell us anything
1721 // about how the sequences rank.
1722 ;
1723 else if (T2.isMoreQualifiedThan(T1)) {
1724 // T1 has fewer qualifiers, so it could be the better sequence.
1725 if (Result == ImplicitConversionSequence::Worse)
1726 // Neither has qualifiers that are a subset of the other's
1727 // qualifiers.
1728 return ImplicitConversionSequence::Indistinguishable;
1729
1730 Result = ImplicitConversionSequence::Better;
1731 } else if (T1.isMoreQualifiedThan(T2)) {
1732 // T2 has fewer qualifiers, so it could be the better sequence.
1733 if (Result == ImplicitConversionSequence::Better)
1734 // Neither has qualifiers that are a subset of the other's
1735 // qualifiers.
1736 return ImplicitConversionSequence::Indistinguishable;
1737
1738 Result = ImplicitConversionSequence::Worse;
1739 } else {
1740 // Qualifiers are disjoint.
1741 return ImplicitConversionSequence::Indistinguishable;
1742 }
1743
1744 // If the types after this point are equivalent, we're done.
1745 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1746 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001747 }
1748
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001749 // Check that the winning standard conversion sequence isn't using
1750 // the deprecated string literal array to pointer conversion.
1751 switch (Result) {
1752 case ImplicitConversionSequence::Better:
1753 if (SCS1.Deprecated)
1754 Result = ImplicitConversionSequence::Indistinguishable;
1755 break;
1756
1757 case ImplicitConversionSequence::Indistinguishable:
1758 break;
1759
1760 case ImplicitConversionSequence::Worse:
1761 if (SCS2.Deprecated)
1762 Result = ImplicitConversionSequence::Indistinguishable;
1763 break;
1764 }
1765
1766 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001767}
1768
Douglas Gregor14046502008-10-23 00:40:37 +00001769/// CompareDerivedToBaseConversions - Compares two standard conversion
1770/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001771/// various kinds of derived-to-base conversions (C++
1772/// [over.ics.rank]p4b3). As part of these checks, we also look at
1773/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001774ImplicitConversionSequence::CompareKind
1775Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1776 const StandardConversionSequence& SCS2) {
1777 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1778 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1779 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1780 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1781
1782 // Adjust the types we're converting from via the array-to-pointer
1783 // conversion, if we need to.
1784 if (SCS1.First == ICK_Array_To_Pointer)
1785 FromType1 = Context.getArrayDecayedType(FromType1);
1786 if (SCS2.First == ICK_Array_To_Pointer)
1787 FromType2 = Context.getArrayDecayedType(FromType2);
1788
1789 // Canonicalize all of the types.
1790 FromType1 = Context.getCanonicalType(FromType1);
1791 ToType1 = Context.getCanonicalType(ToType1);
1792 FromType2 = Context.getCanonicalType(FromType2);
1793 ToType2 = Context.getCanonicalType(ToType2);
1794
Douglas Gregor0e343382008-10-29 14:50:44 +00001795 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001796 //
1797 // If class B is derived directly or indirectly from class A and
1798 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001799 //
1800 // For Objective-C, we let A, B, and C also be Objective-C
1801 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001802
1803 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001804 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001805 SCS2.Second == ICK_Pointer_Conversion &&
1806 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1807 FromType1->isPointerType() && FromType2->isPointerType() &&
1808 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001809 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001810 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001811 QualType ToPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001812 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001813 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001814 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001815 QualType ToPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001816 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001817
1818 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1819 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1820 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1821 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1822
Douglas Gregor0e343382008-10-29 14:50:44 +00001823 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001824 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1825 if (IsDerivedFrom(ToPointee1, ToPointee2))
1826 return ImplicitConversionSequence::Better;
1827 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1828 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001829
1830 if (ToIface1 && ToIface2) {
1831 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1832 return ImplicitConversionSequence::Better;
1833 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1834 return ImplicitConversionSequence::Worse;
1835 }
Douglas Gregor14046502008-10-23 00:40:37 +00001836 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001837
1838 // -- conversion of B* to A* is better than conversion of C* to A*,
1839 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1840 if (IsDerivedFrom(FromPointee2, FromPointee1))
1841 return ImplicitConversionSequence::Better;
1842 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1843 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001844
1845 if (FromIface1 && FromIface2) {
1846 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1847 return ImplicitConversionSequence::Better;
1848 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1849 return ImplicitConversionSequence::Worse;
1850 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001851 }
Douglas Gregor14046502008-10-23 00:40:37 +00001852 }
1853
Douglas Gregor0e343382008-10-29 14:50:44 +00001854 // Compare based on reference bindings.
1855 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1856 SCS1.Second == ICK_Derived_To_Base) {
1857 // -- binding of an expression of type C to a reference of type
1858 // B& is better than binding an expression of type C to a
1859 // reference of type A&,
1860 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1861 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1862 if (IsDerivedFrom(ToType1, ToType2))
1863 return ImplicitConversionSequence::Better;
1864 else if (IsDerivedFrom(ToType2, ToType1))
1865 return ImplicitConversionSequence::Worse;
1866 }
1867
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001868 // -- binding of an expression of type B to a reference of type
1869 // A& is better than binding an expression of type C to a
1870 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001871 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1872 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1873 if (IsDerivedFrom(FromType2, FromType1))
1874 return ImplicitConversionSequence::Better;
1875 else if (IsDerivedFrom(FromType1, FromType2))
1876 return ImplicitConversionSequence::Worse;
1877 }
1878 }
1879
1880
1881 // FIXME: conversion of A::* to B::* is better than conversion of
1882 // A::* to C::*,
1883
1884 // FIXME: conversion of B::* to C::* is better than conversion of
1885 // A::* to C::*, and
1886
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001887 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1888 SCS1.Second == ICK_Derived_To_Base) {
1889 // -- conversion of C to B is better than conversion of C to A,
1890 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1891 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1892 if (IsDerivedFrom(ToType1, ToType2))
1893 return ImplicitConversionSequence::Better;
1894 else if (IsDerivedFrom(ToType2, ToType1))
1895 return ImplicitConversionSequence::Worse;
1896 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001897
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001898 // -- conversion of B to A is better than conversion of C to A.
1899 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1900 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1901 if (IsDerivedFrom(FromType2, FromType1))
1902 return ImplicitConversionSequence::Better;
1903 else if (IsDerivedFrom(FromType1, FromType2))
1904 return ImplicitConversionSequence::Worse;
1905 }
1906 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001907
Douglas Gregor14046502008-10-23 00:40:37 +00001908 return ImplicitConversionSequence::Indistinguishable;
1909}
1910
Douglas Gregor81c29152008-10-29 00:13:59 +00001911/// TryCopyInitialization - Try to copy-initialize a value of type
1912/// ToType from the expression From. Return the implicit conversion
1913/// sequence required to pass this argument, which may be a bad
1914/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001915/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001916/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1917/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001918ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001919Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001920 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001921 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001922 ImplicitConversionSequence ICS;
Sebastian Redla55834a2009-04-12 17:16:29 +00001923 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1924 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001925 return ICS;
1926 } else {
Sebastian Redla55834a2009-04-12 17:16:29 +00001927 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1928 ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001929 }
1930}
1931
Sebastian Redla55834a2009-04-12 17:16:29 +00001932/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1933/// the expression @p From. Returns true (and emits a diagnostic) if there was
1934/// an error, returns false if the initialization succeeded. Elidable should
1935/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1936/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001937bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001938 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001939 if (!getLangOptions().CPlusPlus) {
1940 // In C, argument passing is the same as performing an assignment.
1941 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001942
Douglas Gregor81c29152008-10-29 00:13:59 +00001943 AssignConvertType ConvTy =
1944 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001945 if (ConvTy != Compatible &&
1946 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1947 ConvTy = Compatible;
1948
Douglas Gregor81c29152008-10-29 00:13:59 +00001949 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1950 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001951 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001952
Chris Lattner271d4c22008-11-24 05:29:24 +00001953 if (ToType->isReferenceType())
1954 return CheckReferenceInit(From, ToType);
1955
Sebastian Redla55834a2009-04-12 17:16:29 +00001956 if (!PerformImplicitConversion(From, ToType, Flavor,
1957 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001958 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001959
Chris Lattner271d4c22008-11-24 05:29:24 +00001960 return Diag(From->getSourceRange().getBegin(),
1961 diag::err_typecheck_convert_incompatible)
1962 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001963}
1964
Douglas Gregor5ed15042008-11-18 23:14:02 +00001965/// TryObjectArgumentInitialization - Try to initialize the object
1966/// parameter of the given member function (@c Method) from the
1967/// expression @p From.
1968ImplicitConversionSequence
1969Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1970 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1971 unsigned MethodQuals = Method->getTypeQualifiers();
1972 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1973
1974 // Set up the conversion sequence as a "bad" conversion, to allow us
1975 // to exit early.
1976 ImplicitConversionSequence ICS;
1977 ICS.Standard.setAsIdentityConversion();
1978 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1979
1980 // We need to have an object of class type.
1981 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001982 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001983 FromType = PT->getPointeeType();
1984
1985 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00001986
1987 // The implicit object parmeter is has the type "reference to cv X",
1988 // where X is the class of which the function is a member
1989 // (C++ [over.match.funcs]p4). However, when finding an implicit
1990 // conversion sequence for the argument, we are not allowed to
1991 // create temporaries or perform user-defined conversions
1992 // (C++ [over.match.funcs]p5). We perform a simplified version of
1993 // reference binding here, that allows class rvalues to bind to
1994 // non-constant references.
1995
1996 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1997 // with the implicit object parameter (C++ [over.match.funcs]p5).
1998 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1999 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2000 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2001 return ICS;
2002
2003 // Check that we have either the same type or a derived type. It
2004 // affects the conversion rank.
2005 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2006 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2007 ICS.Standard.Second = ICK_Identity;
2008 else if (IsDerivedFrom(FromType, ClassType))
2009 ICS.Standard.Second = ICK_Derived_To_Base;
2010 else
2011 return ICS;
2012
2013 // Success. Mark this as a reference binding.
2014 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2015 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2016 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2017 ICS.Standard.ReferenceBinding = true;
2018 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00002019 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002020 return ICS;
2021}
2022
2023/// PerformObjectArgumentInitialization - Perform initialization of
2024/// the implicit object parameter for the given Method with the given
2025/// expression.
2026bool
2027Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002028 QualType FromRecordType, DestType;
2029 QualType ImplicitParamRecordType =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002030 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002031
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002032 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002033 FromRecordType = PT->getPointeeType();
2034 DestType = Method->getThisType(Context);
2035 } else {
2036 FromRecordType = From->getType();
2037 DestType = ImplicitParamRecordType;
2038 }
2039
Douglas Gregor5ed15042008-11-18 23:14:02 +00002040 ImplicitConversionSequence ICS
2041 = TryObjectArgumentInitialization(From, Method);
2042 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2043 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002044 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002045 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2046
Douglas Gregor5ed15042008-11-18 23:14:02 +00002047 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002048 CheckDerivedToBaseConversion(FromRecordType,
2049 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002050 From->getSourceRange().getBegin(),
2051 From->getSourceRange()))
2052 return true;
2053
Anders Carlssone25b6cd2009-08-07 18:45:49 +00002054 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2055 /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002056 return false;
2057}
2058
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002059/// TryContextuallyConvertToBool - Attempt to contextually convert the
2060/// expression From to bool (C++0x [conv]p3).
2061ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2062 return TryImplicitConversion(From, Context.BoolTy, false, true);
2063}
2064
2065/// PerformContextuallyConvertToBool - Perform a contextual conversion
2066/// of the expression From to bool (C++0x [conv]p3).
2067bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2068 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2069 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2070 return false;
2071
2072 return Diag(From->getSourceRange().getBegin(),
2073 diag::err_typecheck_bool_condition)
2074 << From->getType() << From->getSourceRange();
2075}
2076
Douglas Gregord2baafd2008-10-21 16:13:35 +00002077/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002078/// candidate functions, using the given function call arguments. If
2079/// @p SuppressUserConversions, then don't allow user-defined
2080/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002081/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2082/// hacky way to implement the overloading rules for elidable copy
2083/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002084void
2085Sema::AddOverloadCandidate(FunctionDecl *Function,
2086 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002087 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002088 bool SuppressUserConversions,
2089 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002090{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002091 const FunctionProtoType* Proto
2092 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002093 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002094 assert(!isa<CXXConversionDecl>(Function) &&
2095 "Use AddConversionCandidate for conversion functions");
Douglas Gregorb60eb752009-06-25 22:08:12 +00002096 assert(!Function->getDescribedFunctionTemplate() &&
2097 "Use AddTemplateOverloadCandidate for function templates");
2098
Douglas Gregor3257fb52008-12-22 05:46:06 +00002099 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002100 if (!isa<CXXConstructorDecl>(Method)) {
2101 // If we get here, it's because we're calling a member function
2102 // that is named without a member access expression (e.g.,
2103 // "this->f") that was either written explicitly or created
2104 // implicitly. This can happen with a qualified call to a member
2105 // function, e.g., X::f(). We use a NULL object as the implied
2106 // object argument (C++ [over.call.func]p3).
2107 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2108 SuppressUserConversions, ForceRValue);
2109 return;
2110 }
2111 // We treat a constructor like a non-member function, since its object
2112 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002113 }
2114
2115
Douglas Gregord2baafd2008-10-21 16:13:35 +00002116 // Add this candidate
2117 CandidateSet.push_back(OverloadCandidate());
2118 OverloadCandidate& Candidate = CandidateSet.back();
2119 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002120 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002121 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002122 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002123
2124 unsigned NumArgsInProto = Proto->getNumArgs();
2125
2126 // (C++ 13.3.2p2): A candidate function having fewer than m
2127 // parameters is viable only if it has an ellipsis in its parameter
2128 // list (8.3.5).
2129 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2130 Candidate.Viable = false;
2131 return;
2132 }
2133
2134 // (C++ 13.3.2p2): A candidate function having more than m parameters
2135 // is viable only if the (m+1)st parameter has a default argument
2136 // (8.3.6). For the purposes of overload resolution, the
2137 // parameter list is truncated on the right, so that there are
2138 // exactly m parameters.
2139 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2140 if (NumArgs < MinRequiredArgs) {
2141 // Not enough arguments.
2142 Candidate.Viable = false;
2143 return;
2144 }
2145
2146 // Determine the implicit conversion sequences for each of the
2147 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002148 Candidate.Conversions.resize(NumArgs);
2149 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2150 if (ArgIdx < NumArgsInProto) {
2151 // (C++ 13.3.2p3): for F to be a viable function, there shall
2152 // exist for each argument an implicit conversion sequence
2153 // (13.3.3.1) that converts that argument to the corresponding
2154 // parameter of F.
2155 QualType ParamType = Proto->getArgType(ArgIdx);
2156 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002157 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002158 SuppressUserConversions, ForceRValue);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002159 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002160 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002161 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002162 break;
2163 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002164 } else {
2165 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2166 // argument for which there is no corresponding parameter is
2167 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2168 Candidate.Conversions[ArgIdx].ConversionKind
2169 = ImplicitConversionSequence::EllipsisConversion;
2170 }
2171 }
2172}
2173
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002174/// \brief Add all of the function declarations in the given function set to
2175/// the overload canddiate set.
2176void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2177 Expr **Args, unsigned NumArgs,
2178 OverloadCandidateSet& CandidateSet,
2179 bool SuppressUserConversions) {
2180 for (FunctionSet::const_iterator F = Functions.begin(),
2181 FEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00002182 F != FEnd; ++F) {
2183 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2184 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2185 SuppressUserConversions);
2186 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002187 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2188 /*FIXME: explicit args */false, 0, 0,
2189 Args, NumArgs, CandidateSet,
Douglas Gregor993a0602009-06-27 21:05:07 +00002190 SuppressUserConversions);
2191 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002192}
2193
Douglas Gregor5ed15042008-11-18 23:14:02 +00002194/// AddMethodCandidate - Adds the given C++ member function to the set
2195/// of candidate functions, using the given function call arguments
2196/// and the object argument (@c Object). For example, in a call
2197/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2198/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2199/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002200/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2201/// a slightly hacky way to implement the overloading rules for elidable copy
2202/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002203void
2204Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2205 Expr **Args, unsigned NumArgs,
2206 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002207 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002208{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002209 const FunctionProtoType* Proto
2210 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002211 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002212 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002213 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002214 assert(!isa<CXXConstructorDecl>(Method) &&
2215 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002216
2217 // Add this candidate
2218 CandidateSet.push_back(OverloadCandidate());
2219 OverloadCandidate& Candidate = CandidateSet.back();
2220 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002221 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002222 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002223
2224 unsigned NumArgsInProto = Proto->getNumArgs();
2225
2226 // (C++ 13.3.2p2): A candidate function having fewer than m
2227 // parameters is viable only if it has an ellipsis in its parameter
2228 // list (8.3.5).
2229 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2230 Candidate.Viable = false;
2231 return;
2232 }
2233
2234 // (C++ 13.3.2p2): A candidate function having more than m parameters
2235 // is viable only if the (m+1)st parameter has a default argument
2236 // (8.3.6). For the purposes of overload resolution, the
2237 // parameter list is truncated on the right, so that there are
2238 // exactly m parameters.
2239 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2240 if (NumArgs < MinRequiredArgs) {
2241 // Not enough arguments.
2242 Candidate.Viable = false;
2243 return;
2244 }
2245
2246 Candidate.Viable = true;
2247 Candidate.Conversions.resize(NumArgs + 1);
2248
Douglas Gregor3257fb52008-12-22 05:46:06 +00002249 if (Method->isStatic() || !Object)
2250 // The implicit object argument is ignored.
2251 Candidate.IgnoreObjectArgument = true;
2252 else {
2253 // Determine the implicit conversion sequence for the object
2254 // parameter.
2255 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2256 if (Candidate.Conversions[0].ConversionKind
2257 == ImplicitConversionSequence::BadConversion) {
2258 Candidate.Viable = false;
2259 return;
2260 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002261 }
2262
2263 // Determine the implicit conversion sequences for each of the
2264 // arguments.
2265 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2266 if (ArgIdx < NumArgsInProto) {
2267 // (C++ 13.3.2p3): for F to be a viable function, there shall
2268 // exist for each argument an implicit conversion sequence
2269 // (13.3.3.1) that converts that argument to the corresponding
2270 // parameter of F.
2271 QualType ParamType = Proto->getArgType(ArgIdx);
2272 Candidate.Conversions[ArgIdx + 1]
2273 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002274 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002275 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2276 == ImplicitConversionSequence::BadConversion) {
2277 Candidate.Viable = false;
2278 break;
2279 }
2280 } else {
2281 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2282 // argument for which there is no corresponding parameter is
2283 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2284 Candidate.Conversions[ArgIdx + 1].ConversionKind
2285 = ImplicitConversionSequence::EllipsisConversion;
2286 }
2287 }
2288}
2289
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002290/// \brief Add a C++ member function template as a candidate to the candidate
2291/// set, using template argument deduction to produce an appropriate member
2292/// function template specialization.
2293void
2294Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2295 bool HasExplicitTemplateArgs,
2296 const TemplateArgument *ExplicitTemplateArgs,
2297 unsigned NumExplicitTemplateArgs,
2298 Expr *Object, Expr **Args, unsigned NumArgs,
2299 OverloadCandidateSet& CandidateSet,
2300 bool SuppressUserConversions,
2301 bool ForceRValue) {
2302 // C++ [over.match.funcs]p7:
2303 // In each case where a candidate is a function template, candidate
2304 // function template specializations are generated using template argument
2305 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2306 // candidate functions in the usual way.113) A given name can refer to one
2307 // or more function templates and also to a set of overloaded non-template
2308 // functions. In such a case, the candidate functions generated from each
2309 // function template are combined with the set of non-template candidate
2310 // functions.
2311 TemplateDeductionInfo Info(Context);
2312 FunctionDecl *Specialization = 0;
2313 if (TemplateDeductionResult Result
2314 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2315 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2316 Args, NumArgs, Specialization, Info)) {
2317 // FIXME: Record what happened with template argument deduction, so
2318 // that we can give the user a beautiful diagnostic.
2319 (void)Result;
2320 return;
2321 }
2322
2323 // Add the function template specialization produced by template argument
2324 // deduction as a candidate.
2325 assert(Specialization && "Missing member function template specialization?");
2326 assert(isa<CXXMethodDecl>(Specialization) &&
2327 "Specialization is not a member function?");
2328 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2329 CandidateSet, SuppressUserConversions, ForceRValue);
2330}
2331
Douglas Gregor8c860df2009-08-21 23:19:43 +00002332/// \brief Add a C++ function template specialization as a candidate
2333/// in the candidate set, using template argument deduction to produce
2334/// an appropriate function template specialization.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002335void
2336Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002337 bool HasExplicitTemplateArgs,
2338 const TemplateArgument *ExplicitTemplateArgs,
2339 unsigned NumExplicitTemplateArgs,
Douglas Gregorb60eb752009-06-25 22:08:12 +00002340 Expr **Args, unsigned NumArgs,
2341 OverloadCandidateSet& CandidateSet,
2342 bool SuppressUserConversions,
2343 bool ForceRValue) {
2344 // C++ [over.match.funcs]p7:
2345 // In each case where a candidate is a function template, candidate
2346 // function template specializations are generated using template argument
2347 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2348 // candidate functions in the usual way.113) A given name can refer to one
2349 // or more function templates and also to a set of overloaded non-template
2350 // functions. In such a case, the candidate functions generated from each
2351 // function template are combined with the set of non-template candidate
2352 // functions.
2353 TemplateDeductionInfo Info(Context);
2354 FunctionDecl *Specialization = 0;
2355 if (TemplateDeductionResult Result
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002356 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2357 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2358 Args, NumArgs, Specialization, Info)) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00002359 // FIXME: Record what happened with template argument deduction, so
2360 // that we can give the user a beautiful diagnostic.
2361 (void)Result;
2362 return;
2363 }
2364
2365 // Add the function template specialization produced by template argument
2366 // deduction as a candidate.
2367 assert(Specialization && "Missing function template specialization?");
2368 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2369 SuppressUserConversions, ForceRValue);
2370}
2371
Douglas Gregor60714f92008-11-07 22:36:19 +00002372/// AddConversionCandidate - Add a C++ conversion function as a
2373/// candidate in the candidate set (C++ [over.match.conv],
2374/// C++ [over.match.copy]). From is the expression we're converting from,
2375/// and ToType is the type that we're eventually trying to convert to
2376/// (which may or may not be the same type as the type that the
2377/// conversion function produces).
2378void
2379Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2380 Expr *From, QualType ToType,
2381 OverloadCandidateSet& CandidateSet) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002382 assert(!Conversion->getDescribedFunctionTemplate() &&
2383 "Conversion function templates use AddTemplateConversionCandidate");
2384
Douglas Gregor60714f92008-11-07 22:36:19 +00002385 // Add this candidate
2386 CandidateSet.push_back(OverloadCandidate());
2387 OverloadCandidate& Candidate = CandidateSet.back();
2388 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002389 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002390 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002391 Candidate.FinalConversion.setAsIdentityConversion();
2392 Candidate.FinalConversion.FromTypePtr
2393 = Conversion->getConversionType().getAsOpaquePtr();
2394 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2395
Douglas Gregor5ed15042008-11-18 23:14:02 +00002396 // Determine the implicit conversion sequence for the implicit
2397 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002398 Candidate.Viable = true;
2399 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002400 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002401
Douglas Gregor60714f92008-11-07 22:36:19 +00002402 if (Candidate.Conversions[0].ConversionKind
2403 == ImplicitConversionSequence::BadConversion) {
2404 Candidate.Viable = false;
2405 return;
2406 }
2407
2408 // To determine what the conversion from the result of calling the
2409 // conversion function to the type we're eventually trying to
2410 // convert to (ToType), we need to synthesize a call to the
2411 // conversion function and attempt copy initialization from it. This
2412 // makes sure that we get the right semantics with respect to
2413 // lvalues/rvalues and the type. Fortunately, we can allocate this
2414 // call on the stack and we don't need its arguments to be
2415 // well-formed.
2416 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2417 SourceLocation());
2418 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002419 CastExpr::CK_Unknown,
Douglas Gregor70d26122008-11-12 17:17:38 +00002420 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002421
2422 // Note that it is safe to allocate CallExpr on the stack here because
2423 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2424 // allocator).
2425 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002426 Conversion->getConversionType().getNonReferenceType(),
2427 SourceLocation());
2428 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2429 switch (ICS.ConversionKind) {
2430 case ImplicitConversionSequence::StandardConversion:
2431 Candidate.FinalConversion = ICS.Standard;
2432 break;
2433
2434 case ImplicitConversionSequence::BadConversion:
2435 Candidate.Viable = false;
2436 break;
2437
2438 default:
2439 assert(false &&
2440 "Can only end up with a standard conversion sequence or failure");
2441 }
2442}
2443
Douglas Gregor8c860df2009-08-21 23:19:43 +00002444/// \brief Adds a conversion function template specialization
2445/// candidate to the overload set, using template argument deduction
2446/// to deduce the template arguments of the conversion function
2447/// template from the type that we are converting to (C++
2448/// [temp.deduct.conv]).
2449void
2450Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2451 Expr *From, QualType ToType,
2452 OverloadCandidateSet &CandidateSet) {
2453 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2454 "Only conversion function templates permitted here");
2455
2456 TemplateDeductionInfo Info(Context);
2457 CXXConversionDecl *Specialization = 0;
2458 if (TemplateDeductionResult Result
2459 = DeduceTemplateArguments(FunctionTemplate, ToType,
2460 Specialization, Info)) {
2461 // FIXME: Record what happened with template argument deduction, so
2462 // that we can give the user a beautiful diagnostic.
2463 (void)Result;
2464 return;
2465 }
2466
2467 // Add the conversion function template specialization produced by
2468 // template argument deduction as a candidate.
2469 assert(Specialization && "Missing function template specialization?");
2470 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2471}
2472
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002473/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2474/// converts the given @c Object to a function pointer via the
2475/// conversion function @c Conversion, and then attempts to call it
2476/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2477/// the type of function that we'll eventually be calling.
2478void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002479 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002480 Expr *Object, Expr **Args, unsigned NumArgs,
2481 OverloadCandidateSet& CandidateSet) {
2482 CandidateSet.push_back(OverloadCandidate());
2483 OverloadCandidate& Candidate = CandidateSet.back();
2484 Candidate.Function = 0;
2485 Candidate.Surrogate = Conversion;
2486 Candidate.Viable = true;
2487 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002488 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002489 Candidate.Conversions.resize(NumArgs + 1);
2490
2491 // Determine the implicit conversion sequence for the implicit
2492 // object parameter.
2493 ImplicitConversionSequence ObjectInit
2494 = TryObjectArgumentInitialization(Object, Conversion);
2495 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2496 Candidate.Viable = false;
2497 return;
2498 }
2499
2500 // The first conversion is actually a user-defined conversion whose
2501 // first conversion is ObjectInit's standard conversion (which is
2502 // effectively a reference binding). Record it as such.
2503 Candidate.Conversions[0].ConversionKind
2504 = ImplicitConversionSequence::UserDefinedConversion;
2505 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2506 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2507 Candidate.Conversions[0].UserDefined.After
2508 = Candidate.Conversions[0].UserDefined.Before;
2509 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2510
2511 // Find the
2512 unsigned NumArgsInProto = Proto->getNumArgs();
2513
2514 // (C++ 13.3.2p2): A candidate function having fewer than m
2515 // parameters is viable only if it has an ellipsis in its parameter
2516 // list (8.3.5).
2517 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2518 Candidate.Viable = false;
2519 return;
2520 }
2521
2522 // Function types don't have any default arguments, so just check if
2523 // we have enough arguments.
2524 if (NumArgs < NumArgsInProto) {
2525 // Not enough arguments.
2526 Candidate.Viable = false;
2527 return;
2528 }
2529
2530 // Determine the implicit conversion sequences for each of the
2531 // arguments.
2532 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2533 if (ArgIdx < NumArgsInProto) {
2534 // (C++ 13.3.2p3): for F to be a viable function, there shall
2535 // exist for each argument an implicit conversion sequence
2536 // (13.3.3.1) that converts that argument to the corresponding
2537 // parameter of F.
2538 QualType ParamType = Proto->getArgType(ArgIdx);
2539 Candidate.Conversions[ArgIdx + 1]
2540 = TryCopyInitialization(Args[ArgIdx], ParamType,
2541 /*SuppressUserConversions=*/false);
2542 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2543 == ImplicitConversionSequence::BadConversion) {
2544 Candidate.Viable = false;
2545 break;
2546 }
2547 } else {
2548 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2549 // argument for which there is no corresponding parameter is
2550 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2551 Candidate.Conversions[ArgIdx + 1].ConversionKind
2552 = ImplicitConversionSequence::EllipsisConversion;
2553 }
2554 }
2555}
2556
Mike Stumpe127ae32009-05-16 07:39:55 +00002557// FIXME: This will eventually be removed, once we've migrated all of the
2558// operator overloading logic over to the scheme used by binary operators, which
2559// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002560void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002561 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002562 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002563 OverloadCandidateSet& CandidateSet,
2564 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002565
2566 FunctionSet Functions;
2567
2568 QualType T1 = Args[0]->getType();
2569 QualType T2;
2570 if (NumArgs > 1)
2571 T2 = Args[1]->getType();
2572
2573 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002574 if (S)
2575 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002576 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2577 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2578 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2579 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2580}
2581
2582/// \brief Add overload candidates for overloaded operators that are
2583/// member functions.
2584///
2585/// Add the overloaded operator candidates that are member functions
2586/// for the operator Op that was used in an operator expression such
2587/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2588/// CandidateSet will store the added overload candidates. (C++
2589/// [over.match.oper]).
2590void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2591 SourceLocation OpLoc,
2592 Expr **Args, unsigned NumArgs,
2593 OverloadCandidateSet& CandidateSet,
2594 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002595 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2596
2597 // C++ [over.match.oper]p3:
2598 // For a unary operator @ with an operand of a type whose
2599 // cv-unqualified version is T1, and for a binary operator @ with
2600 // a left operand of a type whose cv-unqualified version is T1 and
2601 // a right operand of a type whose cv-unqualified version is T2,
2602 // three sets of candidate functions, designated member
2603 // candidates, non-member candidates and built-in candidates, are
2604 // constructed as follows:
2605 QualType T1 = Args[0]->getType();
2606 QualType T2;
2607 if (NumArgs > 1)
2608 T2 = Args[1]->getType();
2609
2610 // -- If T1 is a class type, the set of member candidates is the
2611 // result of the qualified lookup of T1::operator@
2612 // (13.3.1.1.1); otherwise, the set of member candidates is
2613 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002614 // FIXME: Lookup in base classes, too!
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002615 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002616 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002617 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002618 Oper != OperEnd; ++Oper)
2619 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2620 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002621 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002622 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002623}
2624
Douglas Gregor70d26122008-11-12 17:17:38 +00002625/// AddBuiltinCandidate - Add a candidate for a built-in
2626/// operator. ResultTy and ParamTys are the result and parameter types
2627/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002628/// arguments being passed to the candidate. IsAssignmentOperator
2629/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002630/// operator. NumContextualBoolArguments is the number of arguments
2631/// (at the beginning of the argument list) that will be contextually
2632/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002633void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2634 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002635 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002636 bool IsAssignmentOperator,
2637 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002638 // Add this candidate
2639 CandidateSet.push_back(OverloadCandidate());
2640 OverloadCandidate& Candidate = CandidateSet.back();
2641 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002642 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002643 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002644 Candidate.BuiltinTypes.ResultTy = ResultTy;
2645 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2646 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2647
2648 // Determine the implicit conversion sequences for each of the
2649 // arguments.
2650 Candidate.Viable = true;
2651 Candidate.Conversions.resize(NumArgs);
2652 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002653 // C++ [over.match.oper]p4:
2654 // For the built-in assignment operators, conversions of the
2655 // left operand are restricted as follows:
2656 // -- no temporaries are introduced to hold the left operand, and
2657 // -- no user-defined conversions are applied to the left
2658 // operand to achieve a type match with the left-most
2659 // parameter of a built-in candidate.
2660 //
2661 // We block these conversions by turning off user-defined
2662 // conversions, since that is the only way that initialization of
2663 // a reference to a non-class type can occur from something that
2664 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002665 if (ArgIdx < NumContextualBoolArguments) {
2666 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2667 "Contextual conversion to bool requires bool type");
2668 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2669 } else {
2670 Candidate.Conversions[ArgIdx]
2671 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2672 ArgIdx == 0 && IsAssignmentOperator);
2673 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002674 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002675 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002676 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002677 break;
2678 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002679 }
2680}
2681
2682/// BuiltinCandidateTypeSet - A set of types that will be used for the
2683/// candidate operator functions for built-in operators (C++
2684/// [over.built]). The types are separated into pointer types and
2685/// enumeration types.
2686class BuiltinCandidateTypeSet {
2687 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002688 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002689
2690 /// PointerTypes - The set of pointer types that will be used in the
2691 /// built-in candidates.
2692 TypeSet PointerTypes;
2693
Sebastian Redl674d1b72009-04-19 21:53:20 +00002694 /// MemberPointerTypes - The set of member pointer types that will be
2695 /// used in the built-in candidates.
2696 TypeSet MemberPointerTypes;
2697
Douglas Gregor70d26122008-11-12 17:17:38 +00002698 /// EnumerationTypes - The set of enumeration types that will be
2699 /// used in the built-in candidates.
2700 TypeSet EnumerationTypes;
2701
2702 /// Context - The AST context in which we will build the type sets.
2703 ASTContext &Context;
2704
Sebastian Redl674d1b72009-04-19 21:53:20 +00002705 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2706 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002707
2708public:
2709 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002710 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002711
2712 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2713
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002714 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2715 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002716
2717 /// pointer_begin - First pointer type found;
2718 iterator pointer_begin() { return PointerTypes.begin(); }
2719
Sebastian Redl674d1b72009-04-19 21:53:20 +00002720 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002721 iterator pointer_end() { return PointerTypes.end(); }
2722
Sebastian Redl674d1b72009-04-19 21:53:20 +00002723 /// member_pointer_begin - First member pointer type found;
2724 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2725
2726 /// member_pointer_end - Past the last member pointer type found;
2727 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2728
Douglas Gregor70d26122008-11-12 17:17:38 +00002729 /// enumeration_begin - First enumeration type found;
2730 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2731
Sebastian Redl674d1b72009-04-19 21:53:20 +00002732 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002733 iterator enumeration_end() { return EnumerationTypes.end(); }
2734};
2735
Sebastian Redl674d1b72009-04-19 21:53:20 +00002736/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002737/// the set of pointer types along with any more-qualified variants of
2738/// that type. For example, if @p Ty is "int const *", this routine
2739/// will add "int const *", "int const volatile *", "int const
2740/// restrict *", and "int const volatile restrict *" to the set of
2741/// pointer types. Returns true if the add of @p Ty itself succeeded,
2742/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002743bool
2744BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002745 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002746 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002747 return false;
2748
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002749 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002750 QualType PointeeTy = PointerTy->getPointeeType();
2751 // FIXME: Optimize this so that we don't keep trying to add the same types.
2752
Mike Stumpe127ae32009-05-16 07:39:55 +00002753 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2754 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002755 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002756 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002757 (Context.getPointerType(PointeeTy.withConst()));
2758 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002759 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002760 (Context.getPointerType(PointeeTy.withVolatile()));
2761 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002762 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002763 (Context.getPointerType(PointeeTy.withRestrict()));
2764 }
2765
2766 return true;
2767}
2768
Sebastian Redl674d1b72009-04-19 21:53:20 +00002769/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2770/// to the set of pointer types along with any more-qualified variants of
2771/// that type. For example, if @p Ty is "int const *", this routine
2772/// will add "int const *", "int const volatile *", "int const
2773/// restrict *", and "int const volatile restrict *" to the set of
2774/// pointer types. Returns true if the add of @p Ty itself succeeded,
2775/// false otherwise.
2776bool
2777BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2778 QualType Ty) {
2779 // Insert this type.
2780 if (!MemberPointerTypes.insert(Ty))
2781 return false;
2782
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002783 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl674d1b72009-04-19 21:53:20 +00002784 QualType PointeeTy = PointerTy->getPointeeType();
2785 const Type *ClassTy = PointerTy->getClass();
2786 // FIXME: Optimize this so that we don't keep trying to add the same types.
2787
2788 if (!PointeeTy.isConstQualified())
2789 AddMemberPointerWithMoreQualifiedTypeVariants
2790 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2791 if (!PointeeTy.isVolatileQualified())
2792 AddMemberPointerWithMoreQualifiedTypeVariants
2793 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2794 if (!PointeeTy.isRestrictQualified())
2795 AddMemberPointerWithMoreQualifiedTypeVariants
2796 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2797 }
2798
2799 return true;
2800}
2801
Douglas Gregor70d26122008-11-12 17:17:38 +00002802/// AddTypesConvertedFrom - Add each of the types to which the type @p
2803/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002804/// primarily interested in pointer types and enumeration types. We also
2805/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002806/// AllowUserConversions is true if we should look at the conversion
2807/// functions of a class type, and AllowExplicitConversions if we
2808/// should also include the explicit conversion functions of a class
2809/// type.
2810void
2811BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2812 bool AllowUserConversions,
2813 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002814 // Only deal with canonical types.
2815 Ty = Context.getCanonicalType(Ty);
2816
2817 // Look through reference types; they aren't part of the type of an
2818 // expression for the purposes of conversions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002819 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregor70d26122008-11-12 17:17:38 +00002820 Ty = RefTy->getPointeeType();
2821
2822 // We don't care about qualifiers on the type.
2823 Ty = Ty.getUnqualifiedType();
2824
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002825 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002826 QualType PointeeTy = PointerTy->getPointeeType();
2827
2828 // Insert our type, and its more-qualified variants, into the set
2829 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002830 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002831 return;
2832
2833 // Add 'cv void*' to our set of types.
2834 if (!Ty->isVoidType()) {
2835 QualType QualVoid
2836 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002837 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002838 }
2839
2840 // If this is a pointer to a class type, add pointers to its bases
2841 // (with the same level of cv-qualification as the original
2842 // derived class, of course).
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002843 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002844 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2845 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2846 Base != ClassDecl->bases_end(); ++Base) {
2847 QualType BaseTy = Context.getCanonicalType(Base->getType());
2848 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2849
2850 // Add the pointer type, recursively, so that we get all of
2851 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002852 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002853 }
2854 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002855 } else if (Ty->isMemberPointerType()) {
2856 // Member pointers are far easier, since the pointee can't be converted.
2857 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2858 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002859 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002860 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002861 } else if (AllowUserConversions) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002862 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002863 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2864 // FIXME: Visit conversion functions in the base classes, too.
2865 OverloadedFunctionDecl *Conversions
2866 = ClassDecl->getConversionFunctions();
2867 for (OverloadedFunctionDecl::function_iterator Func
2868 = Conversions->function_begin();
2869 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002870 CXXConversionDecl *Conv;
2871 FunctionTemplateDecl *ConvTemplate;
2872 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2873
2874 // Skip conversion function templates; they don't tell us anything
2875 // about which builtin types we can convert to.
2876 if (ConvTemplate)
2877 continue;
2878
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002879 if (AllowExplicitConversions || !Conv->isExplicit())
2880 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002881 }
2882 }
2883 }
2884}
2885
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002886/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2887/// operator overloads to the candidate set (C++ [over.built]), based
2888/// on the operator @p Op and the arguments given. For example, if the
2889/// operator is a binary '+', this routine might add "int
2890/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002891void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002892Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2893 Expr **Args, unsigned NumArgs,
2894 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002895 // The set of "promoted arithmetic types", which are the arithmetic
2896 // types are that preserved by promotion (C++ [over.built]p2). Note
2897 // that the first few of these types are the promoted integral
2898 // types; these types need to be first.
2899 // FIXME: What about complex?
2900 const unsigned FirstIntegralType = 0;
2901 const unsigned LastIntegralType = 13;
2902 const unsigned FirstPromotedIntegralType = 7,
2903 LastPromotedIntegralType = 13;
2904 const unsigned FirstPromotedArithmeticType = 7,
2905 LastPromotedArithmeticType = 16;
2906 const unsigned NumArithmeticTypes = 16;
2907 QualType ArithmeticTypes[NumArithmeticTypes] = {
Alisdair Meredith2bcacb62009-07-14 06:30:34 +00002908 Context.BoolTy, Context.CharTy, Context.WCharTy,
2909// Context.Char16Ty, Context.Char32Ty,
Douglas Gregor70d26122008-11-12 17:17:38 +00002910 Context.SignedCharTy, Context.ShortTy,
2911 Context.UnsignedCharTy, Context.UnsignedShortTy,
2912 Context.IntTy, Context.LongTy, Context.LongLongTy,
2913 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2914 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2915 };
2916
2917 // Find all of the types that the arguments can convert to, but only
2918 // if the operator we're looking at has built-in operator candidates
2919 // that make use of these types.
2920 BuiltinCandidateTypeSet CandidateTypes(Context);
2921 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2922 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002923 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002924 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002925 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00002926 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002927 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002928 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2929 true,
2930 (Op == OO_Exclaim ||
2931 Op == OO_AmpAmp ||
2932 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002933 }
2934
2935 bool isComparison = false;
2936 switch (Op) {
2937 case OO_None:
2938 case NUM_OVERLOADED_OPERATORS:
2939 assert(false && "Expected an overloaded operator");
2940 break;
2941
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002942 case OO_Star: // '*' is either unary or binary
2943 if (NumArgs == 1)
2944 goto UnaryStar;
2945 else
2946 goto BinaryStar;
2947 break;
2948
2949 case OO_Plus: // '+' is either unary or binary
2950 if (NumArgs == 1)
2951 goto UnaryPlus;
2952 else
2953 goto BinaryPlus;
2954 break;
2955
2956 case OO_Minus: // '-' is either unary or binary
2957 if (NumArgs == 1)
2958 goto UnaryMinus;
2959 else
2960 goto BinaryMinus;
2961 break;
2962
2963 case OO_Amp: // '&' is either unary or binary
2964 if (NumArgs == 1)
2965 goto UnaryAmp;
2966 else
2967 goto BinaryAmp;
2968
2969 case OO_PlusPlus:
2970 case OO_MinusMinus:
2971 // C++ [over.built]p3:
2972 //
2973 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2974 // is either volatile or empty, there exist candidate operator
2975 // functions of the form
2976 //
2977 // VQ T& operator++(VQ T&);
2978 // T operator++(VQ T&, int);
2979 //
2980 // C++ [over.built]p4:
2981 //
2982 // For every pair (T, VQ), where T is an arithmetic type other
2983 // than bool, and VQ is either volatile or empty, there exist
2984 // candidate operator functions of the form
2985 //
2986 // VQ T& operator--(VQ T&);
2987 // T operator--(VQ T&, int);
2988 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2989 Arith < NumArithmeticTypes; ++Arith) {
2990 QualType ArithTy = ArithmeticTypes[Arith];
2991 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00002992 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002993
2994 // Non-volatile version.
2995 if (NumArgs == 1)
2996 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2997 else
2998 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2999
3000 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003001 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003002 if (NumArgs == 1)
3003 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3004 else
3005 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3006 }
3007
3008 // C++ [over.built]p5:
3009 //
3010 // For every pair (T, VQ), where T is a cv-qualified or
3011 // cv-unqualified object type, and VQ is either volatile or
3012 // empty, there exist candidate operator functions of the form
3013 //
3014 // T*VQ& operator++(T*VQ&);
3015 // T*VQ& operator--(T*VQ&);
3016 // T* operator++(T*VQ&, int);
3017 // T* operator--(T*VQ&, int);
3018 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3019 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3020 // Skip pointer types that aren't pointers to object types.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003021 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003022 continue;
3023
3024 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003025 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003026 };
3027
3028 // Without volatile
3029 if (NumArgs == 1)
3030 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3031 else
3032 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3033
3034 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3035 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00003036 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003037 if (NumArgs == 1)
3038 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3039 else
3040 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3041 }
3042 }
3043 break;
3044
3045 UnaryStar:
3046 // C++ [over.built]p6:
3047 // For every cv-qualified or cv-unqualified object type T, there
3048 // exist candidate operator functions of the form
3049 //
3050 // T& operator*(T*);
3051 //
3052 // C++ [over.built]p7:
3053 // For every function type T, there exist candidate operator
3054 // functions of the form
3055 // T& operator*(T*);
3056 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3057 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3058 QualType ParamTy = *Ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003059 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003060 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003061 &ParamTy, Args, 1, CandidateSet);
3062 }
3063 break;
3064
3065 UnaryPlus:
3066 // C++ [over.built]p8:
3067 // For every type T, there exist candidate operator functions of
3068 // the form
3069 //
3070 // T* operator+(T*);
3071 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3072 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3073 QualType ParamTy = *Ptr;
3074 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3075 }
3076
3077 // Fall through
3078
3079 UnaryMinus:
3080 // C++ [over.built]p9:
3081 // For every promoted arithmetic type T, there exist candidate
3082 // operator functions of the form
3083 //
3084 // T operator+(T);
3085 // T operator-(T);
3086 for (unsigned Arith = FirstPromotedArithmeticType;
3087 Arith < LastPromotedArithmeticType; ++Arith) {
3088 QualType ArithTy = ArithmeticTypes[Arith];
3089 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3090 }
3091 break;
3092
3093 case OO_Tilde:
3094 // C++ [over.built]p10:
3095 // For every promoted integral type T, there exist candidate
3096 // operator functions of the form
3097 //
3098 // T operator~(T);
3099 for (unsigned Int = FirstPromotedIntegralType;
3100 Int < LastPromotedIntegralType; ++Int) {
3101 QualType IntTy = ArithmeticTypes[Int];
3102 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3103 }
3104 break;
3105
Douglas Gregor70d26122008-11-12 17:17:38 +00003106 case OO_New:
3107 case OO_Delete:
3108 case OO_Array_New:
3109 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00003110 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003111 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00003112 break;
3113
3114 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003115 UnaryAmp:
3116 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00003117 // C++ [over.match.oper]p3:
3118 // -- For the operator ',', the unary operator '&', or the
3119 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00003120 break;
3121
3122 case OO_Less:
3123 case OO_Greater:
3124 case OO_LessEqual:
3125 case OO_GreaterEqual:
3126 case OO_EqualEqual:
3127 case OO_ExclaimEqual:
3128 // C++ [over.built]p15:
3129 //
3130 // For every pointer or enumeration type T, there exist
3131 // candidate operator functions of the form
3132 //
3133 // bool operator<(T, T);
3134 // bool operator>(T, T);
3135 // bool operator<=(T, T);
3136 // bool operator>=(T, T);
3137 // bool operator==(T, T);
3138 // bool operator!=(T, T);
3139 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3140 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3141 QualType ParamTypes[2] = { *Ptr, *Ptr };
3142 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3143 }
3144 for (BuiltinCandidateTypeSet::iterator Enum
3145 = CandidateTypes.enumeration_begin();
3146 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3147 QualType ParamTypes[2] = { *Enum, *Enum };
3148 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3149 }
3150
3151 // Fall through.
3152 isComparison = true;
3153
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003154 BinaryPlus:
3155 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003156 if (!isComparison) {
3157 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3158
3159 // C++ [over.built]p13:
3160 //
3161 // For every cv-qualified or cv-unqualified object type T
3162 // there exist candidate operator functions of the form
3163 //
3164 // T* operator+(T*, ptrdiff_t);
3165 // T& operator[](T*, ptrdiff_t); [BELOW]
3166 // T* operator-(T*, ptrdiff_t);
3167 // T* operator+(ptrdiff_t, T*);
3168 // T& operator[](ptrdiff_t, T*); [BELOW]
3169 //
3170 // C++ [over.built]p14:
3171 //
3172 // For every T, where T is a pointer to object type, there
3173 // exist candidate operator functions of the form
3174 //
3175 // ptrdiff_t operator-(T, T);
3176 for (BuiltinCandidateTypeSet::iterator Ptr
3177 = CandidateTypes.pointer_begin();
3178 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3179 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3180
3181 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3182 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3183
3184 if (Op == OO_Plus) {
3185 // T* operator+(ptrdiff_t, T*);
3186 ParamTypes[0] = ParamTypes[1];
3187 ParamTypes[1] = *Ptr;
3188 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3189 } else {
3190 // ptrdiff_t operator-(T, T);
3191 ParamTypes[1] = *Ptr;
3192 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3193 Args, 2, CandidateSet);
3194 }
3195 }
3196 }
3197 // Fall through
3198
Douglas Gregor70d26122008-11-12 17:17:38 +00003199 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003200 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003201 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003202 // C++ [over.built]p12:
3203 //
3204 // For every pair of promoted arithmetic types L and R, there
3205 // exist candidate operator functions of the form
3206 //
3207 // LR operator*(L, R);
3208 // LR operator/(L, R);
3209 // LR operator+(L, R);
3210 // LR operator-(L, R);
3211 // bool operator<(L, R);
3212 // bool operator>(L, R);
3213 // bool operator<=(L, R);
3214 // bool operator>=(L, R);
3215 // bool operator==(L, R);
3216 // bool operator!=(L, R);
3217 //
3218 // where LR is the result of the usual arithmetic conversions
3219 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003220 //
3221 // C++ [over.built]p24:
3222 //
3223 // For every pair of promoted arithmetic types L and R, there exist
3224 // candidate operator functions of the form
3225 //
3226 // LR operator?(bool, L, R);
3227 //
3228 // where LR is the result of the usual arithmetic conversions
3229 // between types L and R.
3230 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003231 for (unsigned Left = FirstPromotedArithmeticType;
3232 Left < LastPromotedArithmeticType; ++Left) {
3233 for (unsigned Right = FirstPromotedArithmeticType;
3234 Right < LastPromotedArithmeticType; ++Right) {
3235 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman6ae7d112009-08-19 07:44:53 +00003236 QualType Result
3237 = isComparison
3238 ? Context.BoolTy
3239 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003240 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3241 }
3242 }
3243 break;
3244
3245 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003246 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003247 case OO_Caret:
3248 case OO_Pipe:
3249 case OO_LessLess:
3250 case OO_GreaterGreater:
3251 // C++ [over.built]p17:
3252 //
3253 // For every pair of promoted integral types L and R, there
3254 // exist candidate operator functions of the form
3255 //
3256 // LR operator%(L, R);
3257 // LR operator&(L, R);
3258 // LR operator^(L, R);
3259 // LR operator|(L, R);
3260 // L operator<<(L, R);
3261 // L operator>>(L, R);
3262 //
3263 // where LR is the result of the usual arithmetic conversions
3264 // between types L and R.
3265 for (unsigned Left = FirstPromotedIntegralType;
3266 Left < LastPromotedIntegralType; ++Left) {
3267 for (unsigned Right = FirstPromotedIntegralType;
3268 Right < LastPromotedIntegralType; ++Right) {
3269 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3270 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3271 ? LandR[0]
Eli Friedman6ae7d112009-08-19 07:44:53 +00003272 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003273 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3274 }
3275 }
3276 break;
3277
3278 case OO_Equal:
3279 // C++ [over.built]p20:
3280 //
3281 // For every pair (T, VQ), where T is an enumeration or
3282 // (FIXME:) pointer to member type and VQ is either volatile or
3283 // empty, there exist candidate operator functions of the form
3284 //
3285 // VQ T& operator=(VQ T&, T);
3286 for (BuiltinCandidateTypeSet::iterator Enum
3287 = CandidateTypes.enumeration_begin();
3288 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3289 QualType ParamTypes[2];
3290
3291 // T& operator=(T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003292 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregor70d26122008-11-12 17:17:38 +00003293 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003294 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003295 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003296
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003297 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3298 // volatile T& operator=(volatile T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003299 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003300 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003301 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003302 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003303 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003304 }
3305 // Fall through.
3306
3307 case OO_PlusEqual:
3308 case OO_MinusEqual:
3309 // C++ [over.built]p19:
3310 //
3311 // For every pair (T, VQ), where T is any type and VQ is either
3312 // volatile or empty, there exist candidate operator functions
3313 // of the form
3314 //
3315 // T*VQ& operator=(T*VQ&, T*);
3316 //
3317 // C++ [over.built]p21:
3318 //
3319 // For every pair (T, VQ), where T is a cv-qualified or
3320 // cv-unqualified object type and VQ is either volatile or
3321 // empty, there exist candidate operator functions of the form
3322 //
3323 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3324 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3325 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3326 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3327 QualType ParamTypes[2];
3328 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3329
3330 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003331 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003332 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3333 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003334
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003335 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3336 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003337 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003338 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3339 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003340 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003341 }
3342 // Fall through.
3343
3344 case OO_StarEqual:
3345 case OO_SlashEqual:
3346 // C++ [over.built]p18:
3347 //
3348 // For every triple (L, VQ, R), where L is an arithmetic type,
3349 // VQ is either volatile or empty, and R is a promoted
3350 // arithmetic type, there exist candidate operator functions of
3351 // the form
3352 //
3353 // VQ L& operator=(VQ L&, R);
3354 // VQ L& operator*=(VQ L&, R);
3355 // VQ L& operator/=(VQ L&, R);
3356 // VQ L& operator+=(VQ L&, R);
3357 // VQ L& operator-=(VQ L&, R);
3358 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3359 for (unsigned Right = FirstPromotedArithmeticType;
3360 Right < LastPromotedArithmeticType; ++Right) {
3361 QualType ParamTypes[2];
3362 ParamTypes[1] = ArithmeticTypes[Right];
3363
3364 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003365 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003366 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3367 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003368
3369 // Add this built-in operator as a candidate (VQ is 'volatile').
3370 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003371 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003372 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3373 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003374 }
3375 }
3376 break;
3377
3378 case OO_PercentEqual:
3379 case OO_LessLessEqual:
3380 case OO_GreaterGreaterEqual:
3381 case OO_AmpEqual:
3382 case OO_CaretEqual:
3383 case OO_PipeEqual:
3384 // C++ [over.built]p22:
3385 //
3386 // For every triple (L, VQ, R), where L is an integral type, VQ
3387 // is either volatile or empty, and R is a promoted integral
3388 // type, there exist candidate operator functions of the form
3389 //
3390 // VQ L& operator%=(VQ L&, R);
3391 // VQ L& operator<<=(VQ L&, R);
3392 // VQ L& operator>>=(VQ L&, R);
3393 // VQ L& operator&=(VQ L&, R);
3394 // VQ L& operator^=(VQ L&, R);
3395 // VQ L& operator|=(VQ L&, R);
3396 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3397 for (unsigned Right = FirstPromotedIntegralType;
3398 Right < LastPromotedIntegralType; ++Right) {
3399 QualType ParamTypes[2];
3400 ParamTypes[1] = ArithmeticTypes[Right];
3401
3402 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003403 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003404 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3405
3406 // Add this built-in operator as a candidate (VQ is 'volatile').
3407 ParamTypes[0] = ArithmeticTypes[Left];
3408 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003409 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003410 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3411 }
3412 }
3413 break;
3414
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003415 case OO_Exclaim: {
3416 // C++ [over.operator]p23:
3417 //
3418 // There also exist candidate operator functions of the form
3419 //
3420 // bool operator!(bool);
3421 // bool operator&&(bool, bool); [BELOW]
3422 // bool operator||(bool, bool); [BELOW]
3423 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003424 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3425 /*IsAssignmentOperator=*/false,
3426 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003427 break;
3428 }
3429
Douglas Gregor70d26122008-11-12 17:17:38 +00003430 case OO_AmpAmp:
3431 case OO_PipePipe: {
3432 // C++ [over.operator]p23:
3433 //
3434 // There also exist candidate operator functions of the form
3435 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003436 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003437 // bool operator&&(bool, bool);
3438 // bool operator||(bool, bool);
3439 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003440 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3441 /*IsAssignmentOperator=*/false,
3442 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003443 break;
3444 }
3445
3446 case OO_Subscript:
3447 // C++ [over.built]p13:
3448 //
3449 // For every cv-qualified or cv-unqualified object type T there
3450 // exist candidate operator functions of the form
3451 //
3452 // T* operator+(T*, ptrdiff_t); [ABOVE]
3453 // T& operator[](T*, ptrdiff_t);
3454 // T* operator-(T*, ptrdiff_t); [ABOVE]
3455 // T* operator+(ptrdiff_t, T*); [ABOVE]
3456 // T& operator[](ptrdiff_t, T*);
3457 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3458 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3459 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003460 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003461 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003462
3463 // T& operator[](T*, ptrdiff_t)
3464 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3465
3466 // T& operator[](ptrdiff_t, T*);
3467 ParamTypes[0] = ParamTypes[1];
3468 ParamTypes[1] = *Ptr;
3469 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3470 }
3471 break;
3472
3473 case OO_ArrowStar:
3474 // FIXME: No support for pointer-to-members yet.
3475 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003476
3477 case OO_Conditional:
3478 // Note that we don't consider the first argument, since it has been
3479 // contextually converted to bool long ago. The candidates below are
3480 // therefore added as binary.
3481 //
3482 // C++ [over.built]p24:
3483 // For every type T, where T is a pointer or pointer-to-member type,
3484 // there exist candidate operator functions of the form
3485 //
3486 // T operator?(bool, T, T);
3487 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003488 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3489 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3490 QualType ParamTypes[2] = { *Ptr, *Ptr };
3491 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3492 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003493 for (BuiltinCandidateTypeSet::iterator Ptr =
3494 CandidateTypes.member_pointer_begin(),
3495 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3496 QualType ParamTypes[2] = { *Ptr, *Ptr };
3497 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3498 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003499 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003500 }
3501}
3502
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003503/// \brief Add function candidates found via argument-dependent lookup
3504/// to the set of overloading candidates.
3505///
3506/// This routine performs argument-dependent name lookup based on the
3507/// given function name (which may also be an operator name) and adds
3508/// all of the overload candidates found by ADL to the overload
3509/// candidate set (C++ [basic.lookup.argdep]).
3510void
3511Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3512 Expr **Args, unsigned NumArgs,
3513 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003514 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003515
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003516 // Record all of the function candidates that we've already
3517 // added to the overload set, so that we don't add those same
3518 // candidates a second time.
3519 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3520 CandEnd = CandidateSet.end();
3521 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003522 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003523 Functions.insert(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003524 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3525 Functions.insert(FunTmpl);
3526 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003527
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003528 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003529
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003530 // Erase all of the candidates we already knew about.
3531 // FIXME: This is suboptimal. Is there a better way?
3532 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3533 CandEnd = CandidateSet.end();
3534 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003535 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003536 Functions.erase(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003537 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3538 Functions.erase(FunTmpl);
3539 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003540
3541 // For each of the ADL candidates we found, add it to the overload
3542 // set.
3543 for (FunctionSet::iterator Func = Functions.begin(),
3544 FuncEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00003545 Func != FuncEnd; ++Func) {
3546 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3547 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3548 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003549 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3550 /*FIXME: explicit args */false, 0, 0,
3551 Args, NumArgs, CandidateSet);
Douglas Gregor993a0602009-06-27 21:05:07 +00003552 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003553}
3554
Douglas Gregord2baafd2008-10-21 16:13:35 +00003555/// isBetterOverloadCandidate - Determines whether the first overload
3556/// candidate is a better candidate than the second (C++ 13.3.3p1).
3557bool
3558Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3559 const OverloadCandidate& Cand2)
3560{
3561 // Define viable functions to be better candidates than non-viable
3562 // functions.
3563 if (!Cand2.Viable)
3564 return Cand1.Viable;
3565 else if (!Cand1.Viable)
3566 return false;
3567
Douglas Gregor3257fb52008-12-22 05:46:06 +00003568 // C++ [over.match.best]p1:
3569 //
3570 // -- if F is a static member function, ICS1(F) is defined such
3571 // that ICS1(F) is neither better nor worse than ICS1(G) for
3572 // any function G, and, symmetrically, ICS1(G) is neither
3573 // better nor worse than ICS1(F).
3574 unsigned StartArg = 0;
3575 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3576 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003577
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003578 // C++ [over.match.best]p1:
3579 // A viable function F1 is defined to be a better function than another
3580 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3581 // conversion sequence than ICSi(F2), and then...
Douglas Gregord2baafd2008-10-21 16:13:35 +00003582 unsigned NumArgs = Cand1.Conversions.size();
3583 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3584 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003585 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003586 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3587 Cand2.Conversions[ArgIdx])) {
3588 case ImplicitConversionSequence::Better:
3589 // Cand1 has a better conversion sequence.
3590 HasBetterConversion = true;
3591 break;
3592
3593 case ImplicitConversionSequence::Worse:
3594 // Cand1 can't be better than Cand2.
3595 return false;
3596
3597 case ImplicitConversionSequence::Indistinguishable:
3598 // Do nothing.
3599 break;
3600 }
3601 }
3602
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003603 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3604 // ICSj(F2), or, if not that,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003605 if (HasBetterConversion)
3606 return true;
3607
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003608 // - F1 is a non-template function and F2 is a function template
3609 // specialization, or, if not that,
3610 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3611 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3612 return true;
3613
3614 // -- F1 and F2 are function template specializations, and the function
3615 // template for F1 is more specialized than the template for F2
3616 // according to the partial ordering rules described in 14.5.5.2, or,
3617 // if not that,
Douglas Gregorf8e51672009-08-02 23:46:29 +00003618 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3619 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor8c860df2009-08-21 23:19:43 +00003620 if (FunctionTemplateDecl *BetterTemplate
3621 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3622 Cand2.Function->getPrimaryTemplate(),
3623 true))
3624 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003625
Douglas Gregor60714f92008-11-07 22:36:19 +00003626 // -- the context is an initialization by user-defined conversion
3627 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3628 // from the return type of F1 to the destination type (i.e.,
3629 // the type of the entity being initialized) is a better
3630 // conversion sequence than the standard conversion sequence
3631 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003632 if (Cand1.Function && Cand2.Function &&
3633 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003634 isa<CXXConversionDecl>(Cand2.Function)) {
3635 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3636 Cand2.FinalConversion)) {
3637 case ImplicitConversionSequence::Better:
3638 // Cand1 has a better conversion sequence.
3639 return true;
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 Gregord2baafd2008-10-21 16:13:35 +00003651 return false;
3652}
3653
Douglas Gregor98189262009-06-19 23:52:42 +00003654/// \brief Computes the best viable function (C++ 13.3.3)
3655/// within an overload candidate set.
3656///
3657/// \param CandidateSet the set of candidate functions.
3658///
3659/// \param Loc the location of the function name (or operator symbol) for
3660/// which overload resolution occurs.
3661///
3662/// \param Best f overload resolution was successful or found a deleted
3663/// function, Best points to the candidate function found.
3664///
3665/// \returns The result of overload resolution.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003666Sema::OverloadingResult
3667Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003668 SourceLocation Loc,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003669 OverloadCandidateSet::iterator& Best)
3670{
3671 // Find the best viable function.
3672 Best = CandidateSet.end();
3673 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3674 Cand != CandidateSet.end(); ++Cand) {
3675 if (Cand->Viable) {
3676 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3677 Best = Cand;
3678 }
3679 }
3680
3681 // If we didn't find any viable functions, abort.
3682 if (Best == CandidateSet.end())
3683 return OR_No_Viable_Function;
3684
3685 // Make sure that this function is better than every other viable
3686 // function. If not, we have an ambiguity.
3687 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3688 Cand != CandidateSet.end(); ++Cand) {
3689 if (Cand->Viable &&
3690 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003691 !isBetterOverloadCandidate(*Best, *Cand)) {
3692 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003693 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003694 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003695 }
3696
3697 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003698 if (Best->Function &&
3699 (Best->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003700 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003701 return OR_Deleted;
3702
Douglas Gregor98189262009-06-19 23:52:42 +00003703 // C++ [basic.def.odr]p2:
3704 // An overloaded function is used if it is selected by overload resolution
3705 // when referred to from a potentially-evaluated expression. [Note: this
3706 // covers calls to named functions (5.2.2), operator overloading
3707 // (clause 13), user-defined conversions (12.3.2), allocation function for
3708 // placement new (5.3.4), as well as non-default initialization (8.5).
3709 if (Best->Function)
3710 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003711 return OR_Success;
3712}
3713
3714/// PrintOverloadCandidates - When overload resolution fails, prints
3715/// diagnostic messages containing the candidates in the candidate
3716/// set. If OnlyViable is true, only viable candidates will be printed.
3717void
3718Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3719 bool OnlyViable)
3720{
3721 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3722 LastCand = CandidateSet.end();
3723 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003724 if (Cand->Viable || !OnlyViable) {
3725 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003726 if (Cand->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003727 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003728 // Deleted or "unavailable" function.
3729 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3730 << Cand->Function->isDeleted();
3731 } else {
3732 // Normal function
3733 // FIXME: Give a better reason!
3734 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3735 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003736 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003737 // Desugar the type of the surrogate down to a function type,
3738 // retaining as many typedefs as possible while still showing
3739 // the function type (and, therefore, its parameter types).
3740 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003741 bool isLValueReference = false;
3742 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003743 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003744 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003745 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003746 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003747 isLValueReference = true;
3748 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003749 FnType->getAs<RValueReferenceType>()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003750 FnType = FnTypeRef->getPointeeType();
3751 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003752 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003753 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003754 FnType = FnTypePtr->getPointeeType();
3755 isPointer = true;
3756 }
3757 // Desugar down to a function type.
3758 FnType = QualType(FnType->getAsFunctionType(), 0);
3759 // Reconstruct the pointer/reference as appropriate.
3760 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003761 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3762 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003763
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003764 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003765 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003766 } else {
3767 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003768 // FIXME: Do we want the error message to point at the operator?
3769 // (built-ins won't have a location)
Douglas Gregor70d26122008-11-12 17:17:38 +00003770 QualType FnType
3771 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3772 Cand->BuiltinTypes.ParamTypes,
3773 Cand->Conversions.size(),
3774 false, 0);
3775
Chris Lattner4bfd2232008-11-24 06:25:27 +00003776 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003777 }
3778 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003779 }
3780}
3781
Douglas Gregor45014fd2008-11-10 20:40:00 +00003782/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3783/// an overloaded function (C++ [over.over]), where @p From is an
3784/// expression with overloaded function type and @p ToType is the type
3785/// we're trying to resolve to. For example:
3786///
3787/// @code
3788/// int f(double);
3789/// int f(int);
3790///
3791/// int (*pfd)(double) = f; // selects f(double)
3792/// @endcode
3793///
3794/// This routine returns the resulting FunctionDecl if it could be
3795/// resolved, and NULL otherwise. When @p Complain is true, this
3796/// routine will emit diagnostics if there is an error.
3797FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003798Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003799 bool Complain) {
3800 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003801 bool IsMember = false;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003802 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003803 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003804 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003805 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003806 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003807 ToType->getAs<MemberPointerType>()) {
Sebastian Redl7434fc32009-02-04 21:23:32 +00003808 FunctionType = MemTypePtr->getPointeeType();
3809 IsMember = true;
3810 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003811
3812 // We only look at pointers or references to functions.
Douglas Gregor72bb4992009-07-09 17:16:51 +00003813 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor62f78762009-07-08 20:55:45 +00003814 if (!FunctionType->isFunctionType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003815 return 0;
3816
3817 // Find the actual overloaded function declaration.
3818 OverloadedFunctionDecl *Ovl = 0;
3819
3820 // C++ [over.over]p1:
3821 // [...] [Note: any redundant set of parentheses surrounding the
3822 // overloaded function name is ignored (5.1). ]
3823 Expr *OvlExpr = From->IgnoreParens();
3824
3825 // C++ [over.over]p1:
3826 // [...] The overloaded function name can be preceded by the &
3827 // operator.
3828 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3829 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3830 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3831 }
3832
3833 // Try to dig out the overloaded function.
Douglas Gregor62f78762009-07-08 20:55:45 +00003834 FunctionTemplateDecl *FunctionTemplate = 0;
3835 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003836 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor62f78762009-07-08 20:55:45 +00003837 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3838 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003839
Douglas Gregor62f78762009-07-08 20:55:45 +00003840 // If there's no overloaded function declaration or function template,
3841 // we're done.
3842 if (!Ovl && !FunctionTemplate)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003843 return 0;
3844
Douglas Gregor62f78762009-07-08 20:55:45 +00003845 OverloadIterator Fun;
3846 if (Ovl)
3847 Fun = Ovl;
3848 else
3849 Fun = FunctionTemplate;
3850
Douglas Gregor45014fd2008-11-10 20:40:00 +00003851 // Look through all of the overloaded functions, searching for one
3852 // whose type matches exactly.
Douglas Gregora142a052009-07-08 23:33:52 +00003853 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3854
3855 bool FoundNonTemplateFunction = false;
Douglas Gregor62f78762009-07-08 20:55:45 +00003856 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003857 // C++ [over.over]p3:
3858 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003859 // targets of type "pointer-to-function" or "reference-to-function."
3860 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003861 // type "pointer-to-member-function."
3862 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor62f78762009-07-08 20:55:45 +00003863
3864 if (FunctionTemplateDecl *FunctionTemplate
3865 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003866 if (CXXMethodDecl *Method
3867 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3868 // Skip non-static function templates when converting to pointer, and
3869 // static when converting to member pointer.
3870 if (Method->isStatic() == IsMember)
3871 continue;
3872 } else if (IsMember)
3873 continue;
3874
3875 // C++ [over.over]p2:
3876 // If the name is a function template, template argument deduction is
3877 // done (14.8.2.2), and if the argument deduction succeeds, the
3878 // resulting template argument list is used to generate a single
3879 // function template specialization, which is added to the set of
3880 // overloaded functions considered.
Douglas Gregor62f78762009-07-08 20:55:45 +00003881 FunctionDecl *Specialization = 0;
3882 TemplateDeductionInfo Info(Context);
3883 if (TemplateDeductionResult Result
3884 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3885 /*FIXME:*/0, /*FIXME:*/0,
3886 FunctionType, Specialization, Info)) {
3887 // FIXME: make a note of the failed deduction for diagnostics.
3888 (void)Result;
3889 } else {
3890 assert(FunctionType
3891 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregora142a052009-07-08 23:33:52 +00003892 Matches.insert(
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003893 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor62f78762009-07-08 20:55:45 +00003894 }
3895 }
3896
Sebastian Redl7434fc32009-02-04 21:23:32 +00003897 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3898 // Skip non-static functions when converting to pointer, and static
3899 // when converting to member pointer.
3900 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003901 continue;
Douglas Gregora142a052009-07-08 23:33:52 +00003902 } else if (IsMember)
Sebastian Redl7434fc32009-02-04 21:23:32 +00003903 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003904
Douglas Gregorb60eb752009-06-25 22:08:12 +00003905 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003906 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003907 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregora142a052009-07-08 23:33:52 +00003908 FoundNonTemplateFunction = true;
3909 }
Douglas Gregor62f78762009-07-08 20:55:45 +00003910 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003911 }
3912
Douglas Gregora142a052009-07-08 23:33:52 +00003913 // If there were 0 or 1 matches, we're done.
3914 if (Matches.empty())
3915 return 0;
3916 else if (Matches.size() == 1)
3917 return *Matches.begin();
3918
3919 // C++ [over.over]p4:
3920 // If more than one function is selected, [...]
3921 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor8c860df2009-08-21 23:19:43 +00003922 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregora142a052009-07-08 23:33:52 +00003923 if (FoundNonTemplateFunction) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003924 // [...] any function template specializations in the set are
3925 // eliminated if the set also contains a non-template function, [...]
3926 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregora142a052009-07-08 23:33:52 +00003927 if ((*M)->getPrimaryTemplate() == 0)
3928 RemainingMatches.push_back(*M);
3929 } else {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003930 // [...] and any given function template specialization F1 is
3931 // eliminated if the set contains a second function template
3932 // specialization whose function template is more specialized
3933 // than the function template of F1 according to the partial
3934 // ordering rules of 14.5.5.2.
3935
3936 // The algorithm specified above is quadratic. We instead use a
3937 // two-pass algorithm (similar to the one used to identify the
3938 // best viable function in an overload set) that identifies the
3939 // best function template (if it exists).
3940 MatchIter Best = Matches.begin();
3941 MatchIter M = Best, MEnd = Matches.end();
3942 // Find the most specialized function.
3943 for (++M; M != MEnd; ++M)
3944 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
3945 (*Best)->getPrimaryTemplate(),
3946 false)
3947 == (*M)->getPrimaryTemplate())
3948 Best = M;
3949
3950 // Determine whether this function template is more specialized
3951 // that all of the others.
3952 bool Ambiguous = false;
3953 for (M = Matches.begin(); M != MEnd; ++M) {
3954 if (M != Best &&
3955 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
3956 (*Best)->getPrimaryTemplate(),
3957 false)
3958 != (*Best)->getPrimaryTemplate()) {
3959 Ambiguous = true;
3960 break;
3961 }
3962 }
3963
3964 // If one function template was more specialized than all of the
3965 // others, return it.
3966 if (!Ambiguous)
3967 return *Best;
3968
3969 // We could not find a most-specialized function template, which
3970 // is equivalent to having a set of function templates with more
3971 // than one such template. So, we place all of the function
3972 // templates into the set of remaining matches and produce a
3973 // diagnostic below. FIXME: we could perform the quadratic
3974 // algorithm here, pruning the result set to limit the number of
3975 // candidates output later.
3976 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregora142a052009-07-08 23:33:52 +00003977 }
3978
3979 // [...] After such eliminations, if any, there shall remain exactly one
3980 // selected function.
3981 if (RemainingMatches.size() == 1)
3982 return RemainingMatches.front();
3983
3984 // FIXME: We should probably return the same thing that BestViableFunction
3985 // returns (even if we issue the diagnostics here).
3986 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
3987 << RemainingMatches[0]->getDeclName();
3988 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
3989 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor45014fd2008-11-10 20:40:00 +00003990 return 0;
3991}
3992
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003993/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003994/// (which eventually refers to the declaration Func) and the call
3995/// arguments Args/NumArgs, attempt to resolve the function call down
3996/// to a specific function. If overload resolution succeeds, returns
3997/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003998/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003999/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004000FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004001 DeclarationName UnqualifiedName,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004002 bool HasExplicitTemplateArgs,
4003 const TemplateArgument *ExplicitTemplateArgs,
4004 unsigned NumExplicitTemplateArgs,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004005 SourceLocation LParenLoc,
4006 Expr **Args, unsigned NumArgs,
4007 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004008 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004009 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004010 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004011
4012 // Add the functions denoted by Callee to the set of candidate
4013 // functions. While we're doing so, track whether argument-dependent
4014 // lookup still applies, per:
4015 //
4016 // C++0x [basic.lookup.argdep]p3:
4017 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4018 // and let Y be the lookup set produced by argument dependent
4019 // lookup (defined as follows). If X contains
4020 //
4021 // -- a declaration of a class member, or
4022 //
4023 // -- a block-scope function declaration that is not a
4024 // using-declaration, or
4025 //
4026 // -- a declaration that is neither a function or a function
4027 // template
4028 //
4029 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004030 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004031 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4032 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4033 FuncEnd = Ovl->function_end();
4034 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00004035 DeclContext *Ctx = 0;
4036 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004037 if (HasExplicitTemplateArgs)
4038 continue;
4039
Douglas Gregorb60eb752009-06-25 22:08:12 +00004040 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4041 Ctx = FunDecl->getDeclContext();
4042 } else {
4043 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004044 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4045 ExplicitTemplateArgs,
4046 NumExplicitTemplateArgs,
4047 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004048 Ctx = FunTmpl->getDeclContext();
4049 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004050
Douglas Gregorb60eb752009-06-25 22:08:12 +00004051
4052 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004053 ArgumentDependentLookup = false;
4054 }
4055 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004056 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004057 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4058
4059 if (Func->getDeclContext()->isRecord() ||
4060 Func->getDeclContext()->isFunctionOrMethod())
4061 ArgumentDependentLookup = false;
Douglas Gregorb60eb752009-06-25 22:08:12 +00004062 } else if (FunctionTemplateDecl *FuncTemplate
4063 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004064 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4065 ExplicitTemplateArgs,
4066 NumExplicitTemplateArgs,
4067 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004068
4069 if (FuncTemplate->getDeclContext()->isRecord())
4070 ArgumentDependentLookup = false;
4071 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004072
4073 if (Callee)
4074 UnqualifiedName = Callee->getDeclName();
4075
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004076 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004077 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004078 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004079 CandidateSet);
4080
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004081 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004082 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004083 case OR_Success:
4084 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004085
4086 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00004087 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004088 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004089 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004090 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4091 break;
4092
4093 case OR_Ambiguous:
4094 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004095 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004096 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4097 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004098
4099 case OR_Deleted:
4100 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4101 << Best->Function->isDeleted()
4102 << UnqualifiedName
4103 << Fn->getSourceRange();
4104 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4105 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004106 }
4107
4108 // Overload resolution failed. Destroy all of the subexpressions and
4109 // return NULL.
4110 Fn->Destroy(Context);
4111 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4112 Args[Arg]->Destroy(Context);
4113 return 0;
4114}
4115
Douglas Gregorc78182d2009-03-13 23:49:33 +00004116/// \brief Create a unary operation that may resolve to an overloaded
4117/// operator.
4118///
4119/// \param OpLoc The location of the operator itself (e.g., '*').
4120///
4121/// \param OpcIn The UnaryOperator::Opcode that describes this
4122/// operator.
4123///
4124/// \param Functions The set of non-member functions that will be
4125/// considered by overload resolution. The caller needs to build this
4126/// set based on the context using, e.g.,
4127/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4128/// set should not contain any member functions; those will be added
4129/// by CreateOverloadedUnaryOp().
4130///
4131/// \param input The input argument.
4132Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4133 unsigned OpcIn,
4134 FunctionSet &Functions,
4135 ExprArg input) {
4136 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4137 Expr *Input = (Expr *)input.get();
4138
4139 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4140 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4141 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4142
4143 Expr *Args[2] = { Input, 0 };
4144 unsigned NumArgs = 1;
4145
4146 // For post-increment and post-decrement, add the implicit '0' as
4147 // the second argument, so that we know this is a post-increment or
4148 // post-decrement.
4149 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4150 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4151 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4152 SourceLocation());
4153 NumArgs = 2;
4154 }
4155
4156 if (Input->isTypeDependent()) {
4157 OverloadedFunctionDecl *Overloads
4158 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4159 for (FunctionSet::iterator Func = Functions.begin(),
4160 FuncEnd = Functions.end();
4161 Func != FuncEnd; ++Func)
4162 Overloads->addOverload(*Func);
4163
4164 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4165 OpLoc, false, false);
4166
4167 input.release();
4168 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4169 &Args[0], NumArgs,
4170 Context.DependentTy,
4171 OpLoc));
4172 }
4173
4174 // Build an empty overload set.
4175 OverloadCandidateSet CandidateSet;
4176
4177 // Add the candidates from the given function set.
4178 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4179
4180 // Add operator candidates that are member functions.
4181 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4182
4183 // Add builtin operator candidates.
4184 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4185
4186 // Perform overload resolution.
4187 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004188 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004189 case OR_Success: {
4190 // We found a built-in operator or an overloaded operator.
4191 FunctionDecl *FnDecl = Best->Function;
4192
4193 if (FnDecl) {
4194 // We matched an overloaded operator. Build a call to that
4195 // operator.
4196
4197 // Convert the arguments.
4198 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4199 if (PerformObjectArgumentInitialization(Input, Method))
4200 return ExprError();
4201 } else {
4202 // Convert the arguments.
4203 if (PerformCopyInitialization(Input,
4204 FnDecl->getParamDecl(0)->getType(),
4205 "passing"))
4206 return ExprError();
4207 }
4208
4209 // Determine the result type
4210 QualType ResultTy
4211 = FnDecl->getType()->getAsFunctionType()->getResultType();
4212 ResultTy = ResultTy.getNonReferenceType();
4213
4214 // Build the actual expression node.
4215 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4216 SourceLocation());
4217 UsualUnaryConversions(FnExpr);
4218
4219 input.release();
Anders Carlsson16497742009-08-16 04:11:06 +00004220
4221 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4222 &Input, 1, ResultTy, OpLoc);
4223 return MaybeBindToTemporary(CE);
Douglas Gregorc78182d2009-03-13 23:49:33 +00004224 } else {
4225 // We matched a built-in operator. Convert the arguments, then
4226 // break out so that we will build the appropriate built-in
4227 // operator node.
4228 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4229 Best->Conversions[0], "passing"))
4230 return ExprError();
4231
4232 break;
4233 }
4234 }
4235
4236 case OR_No_Viable_Function:
4237 // No viable function; fall through to handling this as a
4238 // built-in operator, which will produce an error message for us.
4239 break;
4240
4241 case OR_Ambiguous:
4242 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4243 << UnaryOperator::getOpcodeStr(Opc)
4244 << Input->getSourceRange();
4245 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4246 return ExprError();
4247
4248 case OR_Deleted:
4249 Diag(OpLoc, diag::err_ovl_deleted_oper)
4250 << Best->Function->isDeleted()
4251 << UnaryOperator::getOpcodeStr(Opc)
4252 << Input->getSourceRange();
4253 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4254 return ExprError();
4255 }
4256
4257 // Either we found no viable overloaded operator or we matched a
4258 // built-in operator. In either case, fall through to trying to
4259 // build a built-in operation.
4260 input.release();
4261 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4262}
4263
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004264/// \brief Create a binary operation that may resolve to an overloaded
4265/// operator.
4266///
4267/// \param OpLoc The location of the operator itself (e.g., '+').
4268///
4269/// \param OpcIn The BinaryOperator::Opcode that describes this
4270/// operator.
4271///
4272/// \param Functions The set of non-member functions that will be
4273/// considered by overload resolution. The caller needs to build this
4274/// set based on the context using, e.g.,
4275/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4276/// set should not contain any member functions; those will be added
4277/// by CreateOverloadedBinOp().
4278///
4279/// \param LHS Left-hand argument.
4280/// \param RHS Right-hand argument.
4281Sema::OwningExprResult
4282Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4283 unsigned OpcIn,
4284 FunctionSet &Functions,
4285 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004286 Expr *Args[2] = { LHS, RHS };
4287
4288 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4289 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4290 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4291
4292 // If either side is type-dependent, create an appropriate dependent
4293 // expression.
4294 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
4295 // .* cannot be overloaded.
4296 if (Opc == BinaryOperator::PtrMemD)
4297 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
4298 Context.DependentTy, OpLoc));
4299
4300 OverloadedFunctionDecl *Overloads
4301 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4302 for (FunctionSet::iterator Func = Functions.begin(),
4303 FuncEnd = Functions.end();
4304 Func != FuncEnd; ++Func)
4305 Overloads->addOverload(*Func);
4306
4307 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4308 OpLoc, false, false);
4309
4310 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4311 Args, 2,
4312 Context.DependentTy,
4313 OpLoc));
4314 }
4315
4316 // If this is the .* operator, which is not overloadable, just
4317 // create a built-in binary operator.
4318 if (Opc == BinaryOperator::PtrMemD)
4319 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4320
4321 // If this is one of the assignment operators, we only perform
4322 // overload resolution if the left-hand side is a class or
4323 // enumeration type (C++ [expr.ass]p3).
4324 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4325 !LHS->getType()->isOverloadableType())
4326 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4327
Douglas Gregorc78182d2009-03-13 23:49:33 +00004328 // Build an empty overload set.
4329 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004330
4331 // Add the candidates from the given function set.
4332 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4333
4334 // Add operator candidates that are member functions.
4335 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4336
4337 // Add builtin operator candidates.
4338 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4339
4340 // Perform overload resolution.
4341 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004342 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004343 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004344 // We found a built-in operator or an overloaded operator.
4345 FunctionDecl *FnDecl = Best->Function;
4346
4347 if (FnDecl) {
4348 // We matched an overloaded operator. Build a call to that
4349 // operator.
4350
4351 // Convert the arguments.
4352 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4353 if (PerformObjectArgumentInitialization(LHS, Method) ||
4354 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
4355 "passing"))
4356 return ExprError();
4357 } else {
4358 // Convert the arguments.
4359 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
4360 "passing") ||
4361 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
4362 "passing"))
4363 return ExprError();
4364 }
4365
4366 // Determine the result type
4367 QualType ResultTy
4368 = FnDecl->getType()->getAsFunctionType()->getResultType();
4369 ResultTy = ResultTy.getNonReferenceType();
4370
4371 // Build the actual expression node.
4372 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argiris Kirtzidiscca21b82009-07-14 03:19:38 +00004373 OpLoc);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004374 UsualUnaryConversions(FnExpr);
4375
Anders Carlsson16497742009-08-16 04:11:06 +00004376 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4377 Args, 2, ResultTy, OpLoc);
4378 return MaybeBindToTemporary(CE);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004379 } else {
4380 // We matched a built-in operator. Convert the arguments, then
4381 // break out so that we will build the appropriate built-in
4382 // operator node.
4383 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4384 Best->Conversions[0], "passing") ||
4385 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4386 Best->Conversions[1], "passing"))
4387 return ExprError();
4388
4389 break;
4390 }
4391 }
4392
4393 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004394 // For class as left operand for assignment or compound assigment operator
4395 // do not fall through to handling in built-in, but report that no overloaded
4396 // assignment operator found
4397 if (LHS->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4398 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4399 << BinaryOperator::getOpcodeStr(Opc)
4400 << LHS->getSourceRange() << RHS->getSourceRange();
4401 return ExprError();
4402 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004403 // No viable function; fall through to handling this as a
4404 // built-in operator, which will produce an error message for us.
4405 break;
4406
4407 case OR_Ambiguous:
4408 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4409 << BinaryOperator::getOpcodeStr(Opc)
4410 << LHS->getSourceRange() << RHS->getSourceRange();
4411 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4412 return ExprError();
4413
4414 case OR_Deleted:
4415 Diag(OpLoc, diag::err_ovl_deleted_oper)
4416 << Best->Function->isDeleted()
4417 << BinaryOperator::getOpcodeStr(Opc)
4418 << LHS->getSourceRange() << RHS->getSourceRange();
4419 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4420 return ExprError();
4421 }
4422
4423 // Either we found no viable overloaded operator or we matched a
4424 // built-in operator. In either case, try to build a built-in
4425 // operation.
4426 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4427}
4428
Douglas Gregor3257fb52008-12-22 05:46:06 +00004429/// BuildCallToMemberFunction - Build a call to a member
4430/// function. MemExpr is the expression that refers to the member
4431/// function (and includes the object parameter), Args/NumArgs are the
4432/// arguments to the function call (not including the object
4433/// parameter). The caller needs to validate that the member
4434/// expression refers to a member function or an overloaded member
4435/// function.
4436Sema::ExprResult
4437Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4438 SourceLocation LParenLoc, Expr **Args,
4439 unsigned NumArgs, SourceLocation *CommaLocs,
4440 SourceLocation RParenLoc) {
4441 // Dig out the member expression. This holds both the object
4442 // argument and the member function we're referring to.
4443 MemberExpr *MemExpr = 0;
4444 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4445 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4446 else
4447 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4448 assert(MemExpr && "Building member call without member expression");
4449
4450 // Extract the object argument.
4451 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004452
Douglas Gregor3257fb52008-12-22 05:46:06 +00004453 CXXMethodDecl *Method = 0;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004454 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4455 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004456 // Add overload candidates
4457 OverloadCandidateSet CandidateSet;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004458 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4459
Douglas Gregor050cabf2009-08-21 18:42:58 +00004460 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4461 Func != FuncEnd; ++Func) {
4462 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4463 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4464 /*SuppressUserConversions=*/false);
4465 else
4466 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4467 /*FIXME:*/false, /*FIXME:*/0,
4468 /*FIXME:*/0, ObjectArg, Args, NumArgs,
4469 CandidateSet,
4470 /*SuppressUsedConversions=*/false);
4471 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004472
Douglas Gregor3257fb52008-12-22 05:46:06 +00004473 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004474 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004475 case OR_Success:
4476 Method = cast<CXXMethodDecl>(Best->Function);
4477 break;
4478
4479 case OR_No_Viable_Function:
4480 Diag(MemExpr->getSourceRange().getBegin(),
4481 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004482 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004483 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4484 // FIXME: Leaking incoming expressions!
4485 return true;
4486
4487 case OR_Ambiguous:
4488 Diag(MemExpr->getSourceRange().getBegin(),
4489 diag::err_ovl_ambiguous_member_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004490 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004491 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4492 // FIXME: Leaking incoming expressions!
4493 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004494
4495 case OR_Deleted:
4496 Diag(MemExpr->getSourceRange().getBegin(),
4497 diag::err_ovl_deleted_member_call)
4498 << Best->Function->isDeleted()
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004499 << DeclName << MemExprE->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004500 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4501 // FIXME: Leaking incoming expressions!
4502 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004503 }
4504
4505 FixOverloadedFunctionReference(MemExpr, Method);
4506 } else {
4507 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4508 }
4509
4510 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004511 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004512 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4513 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004514 Method->getResultType().getNonReferenceType(),
4515 RParenLoc));
4516
4517 // Convert the object argument (for a non-static member function call).
4518 if (!Method->isStatic() &&
4519 PerformObjectArgumentInitialization(ObjectArg, Method))
4520 return true;
4521 MemExpr->setBase(ObjectArg);
4522
4523 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004524 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004525 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4526 RParenLoc))
4527 return true;
4528
Anders Carlsson7fb13802009-08-16 01:56:34 +00004529 if (CheckFunctionCall(Method, TheCall.get()))
4530 return true;
Anders Carlssonb8ff3402009-08-16 03:42:12 +00004531
4532 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004533}
4534
Douglas Gregor10f3c502008-11-19 21:05:33 +00004535/// BuildCallToObjectOfClassType - Build a call to an object of class
4536/// type (C++ [over.call.object]), which can end up invoking an
4537/// overloaded function call operator (@c operator()) or performing a
4538/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004539Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004540Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4541 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004542 Expr **Args, unsigned NumArgs,
4543 SourceLocation *CommaLocs,
4544 SourceLocation RParenLoc) {
4545 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004546 const RecordType *Record = Object->getType()->getAs<RecordType>();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004547
4548 // C++ [over.call.object]p1:
4549 // If the primary-expression E in the function call syntax
Eli Friedmand5a72f02009-08-05 19:21:58 +00004550 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor10f3c502008-11-19 21:05:33 +00004551 // candidate functions includes at least the function call
4552 // operators of T. The function call operators of T are obtained by
4553 // ordinary lookup of the name operator() in the context of
4554 // (E).operator().
4555 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004556 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004557 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004558 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004559 Oper != OperEnd; ++Oper)
4560 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4561 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004562
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004563 // C++ [over.call.object]p2:
4564 // In addition, for each conversion function declared in T of the
4565 // form
4566 //
4567 // operator conversion-type-id () cv-qualifier;
4568 //
4569 // where cv-qualifier is the same cv-qualification as, or a
4570 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004571 // denotes the type "pointer to function of (P1,...,Pn) returning
4572 // R", or the type "reference to pointer to function of
4573 // (P1,...,Pn) returning R", or the type "reference to function
4574 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004575 // is also considered as a candidate function. Similarly,
4576 // surrogate call functions are added to the set of candidate
4577 // functions for each conversion function declared in an
4578 // accessible base class provided the function is not hidden
4579 // within T by another intervening declaration.
4580 //
4581 // FIXME: Look in base classes for more conversion operators!
4582 OverloadedFunctionDecl *Conversions
4583 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004584 for (OverloadedFunctionDecl::function_iterator
4585 Func = Conversions->function_begin(),
4586 FuncEnd = Conversions->function_end();
4587 Func != FuncEnd; ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00004588 CXXConversionDecl *Conv;
4589 FunctionTemplateDecl *ConvTemplate;
4590 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
4591
4592 // Skip over templated conversion functions; they aren't
4593 // surrogates.
4594 if (ConvTemplate)
4595 continue;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004596
4597 // Strip the reference type (if any) and then the pointer type (if
4598 // any) to get down to what might be a function type.
4599 QualType ConvType = Conv->getConversionType().getNonReferenceType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004600 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004601 ConvType = ConvPtrType->getPointeeType();
4602
Douglas Gregor4fa58902009-02-26 23:50:07 +00004603 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004604 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4605 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004606
4607 // Perform overload resolution.
4608 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004609 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004610 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004611 // Overload resolution succeeded; we'll build the appropriate call
4612 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004613 break;
4614
4615 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004616 Diag(Object->getSourceRange().getBegin(),
4617 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004618 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004619 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004620 break;
4621
4622 case OR_Ambiguous:
4623 Diag(Object->getSourceRange().getBegin(),
4624 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004625 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004626 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4627 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004628
4629 case OR_Deleted:
4630 Diag(Object->getSourceRange().getBegin(),
4631 diag::err_ovl_deleted_object_call)
4632 << Best->Function->isDeleted()
4633 << Object->getType() << Object->getSourceRange();
4634 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4635 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004636 }
4637
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004638 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004639 // We had an error; delete all of the subexpressions and return
4640 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004641 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004642 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004643 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004644 return true;
4645 }
4646
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004647 if (Best->Function == 0) {
4648 // Since there is no function declaration, this is one of the
4649 // surrogate candidates. Dig out the conversion function.
4650 CXXConversionDecl *Conv
4651 = cast<CXXConversionDecl>(
4652 Best->Conversions[0].UserDefined.ConversionFunction);
4653
4654 // We selected one of the surrogate functions that converts the
4655 // object parameter to a function pointer. Perform the conversion
4656 // on the object argument, then let ActOnCallExpr finish the job.
4657 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004658 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004659 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00004660 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00004661 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004662 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4663 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4664 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004665 }
4666
4667 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4668 // that calls this method, using Object for the implicit object
4669 // parameter and passing along the remaining arguments.
4670 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004671 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004672
4673 unsigned NumArgsInProto = Proto->getNumArgs();
4674 unsigned NumArgsToCheck = NumArgs;
4675
4676 // Build the full argument list for the method call (the
4677 // implicit object parameter is placed at the beginning of the
4678 // list).
4679 Expr **MethodArgs;
4680 if (NumArgs < NumArgsInProto) {
4681 NumArgsToCheck = NumArgsInProto;
4682 MethodArgs = new Expr*[NumArgsInProto + 1];
4683 } else {
4684 MethodArgs = new Expr*[NumArgs + 1];
4685 }
4686 MethodArgs[0] = Object;
4687 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4688 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4689
Ted Kremenek0c97e042009-02-07 01:47:29 +00004690 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4691 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004692 UsualUnaryConversions(NewFn);
4693
4694 // Once we've built TheCall, all of the expressions are properly
4695 // owned.
4696 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004697 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004698 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4699 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004700 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004701 delete [] MethodArgs;
4702
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004703 // We may have default arguments. If so, we need to allocate more
4704 // slots in the call for them.
4705 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004706 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004707 else if (NumArgs > NumArgsInProto)
4708 NumArgsToCheck = NumArgsInProto;
4709
Chris Lattner81f00ed2009-04-12 08:11:20 +00004710 bool IsError = false;
4711
Douglas Gregor10f3c502008-11-19 21:05:33 +00004712 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004713 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004714 TheCall->setArg(0, Object);
4715
Chris Lattner81f00ed2009-04-12 08:11:20 +00004716
Douglas Gregor10f3c502008-11-19 21:05:33 +00004717 // Check the argument types.
4718 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004719 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004720 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004721 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004722
4723 // Pass the argument.
4724 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004725 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004726 } else {
Anders Carlsson3d752db2009-08-14 18:30:22 +00004727 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004728 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004729
4730 TheCall->setArg(i + 1, Arg);
4731 }
4732
4733 // If this is a variadic call, handle args passed through "...".
4734 if (Proto->isVariadic()) {
4735 // Promote the arguments (C99 6.5.2.2p7).
4736 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4737 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004738 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004739 TheCall->setArg(i + 1, Arg);
4740 }
4741 }
4742
Chris Lattner81f00ed2009-04-12 08:11:20 +00004743 if (IsError) return true;
4744
Anders Carlsson7fb13802009-08-16 01:56:34 +00004745 if (CheckFunctionCall(Method, TheCall.get()))
4746 return true;
4747
Anders Carlsson422a5fe2009-08-16 03:53:54 +00004748 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004749}
4750
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004751/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4752/// (if one exists), where @c Base is an expression of class type and
4753/// @c Member is the name of the member we're trying to find.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004754Sema::OwningExprResult
4755Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4756 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004757 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4758
4759 // C++ [over.ref]p1:
4760 //
4761 // [...] An expression x->m is interpreted as (x.operator->())->m
4762 // for a class object x of type T if T::operator->() exists and if
4763 // the operator is selected as the best match function by the
4764 // overload resolution mechanism (13.3).
4765 // FIXME: look in base classes.
4766 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4767 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004768 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorda61ad22009-08-06 03:17:00 +00004769
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004770 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004771 for (llvm::tie(Oper, OperEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004772 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004773 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004774 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004775
4776 // Perform overload resolution.
4777 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004778 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004779 case OR_Success:
4780 // Overload resolution succeeded; we'll build the call below.
4781 break;
4782
4783 case OR_No_Viable_Function:
4784 if (CandidateSet.empty())
4785 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004786 << Base->getType() << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004787 else
4788 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004789 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004790 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004791 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004792
4793 case OR_Ambiguous:
4794 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004795 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004796 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004797 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004798
4799 case OR_Deleted:
4800 Diag(OpLoc, diag::err_ovl_deleted_oper)
4801 << Best->Function->isDeleted()
Douglas Gregorda61ad22009-08-06 03:17:00 +00004802 << "operator->" << Base->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004803 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004804 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004805 }
4806
4807 // Convert the object parameter.
4808 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004809 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorda61ad22009-08-06 03:17:00 +00004810 return ExprError();
Douglas Gregor9c690e92008-11-21 03:04:22 +00004811
4812 // No concerns about early exits now.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004813 BaseIn.release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004814
4815 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004816 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4817 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004818 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004819 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004820 Method->getResultType().getNonReferenceType(),
4821 OpLoc);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004822 return Owned(Base);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004823}
4824
Douglas Gregor45014fd2008-11-10 20:40:00 +00004825/// FixOverloadedFunctionReference - E is an expression that refers to
4826/// a C++ overloaded function (possibly with some parentheses and
4827/// perhaps a '&' around it). We have resolved the overloaded function
4828/// to the function declaration Fn, so patch up the expression E to
4829/// refer (possibly indirectly) to Fn.
4830void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4831 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4832 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4833 E->setType(PE->getSubExpr()->getType());
4834 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4835 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4836 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004837 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4838 if (Method->isStatic()) {
4839 // Do nothing: static member functions aren't any different
4840 // from non-member functions.
Mike Stump90fc78e2009-08-04 21:02:39 +00004841 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor3f411962009-02-11 01:18:59 +00004842 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4843 // We have taken the address of a pointer to member
4844 // function. Perform the computation here so that we get the
4845 // appropriate pointer to member type.
4846 DRE->setDecl(Fn);
4847 DRE->setType(Fn->getType());
4848 QualType ClassType
4849 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4850 E->setType(Context.getMemberPointerType(Fn->getType(),
4851 ClassType.getTypePtr()));
4852 return;
4853 }
4854 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004855 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004856 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004857 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor62f78762009-07-08 20:55:45 +00004858 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4859 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4860 "Expected overloaded function or function template");
Douglas Gregor45014fd2008-11-10 20:40:00 +00004861 DR->setDecl(Fn);
4862 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004863 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4864 MemExpr->setMemberDecl(Fn);
4865 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004866 } else {
4867 assert(false && "Invalid reference to overloaded function");
4868 }
4869}
4870
Douglas Gregord2baafd2008-10-21 16:13:35 +00004871} // end namespace clang