blob: ada1a2b4328e4d61dbc6d9a126ff89e87f959294 [file] [log] [blame]
Douglas Gregord2baafd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor10f3c502008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000042 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000045 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000050 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000051 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000052 ICC_Conversion
53 };
54 return Category[(int)Kind];
55}
56
57/// GetConversionRank - Retrieve the implicit conversion rank
58/// corresponding to the given implicit conversion kind.
59ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
60 static const ImplicitConversionRank
61 Rank[(int)ICK_Num_Conversion_Kinds] = {
62 ICR_Exact_Match,
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Promotion,
68 ICR_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000069 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000072 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000077 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000078 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000079 ICR_Conversion
80 };
81 return Rank[(int)Kind];
82}
83
84/// GetImplicitConversionName - Return the name of this kind of
85/// implicit conversion.
86const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
87 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
88 "No conversion",
89 "Lvalue-to-rvalue",
90 "Array-to-pointer",
91 "Function-to-pointer",
92 "Qualification",
93 "Integral promotion",
94 "Floating point promotion",
Douglas Gregore819caf2009-02-12 00:15:05 +000095 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000096 "Integral conversion",
97 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +000098 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000099 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000100 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000101 "Pointer conversion",
102 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000103 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000104 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000105 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000106 };
107 return Name[Kind];
108}
109
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113 First = ICK_Identity;
114 Second = ICK_Identity;
115 Third = ICK_Identity;
116 Deprecated = false;
117 ReferenceBinding = false;
118 DirectBinding = false;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +0000119 RRefBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000120 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000121}
122
Douglas Gregord2baafd2008-10-21 16:13:35 +0000123/// getRank - Retrieve the rank of this standard conversion sequence
124/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
125/// implicit conversions.
126ImplicitConversionRank StandardConversionSequence::getRank() const {
127 ImplicitConversionRank Rank = ICR_Exact_Match;
128 if (GetConversionRank(First) > Rank)
129 Rank = GetConversionRank(First);
130 if (GetConversionRank(Second) > Rank)
131 Rank = GetConversionRank(Second);
132 if (GetConversionRank(Third) > Rank)
133 Rank = GetConversionRank(Third);
134 return Rank;
135}
136
137/// isPointerConversionToBool - Determines whether this conversion is
138/// a conversion of a pointer or pointer-to-member to bool. This is
139/// used as part of the ranking of standard conversion sequences
140/// (C++ 13.3.3.2p4).
141bool StandardConversionSequence::isPointerConversionToBool() const
142{
143 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
144 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
145
146 // Note that FromType has not necessarily been transformed by the
147 // array-to-pointer or function-to-pointer implicit conversions, so
148 // check for their presence as well as checking whether FromType is
149 // a pointer.
150 if (ToType->isBooleanType() &&
Douglas Gregor80402cf2008-12-23 00:53:59 +0000151 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000152 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
153 return true;
154
155 return false;
156}
157
Douglas Gregor14046502008-10-23 00:40:37 +0000158/// isPointerConversionToVoidPointer - Determines whether this
159/// conversion is a conversion of a pointer to a void pointer. This is
160/// used as part of the ranking of standard conversion sequences (C++
161/// 13.3.3.2p4).
162bool
163StandardConversionSequence::
164isPointerConversionToVoidPointer(ASTContext& Context) const
165{
166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor14046502008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregord2baafd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
263// FunctionDecl that New cannot be overloaded with.
264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
272// so IsOverload will not be used.
273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl)
288{
289 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
290 // Is this new function an overload of every function in the
291 // overload set?
292 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
293 FuncEnd = Ovl->function_end();
294 for (; Func != FuncEnd; ++Func) {
295 if (!IsOverload(New, *Func, MatchedDecl)) {
296 MatchedDecl = Func;
297 return false;
298 }
299 }
300
301 // This function overloads every function in the overload set.
302 return true;
Douglas Gregorb60eb752009-06-25 22:08:12 +0000303 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
304 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
305 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000306 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
307 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
308
309 // C++ [temp.fct]p2:
310 // A function template can be overloaded with other function templates
311 // and with normal (non-template) functions.
312 if ((OldTemplate == 0) != (NewTemplate == 0))
313 return true;
314
Douglas Gregord2baafd2008-10-21 16:13:35 +0000315 // Is the function New an overload of the function Old?
316 QualType OldQType = Context.getCanonicalType(Old->getType());
317 QualType NewQType = Context.getCanonicalType(New->getType());
318
319 // Compare the signatures (C++ 1.3.10) of the two functions to
320 // determine whether they are overloads. If we find any mismatch
321 // in the signature, they are overloads.
322
323 // If either of these functions is a K&R-style function (no
324 // prototype), then we consider them to have matching signatures.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000325 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
326 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000327 return false;
328
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000329 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
330 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000331
332 // The signature of a function includes the types of its
333 // parameters (C++ 1.3.10), which includes the presence or absence
334 // of the ellipsis; see C++ DR 357).
335 if (OldQType != NewQType &&
336 (OldType->getNumArgs() != NewType->getNumArgs() ||
337 OldType->isVariadic() != NewType->isVariadic() ||
338 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
339 NewType->arg_type_begin())))
340 return true;
341
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000342 // C++ [temp.over.link]p4:
343 // The signature of a function template consists of its function
344 // signature, its return type and its template parameter list. The names
345 // of the template parameters are significant only for establishing the
346 // relationship between the template parameters and the rest of the
347 // signature.
348 //
349 // We check the return type and template parameter lists for function
350 // templates first; the remaining checks follow.
351 if (NewTemplate &&
352 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
353 OldTemplate->getTemplateParameters(),
354 false, false, SourceLocation()) ||
355 OldType->getResultType() != NewType->getResultType()))
356 return true;
357
Douglas Gregord2baafd2008-10-21 16:13:35 +0000358 // If the function is a class member, its signature includes the
359 // cv-qualifiers (if any) on the function itself.
360 //
361 // As part of this, also check whether one of the member functions
362 // is static, in which case they are not overloads (C++
363 // 13.1p2). While not part of the definition of the signature,
364 // this check is important to determine whether these functions
365 // can be overloaded.
366 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
367 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
368 if (OldMethod && NewMethod &&
369 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000370 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000371 return true;
372
373 // The signatures match; this is not an overload.
374 return false;
375 } else {
376 // (C++ 13p1):
377 // Only function declarations can be overloaded; object and type
378 // declarations cannot be overloaded.
379 return false;
380 }
381}
382
Douglas Gregor81c29152008-10-29 00:13:59 +0000383/// TryImplicitConversion - Attempt to perform an implicit conversion
384/// from the given expression (Expr) to the given type (ToType). This
385/// function returns an implicit conversion sequence that can be used
386/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000387///
388/// void f(float f);
389/// void g(int i) { f(i); }
390///
391/// this routine would produce an implicit conversion sequence to
392/// describe the initialization of f from i, which will be a standard
393/// conversion sequence containing an lvalue-to-rvalue conversion (C++
394/// 4.1) followed by a floating-integral conversion (C++ 4.9).
395//
396/// Note that this routine only determines how the conversion can be
397/// performed; it does not actually perform the conversion. As such,
398/// it will not produce any diagnostics if no conversion is available,
399/// but will instead return an implicit conversion sequence of kind
400/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000401///
402/// If @p SuppressUserConversions, then user-defined conversions are
403/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000404/// If @p AllowExplicit, then explicit user-defined conversions are
405/// permitted.
Sebastian Redla55834a2009-04-12 17:16:29 +0000406/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
407/// no matter its actual lvalueness.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000408ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000409Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000410 bool SuppressUserConversions,
Sebastian Redla55834a2009-04-12 17:16:29 +0000411 bool AllowExplicit, bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000412{
413 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000414 if (IsStandardConversion(From, ToType, ICS.Standard))
415 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000416 else if (getLangOptions().CPlusPlus &&
417 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redla55834a2009-04-12 17:16:29 +0000418 !SuppressUserConversions, AllowExplicit,
419 ForceRValue)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000420 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000421 // C++ [over.ics.user]p4:
422 // A conversion of an expression of class type to the same class
423 // type is given Exact Match rank, and a conversion of an
424 // expression of class type to a base class of that type is
425 // given Conversion rank, in spite of the fact that a copy
426 // constructor (i.e., a user-defined conversion function) is
427 // called for those cases.
428 if (CXXConstructorDecl *Constructor
429 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregord9176392009-02-02 22:11:10 +0000430 QualType FromCanon
431 = Context.getCanonicalType(From->getType().getUnqualifiedType());
432 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
433 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000434 // Turn this into a "standard" conversion sequence, so that it
435 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000436 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
437 ICS.Standard.setAsIdentityConversion();
438 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
439 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000440 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000441 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000442 ICS.Standard.Second = ICK_Derived_To_Base;
443 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000444 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000445
446 // C++ [over.best.ics]p4:
447 // However, when considering the argument of a user-defined
448 // conversion function that is a candidate by 13.3.1.3 when
449 // invoked for the copying of the temporary in the second step
450 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
451 // 13.3.1.6 in all cases, only standard conversion sequences and
452 // ellipsis conversion sequences are allowed.
453 if (SuppressUserConversions &&
454 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
455 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000456 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000457 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000458
459 return ICS;
460}
461
462/// IsStandardConversion - Determines whether there is a standard
463/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
464/// expression From to the type ToType. Standard conversion sequences
465/// only consider non-class types; for conversions that involve class
466/// types, use TryImplicitConversion. If a conversion exists, SCS will
467/// contain the standard conversion sequence required to perform this
468/// conversion and this routine will return true. Otherwise, this
469/// routine will return false and the value of SCS is unspecified.
470bool
471Sema::IsStandardConversion(Expr* From, QualType ToType,
472 StandardConversionSequence &SCS)
473{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000474 QualType FromType = From->getType();
475
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000476 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000477 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000478 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000479 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000480 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000481 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000482
Douglas Gregorfcb19192009-02-11 23:02:49 +0000483 // There are no standard conversions for class types in C++, so
484 // abort early. When overloading in C, however, we do permit
485 if (FromType->isRecordType() || ToType->isRecordType()) {
486 if (getLangOptions().CPlusPlus)
487 return false;
488
489 // When we're overloading in C, we allow, as standard conversions,
490 }
491
Douglas Gregord2baafd2008-10-21 16:13:35 +0000492 // The first conversion can be an lvalue-to-rvalue conversion,
493 // array-to-pointer conversion, or function-to-pointer conversion
494 // (C++ 4p1).
495
496 // Lvalue-to-rvalue conversion (C++ 4.1):
497 // An lvalue (3.10) of a non-function, non-array type T can be
498 // converted to an rvalue.
499 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
500 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000501 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000502 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000503 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000504
505 // If T is a non-class type, the type of the rvalue is the
506 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000507 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
508 // just strip the qualifiers because they don't matter.
509
510 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000511 FromType = FromType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000512 } else if (FromType->isArrayType()) {
513 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000514 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000515
516 // An lvalue or rvalue of type "array of N T" or "array of unknown
517 // bound of T" can be converted to an rvalue of type "pointer to
518 // T" (C++ 4.2p1).
519 FromType = Context.getArrayDecayedType(FromType);
520
521 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
522 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000523 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000524
525 // For the purpose of ranking in overload resolution
526 // (13.3.3.1.1), this conversion is considered an
527 // array-to-pointer conversion followed by a qualification
528 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000529 SCS.Second = ICK_Identity;
530 SCS.Third = ICK_Qualification;
531 SCS.ToTypePtr = ToType.getAsOpaquePtr();
532 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000533 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000534 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
535 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000536 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000537
538 // An lvalue of function type T can be converted to an rvalue of
539 // type "pointer to T." The result is a pointer to the
540 // function. (C++ 4.3p1).
541 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000542 } else if (FunctionDecl *Fn
Douglas Gregor45014fd2008-11-10 20:40:00 +0000543 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000544 // Address of overloaded function (C++ [over.over]).
Douglas Gregor45014fd2008-11-10 20:40:00 +0000545 SCS.First = ICK_Function_To_Pointer;
546
547 // We were able to resolve the address of the overloaded function,
548 // so we can convert to the type of that function.
549 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000550 if (ToType->isLValueReferenceType())
551 FromType = Context.getLValueReferenceType(FromType);
552 else if (ToType->isRValueReferenceType())
553 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000554 else if (ToType->isMemberPointerType()) {
555 // Resolve address only succeeds if both sides are member pointers,
556 // but it doesn't have to be the same class. See DR 247.
557 // Note that this means that the type of &Derived::fn can be
558 // Ret (Base::*)(Args) if the fn overload actually found is from the
559 // base class, even if it was brought into the derived class via a
560 // using declaration. The standard isn't clear on this issue at all.
561 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
562 FromType = Context.getMemberPointerType(FromType,
563 Context.getTypeDeclType(M->getParent()).getTypePtr());
564 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000565 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000566 } else {
567 // We don't require any conversions for the first step.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000568 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000569 }
570
571 // The second conversion can be an integral promotion, floating
572 // point promotion, integral conversion, floating point conversion,
573 // floating-integral conversion, pointer conversion,
574 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000575 // For overloading in C, this can also be a "compatible-type"
576 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000577 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000578 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000579 // The unqualified versions of the types are the same: there's no
580 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000581 SCS.Second = ICK_Identity;
Mike Stump90fc78e2009-08-04 21:02:39 +0000582 } else if (IsIntegralPromotion(From, FromType, ToType)) {
583 // Integral promotion (C++ 4.5).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000584 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000585 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000586 } else if (IsFloatingPointPromotion(FromType, ToType)) {
587 // Floating point promotion (C++ 4.6).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000588 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000589 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000590 } else if (IsComplexPromotion(FromType, ToType)) {
591 // Complex promotion (Clang extension)
Douglas Gregore819caf2009-02-12 00:15:05 +0000592 SCS.Second = ICK_Complex_Promotion;
593 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000594 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000595 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000596 // Integral conversions (C++ 4.7).
597 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000598 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000599 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000600 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
601 // Floating point conversions (C++ 4.8).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000602 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000603 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000604 } else if (FromType->isComplexType() && ToType->isComplexType()) {
605 // Complex conversions (C99 6.3.1.6)
Douglas Gregore819caf2009-02-12 00:15:05 +0000606 SCS.Second = ICK_Complex_Conversion;
607 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000608 } else if ((FromType->isFloatingType() &&
609 ToType->isIntegralType() && (!ToType->isBooleanType() &&
610 !ToType->isEnumeralType())) ||
611 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
612 ToType->isFloatingType())) {
613 // Floating-integral conversions (C++ 4.9).
614 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000615 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000616 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000617 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
618 (ToType->isComplexType() && FromType->isArithmeticType())) {
619 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregore819caf2009-02-12 00:15:05 +0000620 SCS.Second = ICK_Complex_Real;
621 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000622 } else if (IsPointerConversion(From, FromType, ToType, FromType,
623 IncompatibleObjC)) {
624 // Pointer conversions (C++ 4.10).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000625 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000626 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump90fc78e2009-08-04 21:02:39 +0000627 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
628 // Pointer to member conversions (4.11).
Sebastian Redlba387562009-01-25 19:43:20 +0000629 SCS.Second = ICK_Pointer_Member;
Mike Stump90fc78e2009-08-04 21:02:39 +0000630 } else if (ToType->isBooleanType() &&
631 (FromType->isArithmeticType() ||
632 FromType->isEnumeralType() ||
633 FromType->isPointerType() ||
634 FromType->isBlockPointerType() ||
635 FromType->isMemberPointerType() ||
636 FromType->isNullPtrType())) {
637 // Boolean conversions (C++ 4.12).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000638 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000639 FromType = Context.BoolTy;
Mike Stump90fc78e2009-08-04 21:02:39 +0000640 } else if (!getLangOptions().CPlusPlus &&
641 Context.typesAreCompatible(ToType, FromType)) {
642 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000643 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000644 } else {
645 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000646 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000647 }
648
Douglas Gregor81c29152008-10-29 00:13:59 +0000649 QualType CanonFrom;
650 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000651 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000652 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000653 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000654 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000655 CanonFrom = Context.getCanonicalType(FromType);
656 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000657 } else {
658 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000659 SCS.Third = ICK_Identity;
660
661 // C++ [over.best.ics]p6:
662 // [...] Any difference in top-level cv-qualification is
663 // subsumed by the initialization itself and does not constitute
664 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000665 CanonFrom = Context.getCanonicalType(FromType);
666 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000667 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000668 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
669 FromType = ToType;
670 CanonFrom = CanonTo;
671 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000672 }
673
674 // If we have not converted the argument type to the parameter type,
675 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000676 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000677 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000678
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000679 SCS.ToTypePtr = FromType.getAsOpaquePtr();
680 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000681}
682
683/// IsIntegralPromotion - Determines whether the conversion from the
684/// expression From (whose potentially-adjusted type is FromType) to
685/// ToType is an integral promotion (C++ 4.5). If so, returns true and
686/// sets PromotedType to the promoted type.
687bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
688{
689 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000690 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000691 if (!To) {
692 return false;
693 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000694
695 // An rvalue of type char, signed char, unsigned char, short int, or
696 // unsigned short int can be converted to an rvalue of type int if
697 // int can represent all the values of the source type; otherwise,
698 // the source rvalue can be converted to an rvalue of type unsigned
699 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000700 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000701 if (// We can promote any signed, promotable integer type to an int
702 (FromType->isSignedIntegerType() ||
703 // We can promote any unsigned integer type whose size is
704 // less than int to an int.
705 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000706 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000707 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000708 }
709
Douglas Gregord2baafd2008-10-21 16:13:35 +0000710 return To->getKind() == BuiltinType::UInt;
711 }
712
713 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
714 // can be converted to an rvalue of the first of the following types
715 // that can represent all the values of its underlying type: int,
716 // unsigned int, long, or unsigned long (C++ 4.5p2).
717 if ((FromType->isEnumeralType() || FromType->isWideCharType())
718 && ToType->isIntegerType()) {
719 // Determine whether the type we're converting from is signed or
720 // unsigned.
721 bool FromIsSigned;
722 uint64_t FromSize = Context.getTypeSize(FromType);
723 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
724 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
725 FromIsSigned = UnderlyingType->isSignedIntegerType();
726 } else {
727 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
728 FromIsSigned = true;
729 }
730
731 // The types we'll try to promote to, in the appropriate
732 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000733 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000734 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000735 Context.LongTy, Context.UnsignedLongTy ,
736 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000737 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000738 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000739 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
740 if (FromSize < ToSize ||
741 (FromSize == ToSize &&
742 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
743 // We found the type that we can promote to. If this is the
744 // type we wanted, we have a promotion. Otherwise, no
745 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000746 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000747 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
748 }
749 }
750 }
751
752 // An rvalue for an integral bit-field (9.6) can be converted to an
753 // rvalue of type int if int can represent all the values of the
754 // bit-field; otherwise, it can be converted to unsigned int if
755 // unsigned int can represent all the values of the bit-field. If
756 // the bit-field is larger yet, no integral promotion applies to
757 // it. If the bit-field has an enumerated type, it is treated as any
758 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stumpe127ae32009-05-16 07:39:55 +0000759 // FIXME: We should delay checking of bit-fields until we actually perform the
760 // conversion.
Douglas Gregor531434b2009-05-02 02:18:30 +0000761 using llvm::APSInt;
762 if (From)
763 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000764 APSInt BitWidth;
Douglas Gregor531434b2009-05-02 02:18:30 +0000765 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
766 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
767 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
768 ToSize = Context.getTypeSize(ToType);
Douglas Gregor82d44772008-12-20 23:49:58 +0000769
770 // Are we promoting to an int from a bitfield that fits in an int?
771 if (BitWidth < ToSize ||
772 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
773 return To->getKind() == BuiltinType::Int;
774 }
775
776 // Are we promoting to an unsigned int from an unsigned bitfield
777 // that fits into an unsigned int?
778 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
779 return To->getKind() == BuiltinType::UInt;
780 }
781
782 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000783 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000784 }
Douglas Gregor531434b2009-05-02 02:18:30 +0000785
Douglas Gregord2baafd2008-10-21 16:13:35 +0000786 // An rvalue of type bool can be converted to an rvalue of type int,
787 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000788 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000789 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000790 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000791
792 return false;
793}
794
795/// IsFloatingPointPromotion - Determines whether the conversion from
796/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
797/// returns true and sets PromotedType to the promoted type.
798bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
799{
800 /// An rvalue of type float can be converted to an rvalue of type
801 /// double. (C++ 4.6p1).
802 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000803 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000804 if (FromBuiltin->getKind() == BuiltinType::Float &&
805 ToBuiltin->getKind() == BuiltinType::Double)
806 return true;
807
Douglas Gregore819caf2009-02-12 00:15:05 +0000808 // C99 6.3.1.5p1:
809 // When a float is promoted to double or long double, or a
810 // double is promoted to long double [...].
811 if (!getLangOptions().CPlusPlus &&
812 (FromBuiltin->getKind() == BuiltinType::Float ||
813 FromBuiltin->getKind() == BuiltinType::Double) &&
814 (ToBuiltin->getKind() == BuiltinType::LongDouble))
815 return true;
816 }
817
Douglas Gregord2baafd2008-10-21 16:13:35 +0000818 return false;
819}
820
Douglas Gregore819caf2009-02-12 00:15:05 +0000821/// \brief Determine if a conversion is a complex promotion.
822///
823/// A complex promotion is defined as a complex -> complex conversion
824/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000825/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000826bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
827 const ComplexType *FromComplex = FromType->getAsComplexType();
828 if (!FromComplex)
829 return false;
830
831 const ComplexType *ToComplex = ToType->getAsComplexType();
832 if (!ToComplex)
833 return false;
834
835 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000836 ToComplex->getElementType()) ||
837 IsIntegralPromotion(0, FromComplex->getElementType(),
838 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000839}
840
Douglas Gregor24a90a52008-11-26 23:31:11 +0000841/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
842/// the pointer type FromPtr to a pointer to type ToPointee, with the
843/// same type qualifiers as FromPtr has on its pointee type. ToType,
844/// if non-empty, will be a pointer to ToType that may or may not have
845/// the right set of qualifiers on its pointee.
846static QualType
847BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
848 QualType ToPointee, QualType ToType,
849 ASTContext &Context) {
850 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
851 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
852 unsigned Quals = CanonFromPointee.getCVRQualifiers();
853
854 // Exact qualifier match -> return the pointer type we're converting to.
855 if (CanonToPointee.getCVRQualifiers() == Quals) {
856 // ToType is exactly what we need. Return it.
857 if (ToType.getTypePtr())
858 return ToType;
859
860 // Build a pointer to ToPointee. It has the right qualifiers
861 // already.
862 return Context.getPointerType(ToPointee);
863 }
864
865 // Just build a canonical type that has the right qualifiers.
866 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
867}
868
Douglas Gregord2baafd2008-10-21 16:13:35 +0000869/// IsPointerConversion - Determines whether the conversion of the
870/// expression From, which has the (possibly adjusted) type FromType,
871/// can be converted to the type ToType via a pointer conversion (C++
872/// 4.10). If so, returns true and places the converted type (that
873/// might differ from ToType in its cv-qualifiers at some level) into
874/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000875///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000876/// This routine also supports conversions to and from block pointers
877/// and conversions with Objective-C's 'id', 'id<protocols...>', and
878/// pointers to interfaces. FIXME: Once we've determined the
879/// appropriate overloading rules for Objective-C, we may want to
880/// split the Objective-C checks into a different routine; however,
881/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000882/// conversions, so for now they live here. IncompatibleObjC will be
883/// set if the conversion is an allowed Objective-C conversion that
884/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000885bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000886 QualType& ConvertedType,
887 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000888{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000889 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000890 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
891 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000892
Douglas Gregorf1d75712008-12-22 20:51:52 +0000893 // Conversion from a null pointer constant to any Objective-C pointer type.
Steve Naroffad75bd22009-07-16 15:41:00 +0000894 if (ToType->isObjCObjectPointerType() &&
Douglas Gregorf1d75712008-12-22 20:51:52 +0000895 From->isNullPointerConstant(Context)) {
896 ConvertedType = ToType;
897 return true;
898 }
899
Douglas Gregor9036ef72008-11-27 00:15:41 +0000900 // Blocks: Block pointers can be converted to void*.
901 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000902 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor9036ef72008-11-27 00:15:41 +0000903 ConvertedType = ToType;
904 return true;
905 }
906 // Blocks: A null pointer constant can be converted to a block
907 // pointer type.
908 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
909 ConvertedType = ToType;
910 return true;
911 }
912
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000913 // If the left-hand-side is nullptr_t, the right side can be a null
914 // pointer constant.
915 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
916 ConvertedType = ToType;
917 return true;
918 }
919
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000920 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000921 if (!ToTypePtr)
922 return false;
923
924 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
925 if (From->isNullPointerConstant(Context)) {
926 ConvertedType = ToType;
927 return true;
928 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000929
Douglas Gregor24a90a52008-11-26 23:31:11 +0000930 // Beyond this point, both types need to be pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000931 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor24a90a52008-11-26 23:31:11 +0000932 if (!FromTypePtr)
933 return false;
934
935 QualType FromPointeeType = FromTypePtr->getPointeeType();
936 QualType ToPointeeType = ToTypePtr->getPointeeType();
937
Douglas Gregord2baafd2008-10-21 16:13:35 +0000938 // An rvalue of type "pointer to cv T," where T is an object type,
939 // can be converted to an rvalue of type "pointer to cv void" (C++
940 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000941 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000942 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
943 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000944 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000945 return true;
946 }
947
Douglas Gregorfcb19192009-02-11 23:02:49 +0000948 // When we're overloading in C, we allow a special kind of pointer
949 // conversion for compatible-but-not-identical pointee types.
950 if (!getLangOptions().CPlusPlus &&
951 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
952 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
953 ToPointeeType,
954 ToType, Context);
955 return true;
956 }
957
Douglas Gregor14046502008-10-23 00:40:37 +0000958 // C++ [conv.ptr]p3:
959 //
960 // An rvalue of type "pointer to cv D," where D is a class type,
961 // can be converted to an rvalue of type "pointer to cv B," where
962 // B is a base class (clause 10) of D. If B is an inaccessible
963 // (clause 11) or ambiguous (10.2) base class of D, a program that
964 // necessitates this conversion is ill-formed. The result of the
965 // conversion is a pointer to the base class sub-object of the
966 // derived class object. The null pointer value is converted to
967 // the null pointer value of the destination type.
968 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000969 // Note that we do not check for ambiguity or inaccessibility
970 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000971 if (getLangOptions().CPlusPlus &&
972 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000973 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000974 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
975 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000976 ToType, Context);
977 return true;
978 }
Douglas Gregor14046502008-10-23 00:40:37 +0000979
Douglas Gregor932778b2008-12-19 19:13:09 +0000980 return false;
981}
982
983/// isObjCPointerConversion - Determines whether this is an
984/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
985/// with the same arguments and return values.
986bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
987 QualType& ConvertedType,
988 bool &IncompatibleObjC) {
989 if (!getLangOptions().ObjC1)
990 return false;
991
Steve Naroff329ec222009-07-10 23:34:53 +0000992 // First, we handle all conversions on ObjC object pointer types.
993 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
994 const ObjCObjectPointerType *FromObjCPtr =
995 FromType->getAsObjCObjectPointerType();
Douglas Gregor932778b2008-12-19 19:13:09 +0000996
Steve Naroff329ec222009-07-10 23:34:53 +0000997 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff7bffd372009-07-15 18:40:39 +0000998 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff329ec222009-07-10 23:34:53 +0000999 // pointer to any interface (in both directions).
Steve Naroff7bffd372009-07-15 18:40:39 +00001000 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00001001 ConvertedType = ToType;
1002 return true;
1003 }
1004 // Conversions with Objective-C's id<...>.
1005 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1006 ToObjCPtr->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00001007 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1008 /*compare=*/false)) {
Steve Naroff329ec222009-07-10 23:34:53 +00001009 ConvertedType = ToType;
1010 return true;
1011 }
1012 // Objective C++: We're able to convert from a pointer to an
1013 // interface to a pointer to a different interface.
1014 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1015 ConvertedType = ToType;
1016 return true;
1017 }
1018
1019 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1020 // Okay: this is some kind of implicit downcast of Objective-C
1021 // interfaces, which is permitted. However, we're going to
1022 // complain about it.
1023 IncompatibleObjC = true;
1024 ConvertedType = FromType;
1025 return true;
1026 }
1027 }
1028 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor80402cf2008-12-23 00:53:59 +00001029 QualType ToPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001030 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001031 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001032 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001033 ToPointeeType = ToBlockPtr->getPointeeType();
1034 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001035 return false;
1036
Douglas Gregor80402cf2008-12-23 00:53:59 +00001037 QualType FromPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001038 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001039 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001040 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001041 FromPointeeType = FromBlockPtr->getPointeeType();
1042 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001043 return false;
1044
Douglas Gregor932778b2008-12-19 19:13:09 +00001045 // If we have pointers to pointers, recursively check whether this
1046 // is an Objective-C conversion.
1047 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1048 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1049 IncompatibleObjC)) {
1050 // We always complain about this conversion.
1051 IncompatibleObjC = true;
1052 ConvertedType = ToType;
1053 return true;
1054 }
Douglas Gregor80402cf2008-12-23 00:53:59 +00001055 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001056 // differences in the argument and result types are in Objective-C
1057 // pointer conversions. If so, we permit the conversion (but
1058 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001059 const FunctionProtoType *FromFunctionType
1060 = FromPointeeType->getAsFunctionProtoType();
1061 const FunctionProtoType *ToFunctionType
1062 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001063 if (FromFunctionType && ToFunctionType) {
1064 // If the function types are exactly the same, this isn't an
1065 // Objective-C pointer conversion.
1066 if (Context.getCanonicalType(FromPointeeType)
1067 == Context.getCanonicalType(ToPointeeType))
1068 return false;
1069
1070 // Perform the quick checks that will tell us whether these
1071 // function types are obviously different.
1072 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1073 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1074 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1075 return false;
1076
1077 bool HasObjCConversion = false;
1078 if (Context.getCanonicalType(FromFunctionType->getResultType())
1079 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1080 // Okay, the types match exactly. Nothing to do.
1081 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1082 ToFunctionType->getResultType(),
1083 ConvertedType, IncompatibleObjC)) {
1084 // Okay, we have an Objective-C pointer conversion.
1085 HasObjCConversion = true;
1086 } else {
1087 // Function types are too different. Abort.
1088 return false;
1089 }
1090
1091 // Check argument types.
1092 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1093 ArgIdx != NumArgs; ++ArgIdx) {
1094 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1095 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1096 if (Context.getCanonicalType(FromArgType)
1097 == Context.getCanonicalType(ToArgType)) {
1098 // Okay, the types match exactly. Nothing to do.
1099 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1100 ConvertedType, IncompatibleObjC)) {
1101 // Okay, we have an Objective-C pointer conversion.
1102 HasObjCConversion = true;
1103 } else {
1104 // Argument types are too different. Abort.
1105 return false;
1106 }
1107 }
1108
1109 if (HasObjCConversion) {
1110 // We had an Objective-C conversion. Allow this pointer
1111 // conversion, but complain about it.
1112 ConvertedType = ToType;
1113 IncompatibleObjC = true;
1114 return true;
1115 }
1116 }
1117
Sebastian Redlba387562009-01-25 19:43:20 +00001118 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001119}
1120
Douglas Gregorbb461502008-10-24 04:54:22 +00001121/// CheckPointerConversion - Check the pointer conversion from the
1122/// expression From to the type ToType. This routine checks for
Sebastian Redl0e35d042009-07-25 15:41:38 +00001123/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregorbb461502008-10-24 04:54:22 +00001124/// conversions for which IsPointerConversion has already returned
1125/// true. It returns true and produces a diagnostic if there was an
1126/// error, or returns false otherwise.
1127bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1128 QualType FromType = From->getType();
1129
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001130 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1131 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001132 QualType FromPointeeType = FromPtrType->getPointeeType(),
1133 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001134
Douglas Gregorbb461502008-10-24 04:54:22 +00001135 if (FromPointeeType->isRecordType() &&
1136 ToPointeeType->isRecordType()) {
1137 // We must have a derived-to-base conversion. Check an
1138 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001139 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1140 From->getExprLoc(),
1141 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001142 }
1143 }
Steve Naroff329ec222009-07-10 23:34:53 +00001144 if (const ObjCObjectPointerType *FromPtrType =
1145 FromType->getAsObjCObjectPointerType())
1146 if (const ObjCObjectPointerType *ToPtrType =
1147 ToType->getAsObjCObjectPointerType()) {
1148 // Objective-C++ conversions are always okay.
1149 // FIXME: We should have a different class of conversions for the
1150 // Objective-C++ implicit conversions.
Steve Naroff7bffd372009-07-15 18:40:39 +00001151 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff329ec222009-07-10 23:34:53 +00001152 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +00001153
Steve Naroff329ec222009-07-10 23:34:53 +00001154 }
Douglas Gregorbb461502008-10-24 04:54:22 +00001155 return false;
1156}
1157
Sebastian Redlba387562009-01-25 19:43:20 +00001158/// IsMemberPointerConversion - Determines whether the conversion of the
1159/// expression From, which has the (possibly adjusted) type FromType, can be
1160/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1161/// If so, returns true and places the converted type (that might differ from
1162/// ToType in its cv-qualifiers at some level) into ConvertedType.
1163bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1164 QualType ToType, QualType &ConvertedType)
1165{
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001166 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001167 if (!ToTypePtr)
1168 return false;
1169
1170 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1171 if (From->isNullPointerConstant(Context)) {
1172 ConvertedType = ToType;
1173 return true;
1174 }
1175
1176 // Otherwise, both types have to be member pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001177 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001178 if (!FromTypePtr)
1179 return false;
1180
1181 // A pointer to member of B can be converted to a pointer to member of D,
1182 // where D is derived from B (C++ 4.11p2).
1183 QualType FromClass(FromTypePtr->getClass(), 0);
1184 QualType ToClass(ToTypePtr->getClass(), 0);
1185 // FIXME: What happens when these are dependent? Is this function even called?
1186
1187 if (IsDerivedFrom(ToClass, FromClass)) {
1188 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1189 ToClass.getTypePtr());
1190 return true;
1191 }
1192
1193 return false;
1194}
1195
1196/// CheckMemberPointerConversion - Check the member pointer conversion from the
1197/// expression From to the type ToType. This routine checks for ambiguous or
1198/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1199/// for which IsMemberPointerConversion has already returned true. It returns
1200/// true and produces a diagnostic if there was an error, or returns false
1201/// otherwise.
1202bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1203 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001204 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001205 if (!FromPtrType)
1206 return false;
Sebastian Redlba387562009-01-25 19:43:20 +00001207
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001208 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001209 assert(ToPtrType && "No member pointer cast has a target type "
1210 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001211
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001212 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1213 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001214
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001215 // FIXME: What about dependent types?
1216 assert(FromClass->isRecordType() && "Pointer into non-class.");
1217 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001218
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001219 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1220 /*DetectVirtual=*/true);
1221 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1222 assert(DerivationOkay &&
1223 "Should not have been called if derivation isn't OK.");
1224 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001225
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001226 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1227 getUnqualifiedType())) {
1228 // Derivation is ambiguous. Redo the check to find the exact paths.
1229 Paths.clear();
1230 Paths.setRecordingPaths(true);
1231 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1232 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1233 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001234
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001235 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1236 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1237 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1238 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001239 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001240
Douglas Gregor2e047592009-02-28 01:32:25 +00001241 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001242 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1243 << FromClass << ToClass << QualType(VBase, 0)
1244 << From->getSourceRange();
1245 return true;
1246 }
1247
Sebastian Redlba387562009-01-25 19:43:20 +00001248 return false;
1249}
1250
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001251/// IsQualificationConversion - Determines whether the conversion from
1252/// an rvalue of type FromType to ToType is a qualification conversion
1253/// (C++ 4.4).
1254bool
1255Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1256{
1257 FromType = Context.getCanonicalType(FromType);
1258 ToType = Context.getCanonicalType(ToType);
1259
1260 // If FromType and ToType are the same type, this is not a
1261 // qualification conversion.
1262 if (FromType == ToType)
1263 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001264
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001265 // (C++ 4.4p4):
1266 // A conversion can add cv-qualifiers at levels other than the first
1267 // in multi-level pointers, subject to the following rules: [...]
1268 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001269 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001270 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001271 // Within each iteration of the loop, we check the qualifiers to
1272 // determine if this still looks like a qualification
1273 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001274 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001275 // until there are no more pointers or pointers-to-members left to
1276 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001277 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001278
1279 // -- for every j > 0, if const is in cv 1,j then const is in cv
1280 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001281 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001282 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001283
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001284 // -- if the cv 1,j and cv 2,j are different, then const is in
1285 // every cv for 0 < k < j.
1286 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001287 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001288 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001289
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001290 // Keep track of whether all prior cv-qualifiers in the "to" type
1291 // include const.
1292 PreviousToQualsIncludeConst
1293 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001294 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001295
1296 // We are left with FromType and ToType being the pointee types
1297 // after unwrapping the original FromType and ToType the same number
1298 // of types. If we unwrapped any pointers, and if FromType and
1299 // ToType have the same unqualified type (since we checked
1300 // qualifiers above), then this is a qualification conversion.
1301 return UnwrappedAnyPointer &&
1302 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1303}
1304
Douglas Gregor8c860df2009-08-21 23:19:43 +00001305/// \brief Given a function template or function, extract the function template
1306/// declaration (if any) and the underlying function declaration.
1307template<typename T>
1308static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1309 FunctionTemplateDecl *&FunctionTemplate) {
1310 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1311 if (FunctionTemplate)
1312 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1313 else
1314 Function = cast<T>(Orig);
1315}
1316
1317
Douglas Gregorb206cc42009-01-30 23:27:23 +00001318/// Determines whether there is a user-defined conversion sequence
1319/// (C++ [over.ics.user]) that converts expression From to the type
1320/// ToType. If such a conversion exists, User will contain the
1321/// user-defined conversion sequence that performs such a conversion
1322/// and this routine will return true. Otherwise, this routine returns
1323/// false and User is unspecified.
1324///
1325/// \param AllowConversionFunctions true if the conversion should
1326/// consider conversion functions at all. If false, only constructors
1327/// will be considered.
1328///
1329/// \param AllowExplicit true if the conversion should consider C++0x
1330/// "explicit" conversion functions as well as non-explicit conversion
1331/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001332///
1333/// \param ForceRValue true if the expression should be treated as an rvalue
1334/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001335bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001336 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001337 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001338 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001339{
1340 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001341 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001342 if (CXXRecordDecl *ToRecordDecl
1343 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1344 // C++ [over.match.ctor]p1:
1345 // When objects of class type are direct-initialized (8.5), or
1346 // copy-initialized from an expression of the same or a
1347 // derived class type (8.5), overload resolution selects the
1348 // constructor. [...] For copy-initialization, the candidate
1349 // functions are all the converting constructors (12.3.1) of
1350 // that class. The argument list is the expression-list within
1351 // the parentheses of the initializer.
1352 DeclarationName ConstructorName
1353 = Context.DeclarationNames.getCXXConstructorName(
1354 Context.getCanonicalType(ToType).getUnqualifiedType());
1355 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001356 for (llvm::tie(Con, ConEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001357 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001358 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00001359 // Find the constructor (which may be a template).
1360 CXXConstructorDecl *Constructor = 0;
1361 FunctionTemplateDecl *ConstructorTmpl
1362 = dyn_cast<FunctionTemplateDecl>(*Con);
1363 if (ConstructorTmpl)
1364 Constructor
1365 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1366 else
1367 Constructor = cast<CXXConstructorDecl>(*Con);
1368
Fariborz Jahanian625fb9d2009-08-06 17:22:51 +00001369 if (!Constructor->isInvalidDecl() &&
Douglas Gregor050cabf2009-08-21 18:42:58 +00001370 Constructor->isConvertingConstructor()) {
1371 if (ConstructorTmpl)
1372 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1373 1, CandidateSet,
1374 /*SuppressUserConversions=*/true,
1375 ForceRValue);
1376 else
1377 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1378 /*SuppressUserConversions=*/true, ForceRValue);
1379 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001380 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001381 }
1382 }
1383
Douglas Gregorb206cc42009-01-30 23:27:23 +00001384 if (!AllowConversionFunctions) {
1385 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-02-28 01:32:25 +00001386 } else if (const RecordType *FromRecordType
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001387 = From->getType()->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001388 if (CXXRecordDecl *FromRecordDecl
1389 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1390 // Add all of the conversion functions as candidates.
1391 // FIXME: Look for conversions in base classes!
1392 OverloadedFunctionDecl *Conversions
1393 = FromRecordDecl->getConversionFunctions();
1394 for (OverloadedFunctionDecl::function_iterator Func
1395 = Conversions->function_begin();
1396 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001397 CXXConversionDecl *Conv;
1398 FunctionTemplateDecl *ConvTemplate;
1399 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1400 if (ConvTemplate)
1401 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1402 else
1403 Conv = dyn_cast<CXXConversionDecl>(*Func);
1404
1405 if (AllowExplicit || !Conv->isExplicit()) {
1406 if (ConvTemplate)
1407 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1408 CandidateSet);
1409 else
1410 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1411 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001412 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001413 }
1414 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001415
1416 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001417 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001418 case OR_Success:
1419 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001420 if (CXXConstructorDecl *Constructor
1421 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1422 // C++ [over.ics.user]p1:
1423 // If the user-defined conversion is specified by a
1424 // constructor (12.3.1), the initial standard conversion
1425 // sequence converts the source type to the type required by
1426 // the argument of the constructor.
1427 //
1428 // FIXME: What about ellipsis conversions?
1429 QualType ThisType = Constructor->getThisType(Context);
1430 User.Before = Best->Conversions[0].Standard;
1431 User.ConversionFunction = Constructor;
1432 User.After.setAsIdentityConversion();
1433 User.After.FromTypePtr
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001434 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001435 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1436 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001437 } else if (CXXConversionDecl *Conversion
1438 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1439 // C++ [over.ics.user]p1:
1440 //
1441 // [...] If the user-defined conversion is specified by a
1442 // conversion function (12.3.2), the initial standard
1443 // conversion sequence converts the source type to the
1444 // implicit object parameter of the conversion function.
1445 User.Before = Best->Conversions[0].Standard;
1446 User.ConversionFunction = Conversion;
1447
1448 // C++ [over.ics.user]p2:
1449 // The second standard conversion sequence converts the
1450 // result of the user-defined conversion to the target type
1451 // for the sequence. Since an implicit conversion sequence
1452 // is an initialization, the special rules for
1453 // initialization by user-defined conversion apply when
1454 // selecting the best user-defined conversion for a
1455 // user-defined conversion sequence (see 13.3.3 and
1456 // 13.3.3.1).
1457 User.After = Best->FinalConversion;
1458 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001459 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001460 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001461 return false;
1462 }
1463
1464 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001465 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001466 // No conversion here! We're done.
1467 return false;
1468
1469 case OR_Ambiguous:
1470 // FIXME: See C++ [over.best.ics]p10 for the handling of
1471 // ambiguous conversion sequences.
1472 return false;
1473 }
1474
1475 return false;
1476}
1477
Douglas Gregord2baafd2008-10-21 16:13:35 +00001478/// CompareImplicitConversionSequences - Compare two implicit
1479/// conversion sequences to determine whether one is better than the
1480/// other or if they are indistinguishable (C++ 13.3.3.2).
1481ImplicitConversionSequence::CompareKind
1482Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1483 const ImplicitConversionSequence& ICS2)
1484{
1485 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1486 // conversion sequences (as defined in 13.3.3.1)
1487 // -- a standard conversion sequence (13.3.3.1.1) is a better
1488 // conversion sequence than a user-defined conversion sequence or
1489 // an ellipsis conversion sequence, and
1490 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1491 // conversion sequence than an ellipsis conversion sequence
1492 // (13.3.3.1.3).
1493 //
1494 if (ICS1.ConversionKind < ICS2.ConversionKind)
1495 return ImplicitConversionSequence::Better;
1496 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1497 return ImplicitConversionSequence::Worse;
1498
1499 // Two implicit conversion sequences of the same form are
1500 // indistinguishable conversion sequences unless one of the
1501 // following rules apply: (C++ 13.3.3.2p3):
1502 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1503 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1504 else if (ICS1.ConversionKind ==
1505 ImplicitConversionSequence::UserDefinedConversion) {
1506 // User-defined conversion sequence U1 is a better conversion
1507 // sequence than another user-defined conversion sequence U2 if
1508 // they contain the same user-defined conversion function or
1509 // constructor and if the second standard conversion sequence of
1510 // U1 is better than the second standard conversion sequence of
1511 // U2 (C++ 13.3.3.2p3).
1512 if (ICS1.UserDefined.ConversionFunction ==
1513 ICS2.UserDefined.ConversionFunction)
1514 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1515 ICS2.UserDefined.After);
1516 }
1517
1518 return ImplicitConversionSequence::Indistinguishable;
1519}
1520
1521/// CompareStandardConversionSequences - Compare two standard
1522/// conversion sequences to determine whether one is better than the
1523/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1524ImplicitConversionSequence::CompareKind
1525Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1526 const StandardConversionSequence& SCS2)
1527{
1528 // Standard conversion sequence S1 is a better conversion sequence
1529 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1530
1531 // -- S1 is a proper subsequence of S2 (comparing the conversion
1532 // sequences in the canonical form defined by 13.3.3.1.1,
1533 // excluding any Lvalue Transformation; the identity conversion
1534 // sequence is considered to be a subsequence of any
1535 // non-identity conversion sequence) or, if not that,
1536 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1537 // Neither is a proper subsequence of the other. Do nothing.
1538 ;
1539 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1540 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1541 (SCS1.Second == ICK_Identity &&
1542 SCS1.Third == ICK_Identity))
1543 // SCS1 is a proper subsequence of SCS2.
1544 return ImplicitConversionSequence::Better;
1545 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1546 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1547 (SCS2.Second == ICK_Identity &&
1548 SCS2.Third == ICK_Identity))
1549 // SCS2 is a proper subsequence of SCS1.
1550 return ImplicitConversionSequence::Worse;
1551
1552 // -- the rank of S1 is better than the rank of S2 (by the rules
1553 // defined below), or, if not that,
1554 ImplicitConversionRank Rank1 = SCS1.getRank();
1555 ImplicitConversionRank Rank2 = SCS2.getRank();
1556 if (Rank1 < Rank2)
1557 return ImplicitConversionSequence::Better;
1558 else if (Rank2 < Rank1)
1559 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001560
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001561 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1562 // are indistinguishable unless one of the following rules
1563 // applies:
1564
1565 // A conversion that is not a conversion of a pointer, or
1566 // pointer to member, to bool is better than another conversion
1567 // that is such a conversion.
1568 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1569 return SCS2.isPointerConversionToBool()
1570 ? ImplicitConversionSequence::Better
1571 : ImplicitConversionSequence::Worse;
1572
Douglas Gregor14046502008-10-23 00:40:37 +00001573 // C++ [over.ics.rank]p4b2:
1574 //
1575 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001576 // conversion of B* to A* is better than conversion of B* to
1577 // void*, and conversion of A* to void* is better than conversion
1578 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001579 bool SCS1ConvertsToVoid
1580 = SCS1.isPointerConversionToVoidPointer(Context);
1581 bool SCS2ConvertsToVoid
1582 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001583 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1584 // Exactly one of the conversion sequences is a conversion to
1585 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001586 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1587 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001588 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1589 // Neither conversion sequence converts to a void pointer; compare
1590 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001591 if (ImplicitConversionSequence::CompareKind DerivedCK
1592 = CompareDerivedToBaseConversions(SCS1, SCS2))
1593 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001594 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1595 // Both conversion sequences are conversions to void
1596 // pointers. Compare the source types to determine if there's an
1597 // inheritance relationship in their sources.
1598 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1599 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1600
1601 // Adjust the types we're converting from via the array-to-pointer
1602 // conversion, if we need to.
1603 if (SCS1.First == ICK_Array_To_Pointer)
1604 FromType1 = Context.getArrayDecayedType(FromType1);
1605 if (SCS2.First == ICK_Array_To_Pointer)
1606 FromType2 = Context.getArrayDecayedType(FromType2);
1607
1608 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001609 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001610 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001611 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001612
1613 if (IsDerivedFrom(FromPointee2, FromPointee1))
1614 return ImplicitConversionSequence::Better;
1615 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1616 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001617
1618 // Objective-C++: If one interface is more specific than the
1619 // other, it is the better one.
1620 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1621 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1622 if (FromIface1 && FromIface1) {
1623 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1624 return ImplicitConversionSequence::Better;
1625 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1626 return ImplicitConversionSequence::Worse;
1627 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001628 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001629
1630 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1631 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001632 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001633 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001634 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001635
Douglas Gregor0e343382008-10-29 14:50:44 +00001636 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001637 // C++0x [over.ics.rank]p3b4:
1638 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1639 // implicit object parameter of a non-static member function declared
1640 // without a ref-qualifier, and S1 binds an rvalue reference to an
1641 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001642 // FIXME: We don't know if we're dealing with the implicit object parameter,
1643 // or if the member function in this case has a ref qualifier.
1644 // (Of course, we don't have ref qualifiers yet.)
1645 if (SCS1.RRefBinding != SCS2.RRefBinding)
1646 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1647 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001648
1649 // C++ [over.ics.rank]p3b4:
1650 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1651 // which the references refer are the same type except for
1652 // top-level cv-qualifiers, and the type to which the reference
1653 // initialized by S2 refers is more cv-qualified than the type
1654 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001655 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1656 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001657 T1 = Context.getCanonicalType(T1);
1658 T2 = Context.getCanonicalType(T2);
1659 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1660 if (T2.isMoreQualifiedThan(T1))
1661 return ImplicitConversionSequence::Better;
1662 else if (T1.isMoreQualifiedThan(T2))
1663 return ImplicitConversionSequence::Worse;
1664 }
1665 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001666
1667 return ImplicitConversionSequence::Indistinguishable;
1668}
1669
1670/// CompareQualificationConversions - Compares two standard conversion
1671/// sequences to determine whether they can be ranked based on their
1672/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1673ImplicitConversionSequence::CompareKind
1674Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1675 const StandardConversionSequence& SCS2)
1676{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001677 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001678 // -- S1 and S2 differ only in their qualification conversion and
1679 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1680 // cv-qualification signature of type T1 is a proper subset of
1681 // the cv-qualification signature of type T2, and S1 is not the
1682 // deprecated string literal array-to-pointer conversion (4.2).
1683 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1684 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1685 return ImplicitConversionSequence::Indistinguishable;
1686
1687 // FIXME: the example in the standard doesn't use a qualification
1688 // conversion (!)
1689 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1690 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1691 T1 = Context.getCanonicalType(T1);
1692 T2 = Context.getCanonicalType(T2);
1693
1694 // If the types are the same, we won't learn anything by unwrapped
1695 // them.
1696 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1697 return ImplicitConversionSequence::Indistinguishable;
1698
1699 ImplicitConversionSequence::CompareKind Result
1700 = ImplicitConversionSequence::Indistinguishable;
1701 while (UnwrapSimilarPointerTypes(T1, T2)) {
1702 // Within each iteration of the loop, we check the qualifiers to
1703 // determine if this still looks like a qualification
1704 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001705 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001706 // until there are no more pointers or pointers-to-members left
1707 // to unwrap. This essentially mimics what
1708 // IsQualificationConversion does, but here we're checking for a
1709 // strict subset of qualifiers.
1710 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1711 // The qualifiers are the same, so this doesn't tell us anything
1712 // about how the sequences rank.
1713 ;
1714 else if (T2.isMoreQualifiedThan(T1)) {
1715 // T1 has fewer qualifiers, so it could be the better sequence.
1716 if (Result == ImplicitConversionSequence::Worse)
1717 // Neither has qualifiers that are a subset of the other's
1718 // qualifiers.
1719 return ImplicitConversionSequence::Indistinguishable;
1720
1721 Result = ImplicitConversionSequence::Better;
1722 } else if (T1.isMoreQualifiedThan(T2)) {
1723 // T2 has fewer qualifiers, so it could be the better sequence.
1724 if (Result == ImplicitConversionSequence::Better)
1725 // Neither has qualifiers that are a subset of the other's
1726 // qualifiers.
1727 return ImplicitConversionSequence::Indistinguishable;
1728
1729 Result = ImplicitConversionSequence::Worse;
1730 } else {
1731 // Qualifiers are disjoint.
1732 return ImplicitConversionSequence::Indistinguishable;
1733 }
1734
1735 // If the types after this point are equivalent, we're done.
1736 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1737 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001738 }
1739
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001740 // Check that the winning standard conversion sequence isn't using
1741 // the deprecated string literal array to pointer conversion.
1742 switch (Result) {
1743 case ImplicitConversionSequence::Better:
1744 if (SCS1.Deprecated)
1745 Result = ImplicitConversionSequence::Indistinguishable;
1746 break;
1747
1748 case ImplicitConversionSequence::Indistinguishable:
1749 break;
1750
1751 case ImplicitConversionSequence::Worse:
1752 if (SCS2.Deprecated)
1753 Result = ImplicitConversionSequence::Indistinguishable;
1754 break;
1755 }
1756
1757 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001758}
1759
Douglas Gregor14046502008-10-23 00:40:37 +00001760/// CompareDerivedToBaseConversions - Compares two standard conversion
1761/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001762/// various kinds of derived-to-base conversions (C++
1763/// [over.ics.rank]p4b3). As part of these checks, we also look at
1764/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001765ImplicitConversionSequence::CompareKind
1766Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1767 const StandardConversionSequence& SCS2) {
1768 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1769 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1770 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1771 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1772
1773 // Adjust the types we're converting from via the array-to-pointer
1774 // conversion, if we need to.
1775 if (SCS1.First == ICK_Array_To_Pointer)
1776 FromType1 = Context.getArrayDecayedType(FromType1);
1777 if (SCS2.First == ICK_Array_To_Pointer)
1778 FromType2 = Context.getArrayDecayedType(FromType2);
1779
1780 // Canonicalize all of the types.
1781 FromType1 = Context.getCanonicalType(FromType1);
1782 ToType1 = Context.getCanonicalType(ToType1);
1783 FromType2 = Context.getCanonicalType(FromType2);
1784 ToType2 = Context.getCanonicalType(ToType2);
1785
Douglas Gregor0e343382008-10-29 14:50:44 +00001786 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001787 //
1788 // If class B is derived directly or indirectly from class A and
1789 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001790 //
1791 // For Objective-C, we let A, B, and C also be Objective-C
1792 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001793
1794 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001795 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001796 SCS2.Second == ICK_Pointer_Conversion &&
1797 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1798 FromType1->isPointerType() && FromType2->isPointerType() &&
1799 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001800 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001801 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001802 QualType ToPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001803 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001804 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001805 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001806 QualType ToPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001807 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001808
1809 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1810 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1811 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1812 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1813
Douglas Gregor0e343382008-10-29 14:50:44 +00001814 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001815 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1816 if (IsDerivedFrom(ToPointee1, ToPointee2))
1817 return ImplicitConversionSequence::Better;
1818 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1819 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001820
1821 if (ToIface1 && ToIface2) {
1822 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1823 return ImplicitConversionSequence::Better;
1824 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1825 return ImplicitConversionSequence::Worse;
1826 }
Douglas Gregor14046502008-10-23 00:40:37 +00001827 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001828
1829 // -- conversion of B* to A* is better than conversion of C* to A*,
1830 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1831 if (IsDerivedFrom(FromPointee2, FromPointee1))
1832 return ImplicitConversionSequence::Better;
1833 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1834 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001835
1836 if (FromIface1 && FromIface2) {
1837 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1838 return ImplicitConversionSequence::Better;
1839 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1840 return ImplicitConversionSequence::Worse;
1841 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001842 }
Douglas Gregor14046502008-10-23 00:40:37 +00001843 }
1844
Douglas Gregor0e343382008-10-29 14:50:44 +00001845 // Compare based on reference bindings.
1846 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1847 SCS1.Second == ICK_Derived_To_Base) {
1848 // -- binding of an expression of type C to a reference of type
1849 // B& is better than binding an expression of type C to a
1850 // reference of type A&,
1851 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1852 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1853 if (IsDerivedFrom(ToType1, ToType2))
1854 return ImplicitConversionSequence::Better;
1855 else if (IsDerivedFrom(ToType2, ToType1))
1856 return ImplicitConversionSequence::Worse;
1857 }
1858
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001859 // -- binding of an expression of type B to a reference of type
1860 // A& is better than binding an expression of type C to a
1861 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001862 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1863 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1864 if (IsDerivedFrom(FromType2, FromType1))
1865 return ImplicitConversionSequence::Better;
1866 else if (IsDerivedFrom(FromType1, FromType2))
1867 return ImplicitConversionSequence::Worse;
1868 }
1869 }
1870
1871
1872 // FIXME: conversion of A::* to B::* is better than conversion of
1873 // A::* to C::*,
1874
1875 // FIXME: conversion of B::* to C::* is better than conversion of
1876 // A::* to C::*, and
1877
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001878 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1879 SCS1.Second == ICK_Derived_To_Base) {
1880 // -- conversion of C to B is better than conversion of C to A,
1881 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1882 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1883 if (IsDerivedFrom(ToType1, ToType2))
1884 return ImplicitConversionSequence::Better;
1885 else if (IsDerivedFrom(ToType2, ToType1))
1886 return ImplicitConversionSequence::Worse;
1887 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001888
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001889 // -- conversion of B to A is better than conversion of C to A.
1890 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1891 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1892 if (IsDerivedFrom(FromType2, FromType1))
1893 return ImplicitConversionSequence::Better;
1894 else if (IsDerivedFrom(FromType1, FromType2))
1895 return ImplicitConversionSequence::Worse;
1896 }
1897 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001898
Douglas Gregor14046502008-10-23 00:40:37 +00001899 return ImplicitConversionSequence::Indistinguishable;
1900}
1901
Douglas Gregor81c29152008-10-29 00:13:59 +00001902/// TryCopyInitialization - Try to copy-initialize a value of type
1903/// ToType from the expression From. Return the implicit conversion
1904/// sequence required to pass this argument, which may be a bad
1905/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001906/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001907/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1908/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001909ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001910Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001911 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001912 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001913 ImplicitConversionSequence ICS;
Sebastian Redla55834a2009-04-12 17:16:29 +00001914 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1915 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001916 return ICS;
1917 } else {
Sebastian Redla55834a2009-04-12 17:16:29 +00001918 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1919 ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001920 }
1921}
1922
Sebastian Redla55834a2009-04-12 17:16:29 +00001923/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1924/// the expression @p From. Returns true (and emits a diagnostic) if there was
1925/// an error, returns false if the initialization succeeded. Elidable should
1926/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1927/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001928bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001929 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001930 if (!getLangOptions().CPlusPlus) {
1931 // In C, argument passing is the same as performing an assignment.
1932 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001933
Douglas Gregor81c29152008-10-29 00:13:59 +00001934 AssignConvertType ConvTy =
1935 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001936 if (ConvTy != Compatible &&
1937 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1938 ConvTy = Compatible;
1939
Douglas Gregor81c29152008-10-29 00:13:59 +00001940 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1941 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001942 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001943
Chris Lattner271d4c22008-11-24 05:29:24 +00001944 if (ToType->isReferenceType())
1945 return CheckReferenceInit(From, ToType);
1946
Sebastian Redla55834a2009-04-12 17:16:29 +00001947 if (!PerformImplicitConversion(From, ToType, Flavor,
1948 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001949 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001950
Chris Lattner271d4c22008-11-24 05:29:24 +00001951 return Diag(From->getSourceRange().getBegin(),
1952 diag::err_typecheck_convert_incompatible)
1953 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001954}
1955
Douglas Gregor5ed15042008-11-18 23:14:02 +00001956/// TryObjectArgumentInitialization - Try to initialize the object
1957/// parameter of the given member function (@c Method) from the
1958/// expression @p From.
1959ImplicitConversionSequence
1960Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1961 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1962 unsigned MethodQuals = Method->getTypeQualifiers();
1963 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1964
1965 // Set up the conversion sequence as a "bad" conversion, to allow us
1966 // to exit early.
1967 ImplicitConversionSequence ICS;
1968 ICS.Standard.setAsIdentityConversion();
1969 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1970
1971 // We need to have an object of class type.
1972 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001973 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001974 FromType = PT->getPointeeType();
1975
1976 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00001977
1978 // The implicit object parmeter is has the type "reference to cv X",
1979 // where X is the class of which the function is a member
1980 // (C++ [over.match.funcs]p4). However, when finding an implicit
1981 // conversion sequence for the argument, we are not allowed to
1982 // create temporaries or perform user-defined conversions
1983 // (C++ [over.match.funcs]p5). We perform a simplified version of
1984 // reference binding here, that allows class rvalues to bind to
1985 // non-constant references.
1986
1987 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1988 // with the implicit object parameter (C++ [over.match.funcs]p5).
1989 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1990 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1991 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1992 return ICS;
1993
1994 // Check that we have either the same type or a derived type. It
1995 // affects the conversion rank.
1996 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1997 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1998 ICS.Standard.Second = ICK_Identity;
1999 else if (IsDerivedFrom(FromType, ClassType))
2000 ICS.Standard.Second = ICK_Derived_To_Base;
2001 else
2002 return ICS;
2003
2004 // Success. Mark this as a reference binding.
2005 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2006 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2007 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2008 ICS.Standard.ReferenceBinding = true;
2009 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00002010 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002011 return ICS;
2012}
2013
2014/// PerformObjectArgumentInitialization - Perform initialization of
2015/// the implicit object parameter for the given Method with the given
2016/// expression.
2017bool
2018Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002019 QualType FromRecordType, DestType;
2020 QualType ImplicitParamRecordType =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002021 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002022
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002023 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002024 FromRecordType = PT->getPointeeType();
2025 DestType = Method->getThisType(Context);
2026 } else {
2027 FromRecordType = From->getType();
2028 DestType = ImplicitParamRecordType;
2029 }
2030
Douglas Gregor5ed15042008-11-18 23:14:02 +00002031 ImplicitConversionSequence ICS
2032 = TryObjectArgumentInitialization(From, Method);
2033 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2034 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002035 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002036 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2037
Douglas Gregor5ed15042008-11-18 23:14:02 +00002038 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002039 CheckDerivedToBaseConversion(FromRecordType,
2040 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002041 From->getSourceRange().getBegin(),
2042 From->getSourceRange()))
2043 return true;
2044
Anders Carlssone25b6cd2009-08-07 18:45:49 +00002045 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2046 /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002047 return false;
2048}
2049
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002050/// TryContextuallyConvertToBool - Attempt to contextually convert the
2051/// expression From to bool (C++0x [conv]p3).
2052ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2053 return TryImplicitConversion(From, Context.BoolTy, false, true);
2054}
2055
2056/// PerformContextuallyConvertToBool - Perform a contextual conversion
2057/// of the expression From to bool (C++0x [conv]p3).
2058bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2059 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2060 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2061 return false;
2062
2063 return Diag(From->getSourceRange().getBegin(),
2064 diag::err_typecheck_bool_condition)
2065 << From->getType() << From->getSourceRange();
2066}
2067
Douglas Gregord2baafd2008-10-21 16:13:35 +00002068/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002069/// candidate functions, using the given function call arguments. If
2070/// @p SuppressUserConversions, then don't allow user-defined
2071/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002072/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2073/// hacky way to implement the overloading rules for elidable copy
2074/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002075void
2076Sema::AddOverloadCandidate(FunctionDecl *Function,
2077 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002078 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002079 bool SuppressUserConversions,
2080 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002081{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002082 const FunctionProtoType* Proto
2083 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002084 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002085 assert(!isa<CXXConversionDecl>(Function) &&
2086 "Use AddConversionCandidate for conversion functions");
Douglas Gregorb60eb752009-06-25 22:08:12 +00002087 assert(!Function->getDescribedFunctionTemplate() &&
2088 "Use AddTemplateOverloadCandidate for function templates");
2089
Douglas Gregor3257fb52008-12-22 05:46:06 +00002090 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002091 if (!isa<CXXConstructorDecl>(Method)) {
2092 // If we get here, it's because we're calling a member function
2093 // that is named without a member access expression (e.g.,
2094 // "this->f") that was either written explicitly or created
2095 // implicitly. This can happen with a qualified call to a member
2096 // function, e.g., X::f(). We use a NULL object as the implied
2097 // object argument (C++ [over.call.func]p3).
2098 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2099 SuppressUserConversions, ForceRValue);
2100 return;
2101 }
2102 // We treat a constructor like a non-member function, since its object
2103 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002104 }
2105
2106
Douglas Gregord2baafd2008-10-21 16:13:35 +00002107 // Add this candidate
2108 CandidateSet.push_back(OverloadCandidate());
2109 OverloadCandidate& Candidate = CandidateSet.back();
2110 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002111 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002112 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002113 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002114
2115 unsigned NumArgsInProto = Proto->getNumArgs();
2116
2117 // (C++ 13.3.2p2): A candidate function having fewer than m
2118 // parameters is viable only if it has an ellipsis in its parameter
2119 // list (8.3.5).
2120 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2121 Candidate.Viable = false;
2122 return;
2123 }
2124
2125 // (C++ 13.3.2p2): A candidate function having more than m parameters
2126 // is viable only if the (m+1)st parameter has a default argument
2127 // (8.3.6). For the purposes of overload resolution, the
2128 // parameter list is truncated on the right, so that there are
2129 // exactly m parameters.
2130 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2131 if (NumArgs < MinRequiredArgs) {
2132 // Not enough arguments.
2133 Candidate.Viable = false;
2134 return;
2135 }
2136
2137 // Determine the implicit conversion sequences for each of the
2138 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002139 Candidate.Conversions.resize(NumArgs);
2140 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2141 if (ArgIdx < NumArgsInProto) {
2142 // (C++ 13.3.2p3): for F to be a viable function, there shall
2143 // exist for each argument an implicit conversion sequence
2144 // (13.3.3.1) that converts that argument to the corresponding
2145 // parameter of F.
2146 QualType ParamType = Proto->getArgType(ArgIdx);
2147 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002148 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002149 SuppressUserConversions, ForceRValue);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002150 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002151 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002152 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002153 break;
2154 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002155 } else {
2156 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2157 // argument for which there is no corresponding parameter is
2158 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2159 Candidate.Conversions[ArgIdx].ConversionKind
2160 = ImplicitConversionSequence::EllipsisConversion;
2161 }
2162 }
2163}
2164
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002165/// \brief Add all of the function declarations in the given function set to
2166/// the overload canddiate set.
2167void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2168 Expr **Args, unsigned NumArgs,
2169 OverloadCandidateSet& CandidateSet,
2170 bool SuppressUserConversions) {
2171 for (FunctionSet::const_iterator F = Functions.begin(),
2172 FEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00002173 F != FEnd; ++F) {
2174 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2175 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2176 SuppressUserConversions);
2177 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002178 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2179 /*FIXME: explicit args */false, 0, 0,
2180 Args, NumArgs, CandidateSet,
Douglas Gregor993a0602009-06-27 21:05:07 +00002181 SuppressUserConversions);
2182 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002183}
2184
Douglas Gregor5ed15042008-11-18 23:14:02 +00002185/// AddMethodCandidate - Adds the given C++ member function to the set
2186/// of candidate functions, using the given function call arguments
2187/// and the object argument (@c Object). For example, in a call
2188/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2189/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2190/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002191/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2192/// a slightly hacky way to implement the overloading rules for elidable copy
2193/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002194void
2195Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2196 Expr **Args, unsigned NumArgs,
2197 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002198 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002199{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002200 const FunctionProtoType* Proto
2201 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002202 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002203 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002204 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002205 assert(!isa<CXXConstructorDecl>(Method) &&
2206 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002207
2208 // Add this candidate
2209 CandidateSet.push_back(OverloadCandidate());
2210 OverloadCandidate& Candidate = CandidateSet.back();
2211 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002212 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002213 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002214
2215 unsigned NumArgsInProto = Proto->getNumArgs();
2216
2217 // (C++ 13.3.2p2): A candidate function having fewer than m
2218 // parameters is viable only if it has an ellipsis in its parameter
2219 // list (8.3.5).
2220 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2221 Candidate.Viable = false;
2222 return;
2223 }
2224
2225 // (C++ 13.3.2p2): A candidate function having more than m parameters
2226 // is viable only if the (m+1)st parameter has a default argument
2227 // (8.3.6). For the purposes of overload resolution, the
2228 // parameter list is truncated on the right, so that there are
2229 // exactly m parameters.
2230 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2231 if (NumArgs < MinRequiredArgs) {
2232 // Not enough arguments.
2233 Candidate.Viable = false;
2234 return;
2235 }
2236
2237 Candidate.Viable = true;
2238 Candidate.Conversions.resize(NumArgs + 1);
2239
Douglas Gregor3257fb52008-12-22 05:46:06 +00002240 if (Method->isStatic() || !Object)
2241 // The implicit object argument is ignored.
2242 Candidate.IgnoreObjectArgument = true;
2243 else {
2244 // Determine the implicit conversion sequence for the object
2245 // parameter.
2246 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2247 if (Candidate.Conversions[0].ConversionKind
2248 == ImplicitConversionSequence::BadConversion) {
2249 Candidate.Viable = false;
2250 return;
2251 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002252 }
2253
2254 // Determine the implicit conversion sequences for each of the
2255 // arguments.
2256 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2257 if (ArgIdx < NumArgsInProto) {
2258 // (C++ 13.3.2p3): for F to be a viable function, there shall
2259 // exist for each argument an implicit conversion sequence
2260 // (13.3.3.1) that converts that argument to the corresponding
2261 // parameter of F.
2262 QualType ParamType = Proto->getArgType(ArgIdx);
2263 Candidate.Conversions[ArgIdx + 1]
2264 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002265 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002266 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2267 == ImplicitConversionSequence::BadConversion) {
2268 Candidate.Viable = false;
2269 break;
2270 }
2271 } else {
2272 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2273 // argument for which there is no corresponding parameter is
2274 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2275 Candidate.Conversions[ArgIdx + 1].ConversionKind
2276 = ImplicitConversionSequence::EllipsisConversion;
2277 }
2278 }
2279}
2280
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002281/// \brief Add a C++ member function template as a candidate to the candidate
2282/// set, using template argument deduction to produce an appropriate member
2283/// function template specialization.
2284void
2285Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2286 bool HasExplicitTemplateArgs,
2287 const TemplateArgument *ExplicitTemplateArgs,
2288 unsigned NumExplicitTemplateArgs,
2289 Expr *Object, Expr **Args, unsigned NumArgs,
2290 OverloadCandidateSet& CandidateSet,
2291 bool SuppressUserConversions,
2292 bool ForceRValue) {
2293 // C++ [over.match.funcs]p7:
2294 // In each case where a candidate is a function template, candidate
2295 // function template specializations are generated using template argument
2296 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2297 // candidate functions in the usual way.113) A given name can refer to one
2298 // or more function templates and also to a set of overloaded non-template
2299 // functions. In such a case, the candidate functions generated from each
2300 // function template are combined with the set of non-template candidate
2301 // functions.
2302 TemplateDeductionInfo Info(Context);
2303 FunctionDecl *Specialization = 0;
2304 if (TemplateDeductionResult Result
2305 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2306 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2307 Args, NumArgs, Specialization, Info)) {
2308 // FIXME: Record what happened with template argument deduction, so
2309 // that we can give the user a beautiful diagnostic.
2310 (void)Result;
2311 return;
2312 }
2313
2314 // Add the function template specialization produced by template argument
2315 // deduction as a candidate.
2316 assert(Specialization && "Missing member function template specialization?");
2317 assert(isa<CXXMethodDecl>(Specialization) &&
2318 "Specialization is not a member function?");
2319 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2320 CandidateSet, SuppressUserConversions, ForceRValue);
2321}
2322
Douglas Gregor8c860df2009-08-21 23:19:43 +00002323/// \brief Add a C++ function template specialization as a candidate
2324/// in the candidate set, using template argument deduction to produce
2325/// an appropriate function template specialization.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002326void
2327Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002328 bool HasExplicitTemplateArgs,
2329 const TemplateArgument *ExplicitTemplateArgs,
2330 unsigned NumExplicitTemplateArgs,
Douglas Gregorb60eb752009-06-25 22:08:12 +00002331 Expr **Args, unsigned NumArgs,
2332 OverloadCandidateSet& CandidateSet,
2333 bool SuppressUserConversions,
2334 bool ForceRValue) {
2335 // C++ [over.match.funcs]p7:
2336 // In each case where a candidate is a function template, candidate
2337 // function template specializations are generated using template argument
2338 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2339 // candidate functions in the usual way.113) A given name can refer to one
2340 // or more function templates and also to a set of overloaded non-template
2341 // functions. In such a case, the candidate functions generated from each
2342 // function template are combined with the set of non-template candidate
2343 // functions.
2344 TemplateDeductionInfo Info(Context);
2345 FunctionDecl *Specialization = 0;
2346 if (TemplateDeductionResult Result
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002347 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2348 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2349 Args, NumArgs, Specialization, Info)) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00002350 // FIXME: Record what happened with template argument deduction, so
2351 // that we can give the user a beautiful diagnostic.
2352 (void)Result;
2353 return;
2354 }
2355
2356 // Add the function template specialization produced by template argument
2357 // deduction as a candidate.
2358 assert(Specialization && "Missing function template specialization?");
2359 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2360 SuppressUserConversions, ForceRValue);
2361}
2362
Douglas Gregor60714f92008-11-07 22:36:19 +00002363/// AddConversionCandidate - Add a C++ conversion function as a
2364/// candidate in the candidate set (C++ [over.match.conv],
2365/// C++ [over.match.copy]). From is the expression we're converting from,
2366/// and ToType is the type that we're eventually trying to convert to
2367/// (which may or may not be the same type as the type that the
2368/// conversion function produces).
2369void
2370Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2371 Expr *From, QualType ToType,
2372 OverloadCandidateSet& CandidateSet) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002373 assert(!Conversion->getDescribedFunctionTemplate() &&
2374 "Conversion function templates use AddTemplateConversionCandidate");
2375
Douglas Gregor60714f92008-11-07 22:36:19 +00002376 // Add this candidate
2377 CandidateSet.push_back(OverloadCandidate());
2378 OverloadCandidate& Candidate = CandidateSet.back();
2379 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002380 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002381 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002382 Candidate.FinalConversion.setAsIdentityConversion();
2383 Candidate.FinalConversion.FromTypePtr
2384 = Conversion->getConversionType().getAsOpaquePtr();
2385 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2386
Douglas Gregor5ed15042008-11-18 23:14:02 +00002387 // Determine the implicit conversion sequence for the implicit
2388 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002389 Candidate.Viable = true;
2390 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002391 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002392
Douglas Gregor60714f92008-11-07 22:36:19 +00002393 if (Candidate.Conversions[0].ConversionKind
2394 == ImplicitConversionSequence::BadConversion) {
2395 Candidate.Viable = false;
2396 return;
2397 }
2398
2399 // To determine what the conversion from the result of calling the
2400 // conversion function to the type we're eventually trying to
2401 // convert to (ToType), we need to synthesize a call to the
2402 // conversion function and attempt copy initialization from it. This
2403 // makes sure that we get the right semantics with respect to
2404 // lvalues/rvalues and the type. Fortunately, we can allocate this
2405 // call on the stack and we don't need its arguments to be
2406 // well-formed.
2407 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2408 SourceLocation());
2409 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002410 CastExpr::CK_Unknown,
Douglas Gregor70d26122008-11-12 17:17:38 +00002411 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002412
2413 // Note that it is safe to allocate CallExpr on the stack here because
2414 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2415 // allocator).
2416 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002417 Conversion->getConversionType().getNonReferenceType(),
2418 SourceLocation());
2419 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2420 switch (ICS.ConversionKind) {
2421 case ImplicitConversionSequence::StandardConversion:
2422 Candidate.FinalConversion = ICS.Standard;
2423 break;
2424
2425 case ImplicitConversionSequence::BadConversion:
2426 Candidate.Viable = false;
2427 break;
2428
2429 default:
2430 assert(false &&
2431 "Can only end up with a standard conversion sequence or failure");
2432 }
2433}
2434
Douglas Gregor8c860df2009-08-21 23:19:43 +00002435/// \brief Adds a conversion function template specialization
2436/// candidate to the overload set, using template argument deduction
2437/// to deduce the template arguments of the conversion function
2438/// template from the type that we are converting to (C++
2439/// [temp.deduct.conv]).
2440void
2441Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2442 Expr *From, QualType ToType,
2443 OverloadCandidateSet &CandidateSet) {
2444 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2445 "Only conversion function templates permitted here");
2446
2447 TemplateDeductionInfo Info(Context);
2448 CXXConversionDecl *Specialization = 0;
2449 if (TemplateDeductionResult Result
2450 = DeduceTemplateArguments(FunctionTemplate, ToType,
2451 Specialization, Info)) {
2452 // FIXME: Record what happened with template argument deduction, so
2453 // that we can give the user a beautiful diagnostic.
2454 (void)Result;
2455 return;
2456 }
2457
2458 // Add the conversion function template specialization produced by
2459 // template argument deduction as a candidate.
2460 assert(Specialization && "Missing function template specialization?");
2461 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2462}
2463
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002464/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2465/// converts the given @c Object to a function pointer via the
2466/// conversion function @c Conversion, and then attempts to call it
2467/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2468/// the type of function that we'll eventually be calling.
2469void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002470 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002471 Expr *Object, Expr **Args, unsigned NumArgs,
2472 OverloadCandidateSet& CandidateSet) {
2473 CandidateSet.push_back(OverloadCandidate());
2474 OverloadCandidate& Candidate = CandidateSet.back();
2475 Candidate.Function = 0;
2476 Candidate.Surrogate = Conversion;
2477 Candidate.Viable = true;
2478 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002479 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002480 Candidate.Conversions.resize(NumArgs + 1);
2481
2482 // Determine the implicit conversion sequence for the implicit
2483 // object parameter.
2484 ImplicitConversionSequence ObjectInit
2485 = TryObjectArgumentInitialization(Object, Conversion);
2486 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2487 Candidate.Viable = false;
2488 return;
2489 }
2490
2491 // The first conversion is actually a user-defined conversion whose
2492 // first conversion is ObjectInit's standard conversion (which is
2493 // effectively a reference binding). Record it as such.
2494 Candidate.Conversions[0].ConversionKind
2495 = ImplicitConversionSequence::UserDefinedConversion;
2496 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2497 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2498 Candidate.Conversions[0].UserDefined.After
2499 = Candidate.Conversions[0].UserDefined.Before;
2500 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2501
2502 // Find the
2503 unsigned NumArgsInProto = Proto->getNumArgs();
2504
2505 // (C++ 13.3.2p2): A candidate function having fewer than m
2506 // parameters is viable only if it has an ellipsis in its parameter
2507 // list (8.3.5).
2508 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2509 Candidate.Viable = false;
2510 return;
2511 }
2512
2513 // Function types don't have any default arguments, so just check if
2514 // we have enough arguments.
2515 if (NumArgs < NumArgsInProto) {
2516 // Not enough arguments.
2517 Candidate.Viable = false;
2518 return;
2519 }
2520
2521 // Determine the implicit conversion sequences for each of the
2522 // arguments.
2523 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2524 if (ArgIdx < NumArgsInProto) {
2525 // (C++ 13.3.2p3): for F to be a viable function, there shall
2526 // exist for each argument an implicit conversion sequence
2527 // (13.3.3.1) that converts that argument to the corresponding
2528 // parameter of F.
2529 QualType ParamType = Proto->getArgType(ArgIdx);
2530 Candidate.Conversions[ArgIdx + 1]
2531 = TryCopyInitialization(Args[ArgIdx], ParamType,
2532 /*SuppressUserConversions=*/false);
2533 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2534 == ImplicitConversionSequence::BadConversion) {
2535 Candidate.Viable = false;
2536 break;
2537 }
2538 } else {
2539 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2540 // argument for which there is no corresponding parameter is
2541 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2542 Candidate.Conversions[ArgIdx + 1].ConversionKind
2543 = ImplicitConversionSequence::EllipsisConversion;
2544 }
2545 }
2546}
2547
Mike Stumpe127ae32009-05-16 07:39:55 +00002548// FIXME: This will eventually be removed, once we've migrated all of the
2549// operator overloading logic over to the scheme used by binary operators, which
2550// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002551void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002552 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002553 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002554 OverloadCandidateSet& CandidateSet,
2555 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002556
2557 FunctionSet Functions;
2558
2559 QualType T1 = Args[0]->getType();
2560 QualType T2;
2561 if (NumArgs > 1)
2562 T2 = Args[1]->getType();
2563
2564 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002565 if (S)
2566 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002567 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2568 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2569 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2570 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2571}
2572
2573/// \brief Add overload candidates for overloaded operators that are
2574/// member functions.
2575///
2576/// Add the overloaded operator candidates that are member functions
2577/// for the operator Op that was used in an operator expression such
2578/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2579/// CandidateSet will store the added overload candidates. (C++
2580/// [over.match.oper]).
2581void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2582 SourceLocation OpLoc,
2583 Expr **Args, unsigned NumArgs,
2584 OverloadCandidateSet& CandidateSet,
2585 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002586 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2587
2588 // C++ [over.match.oper]p3:
2589 // For a unary operator @ with an operand of a type whose
2590 // cv-unqualified version is T1, and for a binary operator @ with
2591 // a left operand of a type whose cv-unqualified version is T1 and
2592 // a right operand of a type whose cv-unqualified version is T2,
2593 // three sets of candidate functions, designated member
2594 // candidates, non-member candidates and built-in candidates, are
2595 // constructed as follows:
2596 QualType T1 = Args[0]->getType();
2597 QualType T2;
2598 if (NumArgs > 1)
2599 T2 = Args[1]->getType();
2600
2601 // -- If T1 is a class type, the set of member candidates is the
2602 // result of the qualified lookup of T1::operator@
2603 // (13.3.1.1.1); otherwise, the set of member candidates is
2604 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002605 // FIXME: Lookup in base classes, too!
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002606 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002607 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002608 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002609 Oper != OperEnd; ++Oper)
2610 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2611 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002612 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002613 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002614}
2615
Douglas Gregor70d26122008-11-12 17:17:38 +00002616/// AddBuiltinCandidate - Add a candidate for a built-in
2617/// operator. ResultTy and ParamTys are the result and parameter types
2618/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002619/// arguments being passed to the candidate. IsAssignmentOperator
2620/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002621/// operator. NumContextualBoolArguments is the number of arguments
2622/// (at the beginning of the argument list) that will be contextually
2623/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002624void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2625 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002626 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002627 bool IsAssignmentOperator,
2628 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002629 // Add this candidate
2630 CandidateSet.push_back(OverloadCandidate());
2631 OverloadCandidate& Candidate = CandidateSet.back();
2632 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002633 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002634 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002635 Candidate.BuiltinTypes.ResultTy = ResultTy;
2636 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2637 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2638
2639 // Determine the implicit conversion sequences for each of the
2640 // arguments.
2641 Candidate.Viable = true;
2642 Candidate.Conversions.resize(NumArgs);
2643 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002644 // C++ [over.match.oper]p4:
2645 // For the built-in assignment operators, conversions of the
2646 // left operand are restricted as follows:
2647 // -- no temporaries are introduced to hold the left operand, and
2648 // -- no user-defined conversions are applied to the left
2649 // operand to achieve a type match with the left-most
2650 // parameter of a built-in candidate.
2651 //
2652 // We block these conversions by turning off user-defined
2653 // conversions, since that is the only way that initialization of
2654 // a reference to a non-class type can occur from something that
2655 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002656 if (ArgIdx < NumContextualBoolArguments) {
2657 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2658 "Contextual conversion to bool requires bool type");
2659 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2660 } else {
2661 Candidate.Conversions[ArgIdx]
2662 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2663 ArgIdx == 0 && IsAssignmentOperator);
2664 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002665 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002666 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002667 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002668 break;
2669 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002670 }
2671}
2672
2673/// BuiltinCandidateTypeSet - A set of types that will be used for the
2674/// candidate operator functions for built-in operators (C++
2675/// [over.built]). The types are separated into pointer types and
2676/// enumeration types.
2677class BuiltinCandidateTypeSet {
2678 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002679 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002680
2681 /// PointerTypes - The set of pointer types that will be used in the
2682 /// built-in candidates.
2683 TypeSet PointerTypes;
2684
Sebastian Redl674d1b72009-04-19 21:53:20 +00002685 /// MemberPointerTypes - The set of member pointer types that will be
2686 /// used in the built-in candidates.
2687 TypeSet MemberPointerTypes;
2688
Douglas Gregor70d26122008-11-12 17:17:38 +00002689 /// EnumerationTypes - The set of enumeration types that will be
2690 /// used in the built-in candidates.
2691 TypeSet EnumerationTypes;
2692
2693 /// Context - The AST context in which we will build the type sets.
2694 ASTContext &Context;
2695
Sebastian Redl674d1b72009-04-19 21:53:20 +00002696 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2697 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002698
2699public:
2700 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002701 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002702
2703 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2704
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002705 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2706 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002707
2708 /// pointer_begin - First pointer type found;
2709 iterator pointer_begin() { return PointerTypes.begin(); }
2710
Sebastian Redl674d1b72009-04-19 21:53:20 +00002711 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002712 iterator pointer_end() { return PointerTypes.end(); }
2713
Sebastian Redl674d1b72009-04-19 21:53:20 +00002714 /// member_pointer_begin - First member pointer type found;
2715 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2716
2717 /// member_pointer_end - Past the last member pointer type found;
2718 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2719
Douglas Gregor70d26122008-11-12 17:17:38 +00002720 /// enumeration_begin - First enumeration type found;
2721 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2722
Sebastian Redl674d1b72009-04-19 21:53:20 +00002723 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002724 iterator enumeration_end() { return EnumerationTypes.end(); }
2725};
2726
Sebastian Redl674d1b72009-04-19 21:53:20 +00002727/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002728/// the set of pointer types along with any more-qualified variants of
2729/// that type. For example, if @p Ty is "int const *", this routine
2730/// will add "int const *", "int const volatile *", "int const
2731/// restrict *", and "int const volatile restrict *" to the set of
2732/// pointer types. Returns true if the add of @p Ty itself succeeded,
2733/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002734bool
2735BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002736 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002737 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002738 return false;
2739
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002740 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002741 QualType PointeeTy = PointerTy->getPointeeType();
2742 // FIXME: Optimize this so that we don't keep trying to add the same types.
2743
Mike Stumpe127ae32009-05-16 07:39:55 +00002744 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2745 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002746 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002747 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002748 (Context.getPointerType(PointeeTy.withConst()));
2749 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002750 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002751 (Context.getPointerType(PointeeTy.withVolatile()));
2752 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002753 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002754 (Context.getPointerType(PointeeTy.withRestrict()));
2755 }
2756
2757 return true;
2758}
2759
Sebastian Redl674d1b72009-04-19 21:53:20 +00002760/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2761/// to the set of pointer types along with any more-qualified variants of
2762/// that type. For example, if @p Ty is "int const *", this routine
2763/// will add "int const *", "int const volatile *", "int const
2764/// restrict *", and "int const volatile restrict *" to the set of
2765/// pointer types. Returns true if the add of @p Ty itself succeeded,
2766/// false otherwise.
2767bool
2768BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2769 QualType Ty) {
2770 // Insert this type.
2771 if (!MemberPointerTypes.insert(Ty))
2772 return false;
2773
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002774 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl674d1b72009-04-19 21:53:20 +00002775 QualType PointeeTy = PointerTy->getPointeeType();
2776 const Type *ClassTy = PointerTy->getClass();
2777 // FIXME: Optimize this so that we don't keep trying to add the same types.
2778
2779 if (!PointeeTy.isConstQualified())
2780 AddMemberPointerWithMoreQualifiedTypeVariants
2781 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2782 if (!PointeeTy.isVolatileQualified())
2783 AddMemberPointerWithMoreQualifiedTypeVariants
2784 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2785 if (!PointeeTy.isRestrictQualified())
2786 AddMemberPointerWithMoreQualifiedTypeVariants
2787 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2788 }
2789
2790 return true;
2791}
2792
Douglas Gregor70d26122008-11-12 17:17:38 +00002793/// AddTypesConvertedFrom - Add each of the types to which the type @p
2794/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002795/// primarily interested in pointer types and enumeration types. We also
2796/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002797/// AllowUserConversions is true if we should look at the conversion
2798/// functions of a class type, and AllowExplicitConversions if we
2799/// should also include the explicit conversion functions of a class
2800/// type.
2801void
2802BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2803 bool AllowUserConversions,
2804 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002805 // Only deal with canonical types.
2806 Ty = Context.getCanonicalType(Ty);
2807
2808 // Look through reference types; they aren't part of the type of an
2809 // expression for the purposes of conversions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002810 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregor70d26122008-11-12 17:17:38 +00002811 Ty = RefTy->getPointeeType();
2812
2813 // We don't care about qualifiers on the type.
2814 Ty = Ty.getUnqualifiedType();
2815
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002816 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002817 QualType PointeeTy = PointerTy->getPointeeType();
2818
2819 // Insert our type, and its more-qualified variants, into the set
2820 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002821 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002822 return;
2823
2824 // Add 'cv void*' to our set of types.
2825 if (!Ty->isVoidType()) {
2826 QualType QualVoid
2827 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002828 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002829 }
2830
2831 // If this is a pointer to a class type, add pointers to its bases
2832 // (with the same level of cv-qualification as the original
2833 // derived class, of course).
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002834 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002835 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2836 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2837 Base != ClassDecl->bases_end(); ++Base) {
2838 QualType BaseTy = Context.getCanonicalType(Base->getType());
2839 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2840
2841 // Add the pointer type, recursively, so that we get all of
2842 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002843 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002844 }
2845 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002846 } else if (Ty->isMemberPointerType()) {
2847 // Member pointers are far easier, since the pointee can't be converted.
2848 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2849 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002850 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002851 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002852 } else if (AllowUserConversions) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002853 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002854 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2855 // FIXME: Visit conversion functions in the base classes, too.
2856 OverloadedFunctionDecl *Conversions
2857 = ClassDecl->getConversionFunctions();
2858 for (OverloadedFunctionDecl::function_iterator Func
2859 = Conversions->function_begin();
2860 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002861 CXXConversionDecl *Conv;
2862 FunctionTemplateDecl *ConvTemplate;
2863 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2864
2865 // Skip conversion function templates; they don't tell us anything
2866 // about which builtin types we can convert to.
2867 if (ConvTemplate)
2868 continue;
2869
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002870 if (AllowExplicitConversions || !Conv->isExplicit())
2871 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002872 }
2873 }
2874 }
2875}
2876
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002877/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2878/// operator overloads to the candidate set (C++ [over.built]), based
2879/// on the operator @p Op and the arguments given. For example, if the
2880/// operator is a binary '+', this routine might add "int
2881/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002882void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002883Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2884 Expr **Args, unsigned NumArgs,
2885 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002886 // The set of "promoted arithmetic types", which are the arithmetic
2887 // types are that preserved by promotion (C++ [over.built]p2). Note
2888 // that the first few of these types are the promoted integral
2889 // types; these types need to be first.
2890 // FIXME: What about complex?
2891 const unsigned FirstIntegralType = 0;
2892 const unsigned LastIntegralType = 13;
2893 const unsigned FirstPromotedIntegralType = 7,
2894 LastPromotedIntegralType = 13;
2895 const unsigned FirstPromotedArithmeticType = 7,
2896 LastPromotedArithmeticType = 16;
2897 const unsigned NumArithmeticTypes = 16;
2898 QualType ArithmeticTypes[NumArithmeticTypes] = {
Alisdair Meredith2bcacb62009-07-14 06:30:34 +00002899 Context.BoolTy, Context.CharTy, Context.WCharTy,
2900// Context.Char16Ty, Context.Char32Ty,
Douglas Gregor70d26122008-11-12 17:17:38 +00002901 Context.SignedCharTy, Context.ShortTy,
2902 Context.UnsignedCharTy, Context.UnsignedShortTy,
2903 Context.IntTy, Context.LongTy, Context.LongLongTy,
2904 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2905 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2906 };
2907
2908 // Find all of the types that the arguments can convert to, but only
2909 // if the operator we're looking at has built-in operator candidates
2910 // that make use of these types.
2911 BuiltinCandidateTypeSet CandidateTypes(Context);
2912 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2913 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002914 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002915 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002916 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00002917 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002918 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002919 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2920 true,
2921 (Op == OO_Exclaim ||
2922 Op == OO_AmpAmp ||
2923 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002924 }
2925
2926 bool isComparison = false;
2927 switch (Op) {
2928 case OO_None:
2929 case NUM_OVERLOADED_OPERATORS:
2930 assert(false && "Expected an overloaded operator");
2931 break;
2932
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002933 case OO_Star: // '*' is either unary or binary
2934 if (NumArgs == 1)
2935 goto UnaryStar;
2936 else
2937 goto BinaryStar;
2938 break;
2939
2940 case OO_Plus: // '+' is either unary or binary
2941 if (NumArgs == 1)
2942 goto UnaryPlus;
2943 else
2944 goto BinaryPlus;
2945 break;
2946
2947 case OO_Minus: // '-' is either unary or binary
2948 if (NumArgs == 1)
2949 goto UnaryMinus;
2950 else
2951 goto BinaryMinus;
2952 break;
2953
2954 case OO_Amp: // '&' is either unary or binary
2955 if (NumArgs == 1)
2956 goto UnaryAmp;
2957 else
2958 goto BinaryAmp;
2959
2960 case OO_PlusPlus:
2961 case OO_MinusMinus:
2962 // C++ [over.built]p3:
2963 //
2964 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2965 // is either volatile or empty, there exist candidate operator
2966 // functions of the form
2967 //
2968 // VQ T& operator++(VQ T&);
2969 // T operator++(VQ T&, int);
2970 //
2971 // C++ [over.built]p4:
2972 //
2973 // For every pair (T, VQ), where T is an arithmetic type other
2974 // than bool, and VQ is either volatile or empty, there exist
2975 // candidate operator functions of the form
2976 //
2977 // VQ T& operator--(VQ T&);
2978 // T operator--(VQ T&, int);
2979 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2980 Arith < NumArithmeticTypes; ++Arith) {
2981 QualType ArithTy = ArithmeticTypes[Arith];
2982 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00002983 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002984
2985 // Non-volatile version.
2986 if (NumArgs == 1)
2987 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2988 else
2989 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2990
2991 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00002992 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002993 if (NumArgs == 1)
2994 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2995 else
2996 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2997 }
2998
2999 // C++ [over.built]p5:
3000 //
3001 // For every pair (T, VQ), where T is a cv-qualified or
3002 // cv-unqualified object type, and VQ is either volatile or
3003 // empty, there exist candidate operator functions of the form
3004 //
3005 // T*VQ& operator++(T*VQ&);
3006 // T*VQ& operator--(T*VQ&);
3007 // T* operator++(T*VQ&, int);
3008 // T* operator--(T*VQ&, int);
3009 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3010 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3011 // Skip pointer types that aren't pointers to object types.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003012 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003013 continue;
3014
3015 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003016 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003017 };
3018
3019 // Without volatile
3020 if (NumArgs == 1)
3021 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3022 else
3023 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3024
3025 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3026 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00003027 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003028 if (NumArgs == 1)
3029 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3030 else
3031 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3032 }
3033 }
3034 break;
3035
3036 UnaryStar:
3037 // C++ [over.built]p6:
3038 // For every cv-qualified or cv-unqualified object type T, there
3039 // exist candidate operator functions of the form
3040 //
3041 // T& operator*(T*);
3042 //
3043 // C++ [over.built]p7:
3044 // For every function type T, there exist candidate operator
3045 // functions of the form
3046 // T& operator*(T*);
3047 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3048 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3049 QualType ParamTy = *Ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003050 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003051 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003052 &ParamTy, Args, 1, CandidateSet);
3053 }
3054 break;
3055
3056 UnaryPlus:
3057 // C++ [over.built]p8:
3058 // For every type T, there exist candidate operator functions of
3059 // the form
3060 //
3061 // T* operator+(T*);
3062 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3063 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3064 QualType ParamTy = *Ptr;
3065 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3066 }
3067
3068 // Fall through
3069
3070 UnaryMinus:
3071 // C++ [over.built]p9:
3072 // For every promoted arithmetic type T, there exist candidate
3073 // operator functions of the form
3074 //
3075 // T operator+(T);
3076 // T operator-(T);
3077 for (unsigned Arith = FirstPromotedArithmeticType;
3078 Arith < LastPromotedArithmeticType; ++Arith) {
3079 QualType ArithTy = ArithmeticTypes[Arith];
3080 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3081 }
3082 break;
3083
3084 case OO_Tilde:
3085 // C++ [over.built]p10:
3086 // For every promoted integral type T, there exist candidate
3087 // operator functions of the form
3088 //
3089 // T operator~(T);
3090 for (unsigned Int = FirstPromotedIntegralType;
3091 Int < LastPromotedIntegralType; ++Int) {
3092 QualType IntTy = ArithmeticTypes[Int];
3093 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3094 }
3095 break;
3096
Douglas Gregor70d26122008-11-12 17:17:38 +00003097 case OO_New:
3098 case OO_Delete:
3099 case OO_Array_New:
3100 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00003101 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003102 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00003103 break;
3104
3105 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003106 UnaryAmp:
3107 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00003108 // C++ [over.match.oper]p3:
3109 // -- For the operator ',', the unary operator '&', or the
3110 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00003111 break;
3112
3113 case OO_Less:
3114 case OO_Greater:
3115 case OO_LessEqual:
3116 case OO_GreaterEqual:
3117 case OO_EqualEqual:
3118 case OO_ExclaimEqual:
3119 // C++ [over.built]p15:
3120 //
3121 // For every pointer or enumeration type T, there exist
3122 // candidate operator functions of the form
3123 //
3124 // bool operator<(T, T);
3125 // bool operator>(T, T);
3126 // bool operator<=(T, T);
3127 // bool operator>=(T, T);
3128 // bool operator==(T, T);
3129 // bool operator!=(T, T);
3130 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3131 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3132 QualType ParamTypes[2] = { *Ptr, *Ptr };
3133 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3134 }
3135 for (BuiltinCandidateTypeSet::iterator Enum
3136 = CandidateTypes.enumeration_begin();
3137 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3138 QualType ParamTypes[2] = { *Enum, *Enum };
3139 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3140 }
3141
3142 // Fall through.
3143 isComparison = true;
3144
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003145 BinaryPlus:
3146 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003147 if (!isComparison) {
3148 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3149
3150 // C++ [over.built]p13:
3151 //
3152 // For every cv-qualified or cv-unqualified object type T
3153 // there exist candidate operator functions of the form
3154 //
3155 // T* operator+(T*, ptrdiff_t);
3156 // T& operator[](T*, ptrdiff_t); [BELOW]
3157 // T* operator-(T*, ptrdiff_t);
3158 // T* operator+(ptrdiff_t, T*);
3159 // T& operator[](ptrdiff_t, T*); [BELOW]
3160 //
3161 // C++ [over.built]p14:
3162 //
3163 // For every T, where T is a pointer to object type, there
3164 // exist candidate operator functions of the form
3165 //
3166 // ptrdiff_t operator-(T, T);
3167 for (BuiltinCandidateTypeSet::iterator Ptr
3168 = CandidateTypes.pointer_begin();
3169 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3170 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3171
3172 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3173 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3174
3175 if (Op == OO_Plus) {
3176 // T* operator+(ptrdiff_t, T*);
3177 ParamTypes[0] = ParamTypes[1];
3178 ParamTypes[1] = *Ptr;
3179 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3180 } else {
3181 // ptrdiff_t operator-(T, T);
3182 ParamTypes[1] = *Ptr;
3183 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3184 Args, 2, CandidateSet);
3185 }
3186 }
3187 }
3188 // Fall through
3189
Douglas Gregor70d26122008-11-12 17:17:38 +00003190 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003191 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003192 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003193 // C++ [over.built]p12:
3194 //
3195 // For every pair of promoted arithmetic types L and R, there
3196 // exist candidate operator functions of the form
3197 //
3198 // LR operator*(L, R);
3199 // LR operator/(L, R);
3200 // LR operator+(L, R);
3201 // LR operator-(L, R);
3202 // bool operator<(L, R);
3203 // bool operator>(L, R);
3204 // bool operator<=(L, R);
3205 // bool operator>=(L, R);
3206 // bool operator==(L, R);
3207 // bool operator!=(L, R);
3208 //
3209 // where LR is the result of the usual arithmetic conversions
3210 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003211 //
3212 // C++ [over.built]p24:
3213 //
3214 // For every pair of promoted arithmetic types L and R, there exist
3215 // candidate operator functions of the form
3216 //
3217 // LR operator?(bool, L, R);
3218 //
3219 // where LR is the result of the usual arithmetic conversions
3220 // between types L and R.
3221 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003222 for (unsigned Left = FirstPromotedArithmeticType;
3223 Left < LastPromotedArithmeticType; ++Left) {
3224 for (unsigned Right = FirstPromotedArithmeticType;
3225 Right < LastPromotedArithmeticType; ++Right) {
3226 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman6ae7d112009-08-19 07:44:53 +00003227 QualType Result
3228 = isComparison
3229 ? Context.BoolTy
3230 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003231 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3232 }
3233 }
3234 break;
3235
3236 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003237 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003238 case OO_Caret:
3239 case OO_Pipe:
3240 case OO_LessLess:
3241 case OO_GreaterGreater:
3242 // C++ [over.built]p17:
3243 //
3244 // For every pair of promoted integral types L and R, there
3245 // exist candidate operator functions of the form
3246 //
3247 // LR operator%(L, R);
3248 // LR operator&(L, R);
3249 // LR operator^(L, R);
3250 // LR operator|(L, R);
3251 // L operator<<(L, R);
3252 // L operator>>(L, R);
3253 //
3254 // where LR is the result of the usual arithmetic conversions
3255 // between types L and R.
3256 for (unsigned Left = FirstPromotedIntegralType;
3257 Left < LastPromotedIntegralType; ++Left) {
3258 for (unsigned Right = FirstPromotedIntegralType;
3259 Right < LastPromotedIntegralType; ++Right) {
3260 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3261 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3262 ? LandR[0]
Eli Friedman6ae7d112009-08-19 07:44:53 +00003263 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003264 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3265 }
3266 }
3267 break;
3268
3269 case OO_Equal:
3270 // C++ [over.built]p20:
3271 //
3272 // For every pair (T, VQ), where T is an enumeration or
3273 // (FIXME:) pointer to member type and VQ is either volatile or
3274 // empty, there exist candidate operator functions of the form
3275 //
3276 // VQ T& operator=(VQ T&, T);
3277 for (BuiltinCandidateTypeSet::iterator Enum
3278 = CandidateTypes.enumeration_begin();
3279 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3280 QualType ParamTypes[2];
3281
3282 // T& operator=(T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003283 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregor70d26122008-11-12 17:17:38 +00003284 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003285 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003286 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003287
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003288 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3289 // volatile T& operator=(volatile T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003290 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003291 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003292 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003293 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003294 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003295 }
3296 // Fall through.
3297
3298 case OO_PlusEqual:
3299 case OO_MinusEqual:
3300 // C++ [over.built]p19:
3301 //
3302 // For every pair (T, VQ), where T is any type and VQ is either
3303 // volatile or empty, there exist candidate operator functions
3304 // of the form
3305 //
3306 // T*VQ& operator=(T*VQ&, T*);
3307 //
3308 // C++ [over.built]p21:
3309 //
3310 // For every pair (T, VQ), where T is a cv-qualified or
3311 // cv-unqualified object type and VQ is either volatile or
3312 // empty, there exist candidate operator functions of the form
3313 //
3314 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3315 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3316 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3317 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3318 QualType ParamTypes[2];
3319 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3320
3321 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003322 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003323 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3324 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003325
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003326 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3327 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003328 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003329 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3330 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003331 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003332 }
3333 // Fall through.
3334
3335 case OO_StarEqual:
3336 case OO_SlashEqual:
3337 // C++ [over.built]p18:
3338 //
3339 // For every triple (L, VQ, R), where L is an arithmetic type,
3340 // VQ is either volatile or empty, and R is a promoted
3341 // arithmetic type, there exist candidate operator functions of
3342 // the form
3343 //
3344 // VQ L& operator=(VQ L&, R);
3345 // VQ L& operator*=(VQ L&, R);
3346 // VQ L& operator/=(VQ L&, R);
3347 // VQ L& operator+=(VQ L&, R);
3348 // VQ L& operator-=(VQ L&, R);
3349 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3350 for (unsigned Right = FirstPromotedArithmeticType;
3351 Right < LastPromotedArithmeticType; ++Right) {
3352 QualType ParamTypes[2];
3353 ParamTypes[1] = ArithmeticTypes[Right];
3354
3355 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003356 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003357 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3358 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003359
3360 // Add this built-in operator as a candidate (VQ is 'volatile').
3361 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003362 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003363 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3364 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003365 }
3366 }
3367 break;
3368
3369 case OO_PercentEqual:
3370 case OO_LessLessEqual:
3371 case OO_GreaterGreaterEqual:
3372 case OO_AmpEqual:
3373 case OO_CaretEqual:
3374 case OO_PipeEqual:
3375 // C++ [over.built]p22:
3376 //
3377 // For every triple (L, VQ, R), where L is an integral type, VQ
3378 // is either volatile or empty, and R is a promoted integral
3379 // type, there exist candidate operator functions of the form
3380 //
3381 // VQ L& operator%=(VQ L&, R);
3382 // VQ L& operator<<=(VQ L&, R);
3383 // VQ L& operator>>=(VQ L&, R);
3384 // VQ L& operator&=(VQ L&, R);
3385 // VQ L& operator^=(VQ L&, R);
3386 // VQ L& operator|=(VQ L&, R);
3387 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3388 for (unsigned Right = FirstPromotedIntegralType;
3389 Right < LastPromotedIntegralType; ++Right) {
3390 QualType ParamTypes[2];
3391 ParamTypes[1] = ArithmeticTypes[Right];
3392
3393 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003394 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003395 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3396
3397 // Add this built-in operator as a candidate (VQ is 'volatile').
3398 ParamTypes[0] = ArithmeticTypes[Left];
3399 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003400 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003401 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3402 }
3403 }
3404 break;
3405
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003406 case OO_Exclaim: {
3407 // C++ [over.operator]p23:
3408 //
3409 // There also exist candidate operator functions of the form
3410 //
3411 // bool operator!(bool);
3412 // bool operator&&(bool, bool); [BELOW]
3413 // bool operator||(bool, bool); [BELOW]
3414 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003415 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3416 /*IsAssignmentOperator=*/false,
3417 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003418 break;
3419 }
3420
Douglas Gregor70d26122008-11-12 17:17:38 +00003421 case OO_AmpAmp:
3422 case OO_PipePipe: {
3423 // C++ [over.operator]p23:
3424 //
3425 // There also exist candidate operator functions of the form
3426 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003427 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003428 // bool operator&&(bool, bool);
3429 // bool operator||(bool, bool);
3430 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003431 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3432 /*IsAssignmentOperator=*/false,
3433 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003434 break;
3435 }
3436
3437 case OO_Subscript:
3438 // C++ [over.built]p13:
3439 //
3440 // For every cv-qualified or cv-unqualified object type T there
3441 // exist candidate operator functions of the form
3442 //
3443 // T* operator+(T*, ptrdiff_t); [ABOVE]
3444 // T& operator[](T*, ptrdiff_t);
3445 // T* operator-(T*, ptrdiff_t); [ABOVE]
3446 // T* operator+(ptrdiff_t, T*); [ABOVE]
3447 // T& operator[](ptrdiff_t, T*);
3448 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3449 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3450 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003451 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003452 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003453
3454 // T& operator[](T*, ptrdiff_t)
3455 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3456
3457 // T& operator[](ptrdiff_t, T*);
3458 ParamTypes[0] = ParamTypes[1];
3459 ParamTypes[1] = *Ptr;
3460 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3461 }
3462 break;
3463
3464 case OO_ArrowStar:
3465 // FIXME: No support for pointer-to-members yet.
3466 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003467
3468 case OO_Conditional:
3469 // Note that we don't consider the first argument, since it has been
3470 // contextually converted to bool long ago. The candidates below are
3471 // therefore added as binary.
3472 //
3473 // C++ [over.built]p24:
3474 // For every type T, where T is a pointer or pointer-to-member type,
3475 // there exist candidate operator functions of the form
3476 //
3477 // T operator?(bool, T, T);
3478 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003479 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3480 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3481 QualType ParamTypes[2] = { *Ptr, *Ptr };
3482 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3483 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003484 for (BuiltinCandidateTypeSet::iterator Ptr =
3485 CandidateTypes.member_pointer_begin(),
3486 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3487 QualType ParamTypes[2] = { *Ptr, *Ptr };
3488 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3489 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003490 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003491 }
3492}
3493
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003494/// \brief Add function candidates found via argument-dependent lookup
3495/// to the set of overloading candidates.
3496///
3497/// This routine performs argument-dependent name lookup based on the
3498/// given function name (which may also be an operator name) and adds
3499/// all of the overload candidates found by ADL to the overload
3500/// candidate set (C++ [basic.lookup.argdep]).
3501void
3502Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3503 Expr **Args, unsigned NumArgs,
3504 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003505 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003506
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003507 // Record all of the function candidates that we've already
3508 // added to the overload set, so that we don't add those same
3509 // candidates a second time.
3510 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3511 CandEnd = CandidateSet.end();
3512 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003513 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003514 Functions.insert(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003515 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3516 Functions.insert(FunTmpl);
3517 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003518
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003519 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003520
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003521 // Erase all of the candidates we already knew about.
3522 // FIXME: This is suboptimal. Is there a better way?
3523 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3524 CandEnd = CandidateSet.end();
3525 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003526 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003527 Functions.erase(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003528 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3529 Functions.erase(FunTmpl);
3530 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003531
3532 // For each of the ADL candidates we found, add it to the overload
3533 // set.
3534 for (FunctionSet::iterator Func = Functions.begin(),
3535 FuncEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00003536 Func != FuncEnd; ++Func) {
3537 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3538 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3539 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003540 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3541 /*FIXME: explicit args */false, 0, 0,
3542 Args, NumArgs, CandidateSet);
Douglas Gregor993a0602009-06-27 21:05:07 +00003543 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003544}
3545
Douglas Gregord2baafd2008-10-21 16:13:35 +00003546/// isBetterOverloadCandidate - Determines whether the first overload
3547/// candidate is a better candidate than the second (C++ 13.3.3p1).
3548bool
3549Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3550 const OverloadCandidate& Cand2)
3551{
3552 // Define viable functions to be better candidates than non-viable
3553 // functions.
3554 if (!Cand2.Viable)
3555 return Cand1.Viable;
3556 else if (!Cand1.Viable)
3557 return false;
3558
Douglas Gregor3257fb52008-12-22 05:46:06 +00003559 // C++ [over.match.best]p1:
3560 //
3561 // -- if F is a static member function, ICS1(F) is defined such
3562 // that ICS1(F) is neither better nor worse than ICS1(G) for
3563 // any function G, and, symmetrically, ICS1(G) is neither
3564 // better nor worse than ICS1(F).
3565 unsigned StartArg = 0;
3566 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3567 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003568
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003569 // C++ [over.match.best]p1:
3570 // A viable function F1 is defined to be a better function than another
3571 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3572 // conversion sequence than ICSi(F2), and then...
Douglas Gregord2baafd2008-10-21 16:13:35 +00003573 unsigned NumArgs = Cand1.Conversions.size();
3574 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3575 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003576 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003577 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3578 Cand2.Conversions[ArgIdx])) {
3579 case ImplicitConversionSequence::Better:
3580 // Cand1 has a better conversion sequence.
3581 HasBetterConversion = true;
3582 break;
3583
3584 case ImplicitConversionSequence::Worse:
3585 // Cand1 can't be better than Cand2.
3586 return false;
3587
3588 case ImplicitConversionSequence::Indistinguishable:
3589 // Do nothing.
3590 break;
3591 }
3592 }
3593
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003594 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3595 // ICSj(F2), or, if not that,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003596 if (HasBetterConversion)
3597 return true;
3598
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003599 // - F1 is a non-template function and F2 is a function template
3600 // specialization, or, if not that,
3601 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3602 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3603 return true;
3604
3605 // -- F1 and F2 are function template specializations, and the function
3606 // template for F1 is more specialized than the template for F2
3607 // according to the partial ordering rules described in 14.5.5.2, or,
3608 // if not that,
Douglas Gregorf8e51672009-08-02 23:46:29 +00003609 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3610 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor8c860df2009-08-21 23:19:43 +00003611 if (FunctionTemplateDecl *BetterTemplate
3612 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3613 Cand2.Function->getPrimaryTemplate(),
3614 true))
3615 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003616
Douglas Gregor60714f92008-11-07 22:36:19 +00003617 // -- the context is an initialization by user-defined conversion
3618 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3619 // from the return type of F1 to the destination type (i.e.,
3620 // the type of the entity being initialized) is a better
3621 // conversion sequence than the standard conversion sequence
3622 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003623 if (Cand1.Function && Cand2.Function &&
3624 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003625 isa<CXXConversionDecl>(Cand2.Function)) {
3626 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3627 Cand2.FinalConversion)) {
3628 case ImplicitConversionSequence::Better:
3629 // Cand1 has a better conversion sequence.
3630 return true;
3631
3632 case ImplicitConversionSequence::Worse:
3633 // Cand1 can't be better than Cand2.
3634 return false;
3635
3636 case ImplicitConversionSequence::Indistinguishable:
3637 // Do nothing
3638 break;
3639 }
3640 }
3641
Douglas Gregord2baafd2008-10-21 16:13:35 +00003642 return false;
3643}
3644
Douglas Gregor98189262009-06-19 23:52:42 +00003645/// \brief Computes the best viable function (C++ 13.3.3)
3646/// within an overload candidate set.
3647///
3648/// \param CandidateSet the set of candidate functions.
3649///
3650/// \param Loc the location of the function name (or operator symbol) for
3651/// which overload resolution occurs.
3652///
3653/// \param Best f overload resolution was successful or found a deleted
3654/// function, Best points to the candidate function found.
3655///
3656/// \returns The result of overload resolution.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003657Sema::OverloadingResult
3658Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003659 SourceLocation Loc,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003660 OverloadCandidateSet::iterator& Best)
3661{
3662 // Find the best viable function.
3663 Best = CandidateSet.end();
3664 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3665 Cand != CandidateSet.end(); ++Cand) {
3666 if (Cand->Viable) {
3667 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3668 Best = Cand;
3669 }
3670 }
3671
3672 // If we didn't find any viable functions, abort.
3673 if (Best == CandidateSet.end())
3674 return OR_No_Viable_Function;
3675
3676 // Make sure that this function is better than every other viable
3677 // function. If not, we have an ambiguity.
3678 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3679 Cand != CandidateSet.end(); ++Cand) {
3680 if (Cand->Viable &&
3681 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003682 !isBetterOverloadCandidate(*Best, *Cand)) {
3683 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003684 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003685 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003686 }
3687
3688 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003689 if (Best->Function &&
3690 (Best->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003691 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003692 return OR_Deleted;
3693
Douglas Gregor98189262009-06-19 23:52:42 +00003694 // C++ [basic.def.odr]p2:
3695 // An overloaded function is used if it is selected by overload resolution
3696 // when referred to from a potentially-evaluated expression. [Note: this
3697 // covers calls to named functions (5.2.2), operator overloading
3698 // (clause 13), user-defined conversions (12.3.2), allocation function for
3699 // placement new (5.3.4), as well as non-default initialization (8.5).
3700 if (Best->Function)
3701 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003702 return OR_Success;
3703}
3704
3705/// PrintOverloadCandidates - When overload resolution fails, prints
3706/// diagnostic messages containing the candidates in the candidate
3707/// set. If OnlyViable is true, only viable candidates will be printed.
3708void
3709Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3710 bool OnlyViable)
3711{
3712 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3713 LastCand = CandidateSet.end();
3714 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003715 if (Cand->Viable || !OnlyViable) {
3716 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003717 if (Cand->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003718 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003719 // Deleted or "unavailable" function.
3720 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3721 << Cand->Function->isDeleted();
3722 } else {
3723 // Normal function
3724 // FIXME: Give a better reason!
3725 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3726 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003727 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003728 // Desugar the type of the surrogate down to a function type,
3729 // retaining as many typedefs as possible while still showing
3730 // the function type (and, therefore, its parameter types).
3731 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003732 bool isLValueReference = false;
3733 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003734 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003735 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003736 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003737 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003738 isLValueReference = true;
3739 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003740 FnType->getAs<RValueReferenceType>()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003741 FnType = FnTypeRef->getPointeeType();
3742 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003743 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003744 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003745 FnType = FnTypePtr->getPointeeType();
3746 isPointer = true;
3747 }
3748 // Desugar down to a function type.
3749 FnType = QualType(FnType->getAsFunctionType(), 0);
3750 // Reconstruct the pointer/reference as appropriate.
3751 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003752 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3753 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003754
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003755 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003756 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003757 } else {
3758 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003759 // FIXME: Do we want the error message to point at the operator?
3760 // (built-ins won't have a location)
Douglas Gregor70d26122008-11-12 17:17:38 +00003761 QualType FnType
3762 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3763 Cand->BuiltinTypes.ParamTypes,
3764 Cand->Conversions.size(),
3765 false, 0);
3766
Chris Lattner4bfd2232008-11-24 06:25:27 +00003767 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003768 }
3769 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003770 }
3771}
3772
Douglas Gregor45014fd2008-11-10 20:40:00 +00003773/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3774/// an overloaded function (C++ [over.over]), where @p From is an
3775/// expression with overloaded function type and @p ToType is the type
3776/// we're trying to resolve to. For example:
3777///
3778/// @code
3779/// int f(double);
3780/// int f(int);
3781///
3782/// int (*pfd)(double) = f; // selects f(double)
3783/// @endcode
3784///
3785/// This routine returns the resulting FunctionDecl if it could be
3786/// resolved, and NULL otherwise. When @p Complain is true, this
3787/// routine will emit diagnostics if there is an error.
3788FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003789Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003790 bool Complain) {
3791 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003792 bool IsMember = false;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003793 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003794 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003795 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003796 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003797 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003798 ToType->getAs<MemberPointerType>()) {
Sebastian Redl7434fc32009-02-04 21:23:32 +00003799 FunctionType = MemTypePtr->getPointeeType();
3800 IsMember = true;
3801 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003802
3803 // We only look at pointers or references to functions.
Douglas Gregor72bb4992009-07-09 17:16:51 +00003804 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor62f78762009-07-08 20:55:45 +00003805 if (!FunctionType->isFunctionType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003806 return 0;
3807
3808 // Find the actual overloaded function declaration.
3809 OverloadedFunctionDecl *Ovl = 0;
3810
3811 // C++ [over.over]p1:
3812 // [...] [Note: any redundant set of parentheses surrounding the
3813 // overloaded function name is ignored (5.1). ]
3814 Expr *OvlExpr = From->IgnoreParens();
3815
3816 // C++ [over.over]p1:
3817 // [...] The overloaded function name can be preceded by the &
3818 // operator.
3819 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3820 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3821 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3822 }
3823
3824 // Try to dig out the overloaded function.
Douglas Gregor62f78762009-07-08 20:55:45 +00003825 FunctionTemplateDecl *FunctionTemplate = 0;
3826 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003827 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor62f78762009-07-08 20:55:45 +00003828 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3829 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003830
Douglas Gregor62f78762009-07-08 20:55:45 +00003831 // If there's no overloaded function declaration or function template,
3832 // we're done.
3833 if (!Ovl && !FunctionTemplate)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003834 return 0;
3835
Douglas Gregor62f78762009-07-08 20:55:45 +00003836 OverloadIterator Fun;
3837 if (Ovl)
3838 Fun = Ovl;
3839 else
3840 Fun = FunctionTemplate;
3841
Douglas Gregor45014fd2008-11-10 20:40:00 +00003842 // Look through all of the overloaded functions, searching for one
3843 // whose type matches exactly.
Douglas Gregora142a052009-07-08 23:33:52 +00003844 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3845
3846 bool FoundNonTemplateFunction = false;
Douglas Gregor62f78762009-07-08 20:55:45 +00003847 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003848 // C++ [over.over]p3:
3849 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003850 // targets of type "pointer-to-function" or "reference-to-function."
3851 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003852 // type "pointer-to-member-function."
3853 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor62f78762009-07-08 20:55:45 +00003854
3855 if (FunctionTemplateDecl *FunctionTemplate
3856 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003857 if (CXXMethodDecl *Method
3858 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3859 // Skip non-static function templates when converting to pointer, and
3860 // static when converting to member pointer.
3861 if (Method->isStatic() == IsMember)
3862 continue;
3863 } else if (IsMember)
3864 continue;
3865
3866 // C++ [over.over]p2:
3867 // If the name is a function template, template argument deduction is
3868 // done (14.8.2.2), and if the argument deduction succeeds, the
3869 // resulting template argument list is used to generate a single
3870 // function template specialization, which is added to the set of
3871 // overloaded functions considered.
Douglas Gregor62f78762009-07-08 20:55:45 +00003872 FunctionDecl *Specialization = 0;
3873 TemplateDeductionInfo Info(Context);
3874 if (TemplateDeductionResult Result
3875 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3876 /*FIXME:*/0, /*FIXME:*/0,
3877 FunctionType, Specialization, Info)) {
3878 // FIXME: make a note of the failed deduction for diagnostics.
3879 (void)Result;
3880 } else {
3881 assert(FunctionType
3882 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregora142a052009-07-08 23:33:52 +00003883 Matches.insert(
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003884 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor62f78762009-07-08 20:55:45 +00003885 }
3886 }
3887
Sebastian Redl7434fc32009-02-04 21:23:32 +00003888 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3889 // Skip non-static functions when converting to pointer, and static
3890 // when converting to member pointer.
3891 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003892 continue;
Douglas Gregora142a052009-07-08 23:33:52 +00003893 } else if (IsMember)
Sebastian Redl7434fc32009-02-04 21:23:32 +00003894 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003895
Douglas Gregorb60eb752009-06-25 22:08:12 +00003896 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003897 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003898 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregora142a052009-07-08 23:33:52 +00003899 FoundNonTemplateFunction = true;
3900 }
Douglas Gregor62f78762009-07-08 20:55:45 +00003901 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003902 }
3903
Douglas Gregora142a052009-07-08 23:33:52 +00003904 // If there were 0 or 1 matches, we're done.
3905 if (Matches.empty())
3906 return 0;
3907 else if (Matches.size() == 1)
3908 return *Matches.begin();
3909
3910 // C++ [over.over]p4:
3911 // If more than one function is selected, [...]
3912 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor8c860df2009-08-21 23:19:43 +00003913 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregora142a052009-07-08 23:33:52 +00003914 if (FoundNonTemplateFunction) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003915 // [...] any function template specializations in the set are
3916 // eliminated if the set also contains a non-template function, [...]
3917 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregora142a052009-07-08 23:33:52 +00003918 if ((*M)->getPrimaryTemplate() == 0)
3919 RemainingMatches.push_back(*M);
3920 } else {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003921 // [...] and any given function template specialization F1 is
3922 // eliminated if the set contains a second function template
3923 // specialization whose function template is more specialized
3924 // than the function template of F1 according to the partial
3925 // ordering rules of 14.5.5.2.
3926
3927 // The algorithm specified above is quadratic. We instead use a
3928 // two-pass algorithm (similar to the one used to identify the
3929 // best viable function in an overload set) that identifies the
3930 // best function template (if it exists).
3931 MatchIter Best = Matches.begin();
3932 MatchIter M = Best, MEnd = Matches.end();
3933 // Find the most specialized function.
3934 for (++M; M != MEnd; ++M)
3935 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
3936 (*Best)->getPrimaryTemplate(),
3937 false)
3938 == (*M)->getPrimaryTemplate())
3939 Best = M;
3940
3941 // Determine whether this function template is more specialized
3942 // that all of the others.
3943 bool Ambiguous = false;
3944 for (M = Matches.begin(); M != MEnd; ++M) {
3945 if (M != Best &&
3946 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
3947 (*Best)->getPrimaryTemplate(),
3948 false)
3949 != (*Best)->getPrimaryTemplate()) {
3950 Ambiguous = true;
3951 break;
3952 }
3953 }
3954
3955 // If one function template was more specialized than all of the
3956 // others, return it.
3957 if (!Ambiguous)
3958 return *Best;
3959
3960 // We could not find a most-specialized function template, which
3961 // is equivalent to having a set of function templates with more
3962 // than one such template. So, we place all of the function
3963 // templates into the set of remaining matches and produce a
3964 // diagnostic below. FIXME: we could perform the quadratic
3965 // algorithm here, pruning the result set to limit the number of
3966 // candidates output later.
3967 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregora142a052009-07-08 23:33:52 +00003968 }
3969
3970 // [...] After such eliminations, if any, there shall remain exactly one
3971 // selected function.
3972 if (RemainingMatches.size() == 1)
3973 return RemainingMatches.front();
3974
3975 // FIXME: We should probably return the same thing that BestViableFunction
3976 // returns (even if we issue the diagnostics here).
3977 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
3978 << RemainingMatches[0]->getDeclName();
3979 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
3980 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor45014fd2008-11-10 20:40:00 +00003981 return 0;
3982}
3983
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003984/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003985/// (which eventually refers to the declaration Func) and the call
3986/// arguments Args/NumArgs, attempt to resolve the function call down
3987/// to a specific function. If overload resolution succeeds, returns
3988/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003989/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003990/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003991FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003992 DeclarationName UnqualifiedName,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003993 bool HasExplicitTemplateArgs,
3994 const TemplateArgument *ExplicitTemplateArgs,
3995 unsigned NumExplicitTemplateArgs,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003996 SourceLocation LParenLoc,
3997 Expr **Args, unsigned NumArgs,
3998 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003999 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004000 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004001 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004002
4003 // Add the functions denoted by Callee to the set of candidate
4004 // functions. While we're doing so, track whether argument-dependent
4005 // lookup still applies, per:
4006 //
4007 // C++0x [basic.lookup.argdep]p3:
4008 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4009 // and let Y be the lookup set produced by argument dependent
4010 // lookup (defined as follows). If X contains
4011 //
4012 // -- a declaration of a class member, or
4013 //
4014 // -- a block-scope function declaration that is not a
4015 // using-declaration, or
4016 //
4017 // -- a declaration that is neither a function or a function
4018 // template
4019 //
4020 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004021 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004022 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4023 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4024 FuncEnd = Ovl->function_end();
4025 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00004026 DeclContext *Ctx = 0;
4027 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004028 if (HasExplicitTemplateArgs)
4029 continue;
4030
Douglas Gregorb60eb752009-06-25 22:08:12 +00004031 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4032 Ctx = FunDecl->getDeclContext();
4033 } else {
4034 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004035 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4036 ExplicitTemplateArgs,
4037 NumExplicitTemplateArgs,
4038 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004039 Ctx = FunTmpl->getDeclContext();
4040 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004041
Douglas Gregorb60eb752009-06-25 22:08:12 +00004042
4043 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004044 ArgumentDependentLookup = false;
4045 }
4046 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004047 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004048 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4049
4050 if (Func->getDeclContext()->isRecord() ||
4051 Func->getDeclContext()->isFunctionOrMethod())
4052 ArgumentDependentLookup = false;
Douglas Gregorb60eb752009-06-25 22:08:12 +00004053 } else if (FunctionTemplateDecl *FuncTemplate
4054 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004055 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4056 ExplicitTemplateArgs,
4057 NumExplicitTemplateArgs,
4058 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004059
4060 if (FuncTemplate->getDeclContext()->isRecord())
4061 ArgumentDependentLookup = false;
4062 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004063
4064 if (Callee)
4065 UnqualifiedName = Callee->getDeclName();
4066
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004067 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004068 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004069 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004070 CandidateSet);
4071
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004072 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004073 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004074 case OR_Success:
4075 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004076
4077 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00004078 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004079 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004080 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004081 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4082 break;
4083
4084 case OR_Ambiguous:
4085 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004086 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004087 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4088 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004089
4090 case OR_Deleted:
4091 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4092 << Best->Function->isDeleted()
4093 << UnqualifiedName
4094 << Fn->getSourceRange();
4095 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4096 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004097 }
4098
4099 // Overload resolution failed. Destroy all of the subexpressions and
4100 // return NULL.
4101 Fn->Destroy(Context);
4102 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4103 Args[Arg]->Destroy(Context);
4104 return 0;
4105}
4106
Douglas Gregorc78182d2009-03-13 23:49:33 +00004107/// \brief Create a unary operation that may resolve to an overloaded
4108/// operator.
4109///
4110/// \param OpLoc The location of the operator itself (e.g., '*').
4111///
4112/// \param OpcIn The UnaryOperator::Opcode that describes this
4113/// operator.
4114///
4115/// \param Functions The set of non-member functions that will be
4116/// considered by overload resolution. The caller needs to build this
4117/// set based on the context using, e.g.,
4118/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4119/// set should not contain any member functions; those will be added
4120/// by CreateOverloadedUnaryOp().
4121///
4122/// \param input The input argument.
4123Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4124 unsigned OpcIn,
4125 FunctionSet &Functions,
4126 ExprArg input) {
4127 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4128 Expr *Input = (Expr *)input.get();
4129
4130 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4131 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4132 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4133
4134 Expr *Args[2] = { Input, 0 };
4135 unsigned NumArgs = 1;
4136
4137 // For post-increment and post-decrement, add the implicit '0' as
4138 // the second argument, so that we know this is a post-increment or
4139 // post-decrement.
4140 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4141 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4142 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4143 SourceLocation());
4144 NumArgs = 2;
4145 }
4146
4147 if (Input->isTypeDependent()) {
4148 OverloadedFunctionDecl *Overloads
4149 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4150 for (FunctionSet::iterator Func = Functions.begin(),
4151 FuncEnd = Functions.end();
4152 Func != FuncEnd; ++Func)
4153 Overloads->addOverload(*Func);
4154
4155 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4156 OpLoc, false, false);
4157
4158 input.release();
4159 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4160 &Args[0], NumArgs,
4161 Context.DependentTy,
4162 OpLoc));
4163 }
4164
4165 // Build an empty overload set.
4166 OverloadCandidateSet CandidateSet;
4167
4168 // Add the candidates from the given function set.
4169 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4170
4171 // Add operator candidates that are member functions.
4172 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4173
4174 // Add builtin operator candidates.
4175 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4176
4177 // Perform overload resolution.
4178 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004179 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004180 case OR_Success: {
4181 // We found a built-in operator or an overloaded operator.
4182 FunctionDecl *FnDecl = Best->Function;
4183
4184 if (FnDecl) {
4185 // We matched an overloaded operator. Build a call to that
4186 // operator.
4187
4188 // Convert the arguments.
4189 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4190 if (PerformObjectArgumentInitialization(Input, Method))
4191 return ExprError();
4192 } else {
4193 // Convert the arguments.
4194 if (PerformCopyInitialization(Input,
4195 FnDecl->getParamDecl(0)->getType(),
4196 "passing"))
4197 return ExprError();
4198 }
4199
4200 // Determine the result type
4201 QualType ResultTy
4202 = FnDecl->getType()->getAsFunctionType()->getResultType();
4203 ResultTy = ResultTy.getNonReferenceType();
4204
4205 // Build the actual expression node.
4206 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4207 SourceLocation());
4208 UsualUnaryConversions(FnExpr);
4209
4210 input.release();
Anders Carlsson16497742009-08-16 04:11:06 +00004211
4212 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4213 &Input, 1, ResultTy, OpLoc);
4214 return MaybeBindToTemporary(CE);
Douglas Gregorc78182d2009-03-13 23:49:33 +00004215 } else {
4216 // We matched a built-in operator. Convert the arguments, then
4217 // break out so that we will build the appropriate built-in
4218 // operator node.
4219 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4220 Best->Conversions[0], "passing"))
4221 return ExprError();
4222
4223 break;
4224 }
4225 }
4226
4227 case OR_No_Viable_Function:
4228 // No viable function; fall through to handling this as a
4229 // built-in operator, which will produce an error message for us.
4230 break;
4231
4232 case OR_Ambiguous:
4233 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4234 << UnaryOperator::getOpcodeStr(Opc)
4235 << Input->getSourceRange();
4236 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4237 return ExprError();
4238
4239 case OR_Deleted:
4240 Diag(OpLoc, diag::err_ovl_deleted_oper)
4241 << Best->Function->isDeleted()
4242 << UnaryOperator::getOpcodeStr(Opc)
4243 << Input->getSourceRange();
4244 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4245 return ExprError();
4246 }
4247
4248 // Either we found no viable overloaded operator or we matched a
4249 // built-in operator. In either case, fall through to trying to
4250 // build a built-in operation.
4251 input.release();
4252 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4253}
4254
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004255/// \brief Create a binary operation that may resolve to an overloaded
4256/// operator.
4257///
4258/// \param OpLoc The location of the operator itself (e.g., '+').
4259///
4260/// \param OpcIn The BinaryOperator::Opcode that describes this
4261/// operator.
4262///
4263/// \param Functions The set of non-member functions that will be
4264/// considered by overload resolution. The caller needs to build this
4265/// set based on the context using, e.g.,
4266/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4267/// set should not contain any member functions; those will be added
4268/// by CreateOverloadedBinOp().
4269///
4270/// \param LHS Left-hand argument.
4271/// \param RHS Right-hand argument.
4272Sema::OwningExprResult
4273Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4274 unsigned OpcIn,
4275 FunctionSet &Functions,
4276 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004277 Expr *Args[2] = { LHS, RHS };
4278
4279 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4280 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4281 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4282
4283 // If either side is type-dependent, create an appropriate dependent
4284 // expression.
4285 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
4286 // .* cannot be overloaded.
4287 if (Opc == BinaryOperator::PtrMemD)
4288 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
4289 Context.DependentTy, OpLoc));
4290
4291 OverloadedFunctionDecl *Overloads
4292 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4293 for (FunctionSet::iterator Func = Functions.begin(),
4294 FuncEnd = Functions.end();
4295 Func != FuncEnd; ++Func)
4296 Overloads->addOverload(*Func);
4297
4298 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4299 OpLoc, false, false);
4300
4301 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4302 Args, 2,
4303 Context.DependentTy,
4304 OpLoc));
4305 }
4306
4307 // If this is the .* operator, which is not overloadable, just
4308 // create a built-in binary operator.
4309 if (Opc == BinaryOperator::PtrMemD)
4310 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4311
4312 // If this is one of the assignment operators, we only perform
4313 // overload resolution if the left-hand side is a class or
4314 // enumeration type (C++ [expr.ass]p3).
4315 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4316 !LHS->getType()->isOverloadableType())
4317 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4318
Douglas Gregorc78182d2009-03-13 23:49:33 +00004319 // Build an empty overload set.
4320 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004321
4322 // Add the candidates from the given function set.
4323 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4324
4325 // Add operator candidates that are member functions.
4326 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4327
4328 // Add builtin operator candidates.
4329 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4330
4331 // Perform overload resolution.
4332 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004333 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004334 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004335 // We found a built-in operator or an overloaded operator.
4336 FunctionDecl *FnDecl = Best->Function;
4337
4338 if (FnDecl) {
4339 // We matched an overloaded operator. Build a call to that
4340 // operator.
4341
4342 // Convert the arguments.
4343 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4344 if (PerformObjectArgumentInitialization(LHS, Method) ||
4345 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
4346 "passing"))
4347 return ExprError();
4348 } else {
4349 // Convert the arguments.
4350 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
4351 "passing") ||
4352 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
4353 "passing"))
4354 return ExprError();
4355 }
4356
4357 // Determine the result type
4358 QualType ResultTy
4359 = FnDecl->getType()->getAsFunctionType()->getResultType();
4360 ResultTy = ResultTy.getNonReferenceType();
4361
4362 // Build the actual expression node.
4363 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argiris Kirtzidiscca21b82009-07-14 03:19:38 +00004364 OpLoc);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004365 UsualUnaryConversions(FnExpr);
4366
Anders Carlsson16497742009-08-16 04:11:06 +00004367 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4368 Args, 2, ResultTy, OpLoc);
4369 return MaybeBindToTemporary(CE);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004370 } else {
4371 // We matched a built-in operator. Convert the arguments, then
4372 // break out so that we will build the appropriate built-in
4373 // operator node.
4374 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4375 Best->Conversions[0], "passing") ||
4376 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4377 Best->Conversions[1], "passing"))
4378 return ExprError();
4379
4380 break;
4381 }
4382 }
4383
4384 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004385 // For class as left operand for assignment or compound assigment operator
4386 // do not fall through to handling in built-in, but report that no overloaded
4387 // assignment operator found
4388 if (LHS->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4389 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4390 << BinaryOperator::getOpcodeStr(Opc)
4391 << LHS->getSourceRange() << RHS->getSourceRange();
4392 return ExprError();
4393 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004394 // No viable function; fall through to handling this as a
4395 // built-in operator, which will produce an error message for us.
4396 break;
4397
4398 case OR_Ambiguous:
4399 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4400 << BinaryOperator::getOpcodeStr(Opc)
4401 << LHS->getSourceRange() << RHS->getSourceRange();
4402 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4403 return ExprError();
4404
4405 case OR_Deleted:
4406 Diag(OpLoc, diag::err_ovl_deleted_oper)
4407 << Best->Function->isDeleted()
4408 << BinaryOperator::getOpcodeStr(Opc)
4409 << LHS->getSourceRange() << RHS->getSourceRange();
4410 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4411 return ExprError();
4412 }
4413
4414 // Either we found no viable overloaded operator or we matched a
4415 // built-in operator. In either case, try to build a built-in
4416 // operation.
4417 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4418}
4419
Douglas Gregor3257fb52008-12-22 05:46:06 +00004420/// BuildCallToMemberFunction - Build a call to a member
4421/// function. MemExpr is the expression that refers to the member
4422/// function (and includes the object parameter), Args/NumArgs are the
4423/// arguments to the function call (not including the object
4424/// parameter). The caller needs to validate that the member
4425/// expression refers to a member function or an overloaded member
4426/// function.
4427Sema::ExprResult
4428Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4429 SourceLocation LParenLoc, Expr **Args,
4430 unsigned NumArgs, SourceLocation *CommaLocs,
4431 SourceLocation RParenLoc) {
4432 // Dig out the member expression. This holds both the object
4433 // argument and the member function we're referring to.
4434 MemberExpr *MemExpr = 0;
4435 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4436 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4437 else
4438 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4439 assert(MemExpr && "Building member call without member expression");
4440
4441 // Extract the object argument.
4442 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004443
Douglas Gregor3257fb52008-12-22 05:46:06 +00004444 CXXMethodDecl *Method = 0;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004445 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4446 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004447 // Add overload candidates
4448 OverloadCandidateSet CandidateSet;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004449 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4450
Douglas Gregor050cabf2009-08-21 18:42:58 +00004451 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4452 Func != FuncEnd; ++Func) {
4453 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4454 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4455 /*SuppressUserConversions=*/false);
4456 else
4457 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4458 /*FIXME:*/false, /*FIXME:*/0,
4459 /*FIXME:*/0, ObjectArg, Args, NumArgs,
4460 CandidateSet,
4461 /*SuppressUsedConversions=*/false);
4462 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004463
Douglas Gregor3257fb52008-12-22 05:46:06 +00004464 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004465 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004466 case OR_Success:
4467 Method = cast<CXXMethodDecl>(Best->Function);
4468 break;
4469
4470 case OR_No_Viable_Function:
4471 Diag(MemExpr->getSourceRange().getBegin(),
4472 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004473 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004474 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4475 // FIXME: Leaking incoming expressions!
4476 return true;
4477
4478 case OR_Ambiguous:
4479 Diag(MemExpr->getSourceRange().getBegin(),
4480 diag::err_ovl_ambiguous_member_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004481 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004482 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4483 // FIXME: Leaking incoming expressions!
4484 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004485
4486 case OR_Deleted:
4487 Diag(MemExpr->getSourceRange().getBegin(),
4488 diag::err_ovl_deleted_member_call)
4489 << Best->Function->isDeleted()
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004490 << DeclName << MemExprE->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004491 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4492 // FIXME: Leaking incoming expressions!
4493 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004494 }
4495
4496 FixOverloadedFunctionReference(MemExpr, Method);
4497 } else {
4498 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4499 }
4500
4501 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004502 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004503 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4504 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004505 Method->getResultType().getNonReferenceType(),
4506 RParenLoc));
4507
4508 // Convert the object argument (for a non-static member function call).
4509 if (!Method->isStatic() &&
4510 PerformObjectArgumentInitialization(ObjectArg, Method))
4511 return true;
4512 MemExpr->setBase(ObjectArg);
4513
4514 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004515 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004516 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4517 RParenLoc))
4518 return true;
4519
Anders Carlsson7fb13802009-08-16 01:56:34 +00004520 if (CheckFunctionCall(Method, TheCall.get()))
4521 return true;
Anders Carlssonb8ff3402009-08-16 03:42:12 +00004522
4523 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004524}
4525
Douglas Gregor10f3c502008-11-19 21:05:33 +00004526/// BuildCallToObjectOfClassType - Build a call to an object of class
4527/// type (C++ [over.call.object]), which can end up invoking an
4528/// overloaded function call operator (@c operator()) or performing a
4529/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004530Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004531Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4532 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004533 Expr **Args, unsigned NumArgs,
4534 SourceLocation *CommaLocs,
4535 SourceLocation RParenLoc) {
4536 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004537 const RecordType *Record = Object->getType()->getAs<RecordType>();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004538
4539 // C++ [over.call.object]p1:
4540 // If the primary-expression E in the function call syntax
Eli Friedmand5a72f02009-08-05 19:21:58 +00004541 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor10f3c502008-11-19 21:05:33 +00004542 // candidate functions includes at least the function call
4543 // operators of T. The function call operators of T are obtained by
4544 // ordinary lookup of the name operator() in the context of
4545 // (E).operator().
4546 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004547 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004548 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004549 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004550 Oper != OperEnd; ++Oper)
4551 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4552 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004553
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004554 // C++ [over.call.object]p2:
4555 // In addition, for each conversion function declared in T of the
4556 // form
4557 //
4558 // operator conversion-type-id () cv-qualifier;
4559 //
4560 // where cv-qualifier is the same cv-qualification as, or a
4561 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004562 // denotes the type "pointer to function of (P1,...,Pn) returning
4563 // R", or the type "reference to pointer to function of
4564 // (P1,...,Pn) returning R", or the type "reference to function
4565 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004566 // is also considered as a candidate function. Similarly,
4567 // surrogate call functions are added to the set of candidate
4568 // functions for each conversion function declared in an
4569 // accessible base class provided the function is not hidden
4570 // within T by another intervening declaration.
4571 //
4572 // FIXME: Look in base classes for more conversion operators!
4573 OverloadedFunctionDecl *Conversions
4574 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004575 for (OverloadedFunctionDecl::function_iterator
4576 Func = Conversions->function_begin(),
4577 FuncEnd = Conversions->function_end();
4578 Func != FuncEnd; ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00004579 CXXConversionDecl *Conv;
4580 FunctionTemplateDecl *ConvTemplate;
4581 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
4582
4583 // Skip over templated conversion functions; they aren't
4584 // surrogates.
4585 if (ConvTemplate)
4586 continue;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004587
4588 // Strip the reference type (if any) and then the pointer type (if
4589 // any) to get down to what might be a function type.
4590 QualType ConvType = Conv->getConversionType().getNonReferenceType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004591 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004592 ConvType = ConvPtrType->getPointeeType();
4593
Douglas Gregor4fa58902009-02-26 23:50:07 +00004594 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004595 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4596 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004597
4598 // Perform overload resolution.
4599 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004600 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004601 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004602 // Overload resolution succeeded; we'll build the appropriate call
4603 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004604 break;
4605
4606 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004607 Diag(Object->getSourceRange().getBegin(),
4608 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004609 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004610 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004611 break;
4612
4613 case OR_Ambiguous:
4614 Diag(Object->getSourceRange().getBegin(),
4615 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004616 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004617 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4618 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004619
4620 case OR_Deleted:
4621 Diag(Object->getSourceRange().getBegin(),
4622 diag::err_ovl_deleted_object_call)
4623 << Best->Function->isDeleted()
4624 << Object->getType() << Object->getSourceRange();
4625 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4626 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004627 }
4628
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004629 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004630 // We had an error; delete all of the subexpressions and return
4631 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004632 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004633 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004634 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004635 return true;
4636 }
4637
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004638 if (Best->Function == 0) {
4639 // Since there is no function declaration, this is one of the
4640 // surrogate candidates. Dig out the conversion function.
4641 CXXConversionDecl *Conv
4642 = cast<CXXConversionDecl>(
4643 Best->Conversions[0].UserDefined.ConversionFunction);
4644
4645 // We selected one of the surrogate functions that converts the
4646 // object parameter to a function pointer. Perform the conversion
4647 // on the object argument, then let ActOnCallExpr finish the job.
4648 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004649 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004650 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00004651 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00004652 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004653 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4654 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4655 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004656 }
4657
4658 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4659 // that calls this method, using Object for the implicit object
4660 // parameter and passing along the remaining arguments.
4661 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004662 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004663
4664 unsigned NumArgsInProto = Proto->getNumArgs();
4665 unsigned NumArgsToCheck = NumArgs;
4666
4667 // Build the full argument list for the method call (the
4668 // implicit object parameter is placed at the beginning of the
4669 // list).
4670 Expr **MethodArgs;
4671 if (NumArgs < NumArgsInProto) {
4672 NumArgsToCheck = NumArgsInProto;
4673 MethodArgs = new Expr*[NumArgsInProto + 1];
4674 } else {
4675 MethodArgs = new Expr*[NumArgs + 1];
4676 }
4677 MethodArgs[0] = Object;
4678 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4679 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4680
Ted Kremenek0c97e042009-02-07 01:47:29 +00004681 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4682 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004683 UsualUnaryConversions(NewFn);
4684
4685 // Once we've built TheCall, all of the expressions are properly
4686 // owned.
4687 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004688 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004689 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4690 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004691 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004692 delete [] MethodArgs;
4693
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004694 // We may have default arguments. If so, we need to allocate more
4695 // slots in the call for them.
4696 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004697 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004698 else if (NumArgs > NumArgsInProto)
4699 NumArgsToCheck = NumArgsInProto;
4700
Chris Lattner81f00ed2009-04-12 08:11:20 +00004701 bool IsError = false;
4702
Douglas Gregor10f3c502008-11-19 21:05:33 +00004703 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004704 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004705 TheCall->setArg(0, Object);
4706
Chris Lattner81f00ed2009-04-12 08:11:20 +00004707
Douglas Gregor10f3c502008-11-19 21:05:33 +00004708 // Check the argument types.
4709 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004710 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004711 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004712 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004713
4714 // Pass the argument.
4715 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004716 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004717 } else {
Anders Carlsson3d752db2009-08-14 18:30:22 +00004718 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004719 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004720
4721 TheCall->setArg(i + 1, Arg);
4722 }
4723
4724 // If this is a variadic call, handle args passed through "...".
4725 if (Proto->isVariadic()) {
4726 // Promote the arguments (C99 6.5.2.2p7).
4727 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4728 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004729 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004730 TheCall->setArg(i + 1, Arg);
4731 }
4732 }
4733
Chris Lattner81f00ed2009-04-12 08:11:20 +00004734 if (IsError) return true;
4735
Anders Carlsson7fb13802009-08-16 01:56:34 +00004736 if (CheckFunctionCall(Method, TheCall.get()))
4737 return true;
4738
Anders Carlsson422a5fe2009-08-16 03:53:54 +00004739 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004740}
4741
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004742/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4743/// (if one exists), where @c Base is an expression of class type and
4744/// @c Member is the name of the member we're trying to find.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004745Sema::OwningExprResult
4746Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4747 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004748 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4749
4750 // C++ [over.ref]p1:
4751 //
4752 // [...] An expression x->m is interpreted as (x.operator->())->m
4753 // for a class object x of type T if T::operator->() exists and if
4754 // the operator is selected as the best match function by the
4755 // overload resolution mechanism (13.3).
4756 // FIXME: look in base classes.
4757 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4758 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004759 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorda61ad22009-08-06 03:17:00 +00004760
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004761 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004762 for (llvm::tie(Oper, OperEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004763 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004764 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004765 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004766
4767 // Perform overload resolution.
4768 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004769 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004770 case OR_Success:
4771 // Overload resolution succeeded; we'll build the call below.
4772 break;
4773
4774 case OR_No_Viable_Function:
4775 if (CandidateSet.empty())
4776 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004777 << Base->getType() << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004778 else
4779 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004780 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004781 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004782 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004783
4784 case OR_Ambiguous:
4785 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004786 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004787 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004788 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004789
4790 case OR_Deleted:
4791 Diag(OpLoc, diag::err_ovl_deleted_oper)
4792 << Best->Function->isDeleted()
Douglas Gregorda61ad22009-08-06 03:17:00 +00004793 << "operator->" << Base->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004794 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004795 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004796 }
4797
4798 // Convert the object parameter.
4799 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004800 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorda61ad22009-08-06 03:17:00 +00004801 return ExprError();
Douglas Gregor9c690e92008-11-21 03:04:22 +00004802
4803 // No concerns about early exits now.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004804 BaseIn.release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004805
4806 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004807 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4808 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004809 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004810 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004811 Method->getResultType().getNonReferenceType(),
4812 OpLoc);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004813 return Owned(Base);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004814}
4815
Douglas Gregor45014fd2008-11-10 20:40:00 +00004816/// FixOverloadedFunctionReference - E is an expression that refers to
4817/// a C++ overloaded function (possibly with some parentheses and
4818/// perhaps a '&' around it). We have resolved the overloaded function
4819/// to the function declaration Fn, so patch up the expression E to
4820/// refer (possibly indirectly) to Fn.
4821void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4822 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4823 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4824 E->setType(PE->getSubExpr()->getType());
4825 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4826 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4827 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004828 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4829 if (Method->isStatic()) {
4830 // Do nothing: static member functions aren't any different
4831 // from non-member functions.
Mike Stump90fc78e2009-08-04 21:02:39 +00004832 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor3f411962009-02-11 01:18:59 +00004833 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4834 // We have taken the address of a pointer to member
4835 // function. Perform the computation here so that we get the
4836 // appropriate pointer to member type.
4837 DRE->setDecl(Fn);
4838 DRE->setType(Fn->getType());
4839 QualType ClassType
4840 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4841 E->setType(Context.getMemberPointerType(Fn->getType(),
4842 ClassType.getTypePtr()));
4843 return;
4844 }
4845 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004846 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004847 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004848 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor62f78762009-07-08 20:55:45 +00004849 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4850 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4851 "Expected overloaded function or function template");
Douglas Gregor45014fd2008-11-10 20:40:00 +00004852 DR->setDecl(Fn);
4853 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004854 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4855 MemExpr->setMemberDecl(Fn);
4856 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004857 } else {
4858 assert(false && "Invalid reference to overloaded function");
4859 }
4860}
4861
Douglas Gregord2baafd2008-10-21 16:13:35 +00004862} // end namespace clang