blob: c445144b6238d1c493f6d8f761f044809d01dd2b [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.
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001202bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1203 CastExpr::CastKind &Kind) {
Sebastian Redlba387562009-01-25 19:43:20 +00001204 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001205 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001206 if (!FromPtrType) {
1207 // This must be a null pointer to member pointer conversion
1208 assert(From->isNullPointerConstant(Context) &&
1209 "Expr must be null pointer constant!");
1210 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001211 return false;
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001212 }
Sebastian Redlba387562009-01-25 19:43:20 +00001213
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001214 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001215 assert(ToPtrType && "No member pointer cast has a target type "
1216 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001217
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001218 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1219 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001220
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001221 // FIXME: What about dependent types?
1222 assert(FromClass->isRecordType() && "Pointer into non-class.");
1223 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001224
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001225 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1226 /*DetectVirtual=*/true);
1227 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1228 assert(DerivationOkay &&
1229 "Should not have been called if derivation isn't OK.");
1230 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001231
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001232 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1233 getUnqualifiedType())) {
1234 // Derivation is ambiguous. Redo the check to find the exact paths.
1235 Paths.clear();
1236 Paths.setRecordingPaths(true);
1237 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1238 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1239 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001240
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001241 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1242 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1243 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1244 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001245 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001246
Douglas Gregor2e047592009-02-28 01:32:25 +00001247 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001248 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1249 << FromClass << ToClass << QualType(VBase, 0)
1250 << From->getSourceRange();
1251 return true;
1252 }
1253
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001254 // Must be a base to derived member conversion.
1255 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redlba387562009-01-25 19:43:20 +00001256 return false;
1257}
1258
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001259/// IsQualificationConversion - Determines whether the conversion from
1260/// an rvalue of type FromType to ToType is a qualification conversion
1261/// (C++ 4.4).
1262bool
1263Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1264{
1265 FromType = Context.getCanonicalType(FromType);
1266 ToType = Context.getCanonicalType(ToType);
1267
1268 // If FromType and ToType are the same type, this is not a
1269 // qualification conversion.
1270 if (FromType == ToType)
1271 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001272
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001273 // (C++ 4.4p4):
1274 // A conversion can add cv-qualifiers at levels other than the first
1275 // in multi-level pointers, subject to the following rules: [...]
1276 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001277 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001278 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001279 // Within each iteration of the loop, we check the qualifiers to
1280 // determine if this still looks like a qualification
1281 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001282 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001283 // until there are no more pointers or pointers-to-members left to
1284 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001285 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001286
1287 // -- for every j > 0, if const is in cv 1,j then const is in cv
1288 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001289 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001290 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001291
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001292 // -- if the cv 1,j and cv 2,j are different, then const is in
1293 // every cv for 0 < k < j.
1294 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001295 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001296 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001297
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001298 // Keep track of whether all prior cv-qualifiers in the "to" type
1299 // include const.
1300 PreviousToQualsIncludeConst
1301 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001302 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001303
1304 // We are left with FromType and ToType being the pointee types
1305 // after unwrapping the original FromType and ToType the same number
1306 // of types. If we unwrapped any pointers, and if FromType and
1307 // ToType have the same unqualified type (since we checked
1308 // qualifiers above), then this is a qualification conversion.
1309 return UnwrappedAnyPointer &&
1310 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1311}
1312
Douglas Gregor8c860df2009-08-21 23:19:43 +00001313/// \brief Given a function template or function, extract the function template
1314/// declaration (if any) and the underlying function declaration.
1315template<typename T>
1316static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1317 FunctionTemplateDecl *&FunctionTemplate) {
1318 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1319 if (FunctionTemplate)
1320 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1321 else
1322 Function = cast<T>(Orig);
1323}
1324
1325
Douglas Gregorb206cc42009-01-30 23:27:23 +00001326/// Determines whether there is a user-defined conversion sequence
1327/// (C++ [over.ics.user]) that converts expression From to the type
1328/// ToType. If such a conversion exists, User will contain the
1329/// user-defined conversion sequence that performs such a conversion
1330/// and this routine will return true. Otherwise, this routine returns
1331/// false and User is unspecified.
1332///
1333/// \param AllowConversionFunctions true if the conversion should
1334/// consider conversion functions at all. If false, only constructors
1335/// will be considered.
1336///
1337/// \param AllowExplicit true if the conversion should consider C++0x
1338/// "explicit" conversion functions as well as non-explicit conversion
1339/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001340///
1341/// \param ForceRValue true if the expression should be treated as an rvalue
1342/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001343bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001344 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001345 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001346 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001347{
1348 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001349 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001350 if (CXXRecordDecl *ToRecordDecl
1351 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1352 // C++ [over.match.ctor]p1:
1353 // When objects of class type are direct-initialized (8.5), or
1354 // copy-initialized from an expression of the same or a
1355 // derived class type (8.5), overload resolution selects the
1356 // constructor. [...] For copy-initialization, the candidate
1357 // functions are all the converting constructors (12.3.1) of
1358 // that class. The argument list is the expression-list within
1359 // the parentheses of the initializer.
1360 DeclarationName ConstructorName
1361 = Context.DeclarationNames.getCXXConstructorName(
1362 Context.getCanonicalType(ToType).getUnqualifiedType());
1363 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001364 for (llvm::tie(Con, ConEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001365 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001366 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00001367 // Find the constructor (which may be a template).
1368 CXXConstructorDecl *Constructor = 0;
1369 FunctionTemplateDecl *ConstructorTmpl
1370 = dyn_cast<FunctionTemplateDecl>(*Con);
1371 if (ConstructorTmpl)
1372 Constructor
1373 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1374 else
1375 Constructor = cast<CXXConstructorDecl>(*Con);
1376
Fariborz Jahanian625fb9d2009-08-06 17:22:51 +00001377 if (!Constructor->isInvalidDecl() &&
Douglas Gregor050cabf2009-08-21 18:42:58 +00001378 Constructor->isConvertingConstructor()) {
1379 if (ConstructorTmpl)
1380 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1381 1, CandidateSet,
1382 /*SuppressUserConversions=*/true,
1383 ForceRValue);
1384 else
1385 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1386 /*SuppressUserConversions=*/true, ForceRValue);
1387 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001388 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001389 }
1390 }
1391
Douglas Gregorb206cc42009-01-30 23:27:23 +00001392 if (!AllowConversionFunctions) {
1393 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-02-28 01:32:25 +00001394 } else if (const RecordType *FromRecordType
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001395 = From->getType()->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001396 if (CXXRecordDecl *FromRecordDecl
1397 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1398 // Add all of the conversion functions as candidates.
1399 // FIXME: Look for conversions in base classes!
1400 OverloadedFunctionDecl *Conversions
1401 = FromRecordDecl->getConversionFunctions();
1402 for (OverloadedFunctionDecl::function_iterator Func
1403 = Conversions->function_begin();
1404 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001405 CXXConversionDecl *Conv;
1406 FunctionTemplateDecl *ConvTemplate;
1407 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1408 if (ConvTemplate)
1409 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1410 else
1411 Conv = dyn_cast<CXXConversionDecl>(*Func);
1412
1413 if (AllowExplicit || !Conv->isExplicit()) {
1414 if (ConvTemplate)
1415 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1416 CandidateSet);
1417 else
1418 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1419 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001420 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001421 }
1422 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001423
1424 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001425 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001426 case OR_Success:
1427 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001428 if (CXXConstructorDecl *Constructor
1429 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1430 // C++ [over.ics.user]p1:
1431 // If the user-defined conversion is specified by a
1432 // constructor (12.3.1), the initial standard conversion
1433 // sequence converts the source type to the type required by
1434 // the argument of the constructor.
1435 //
1436 // FIXME: What about ellipsis conversions?
1437 QualType ThisType = Constructor->getThisType(Context);
1438 User.Before = Best->Conversions[0].Standard;
1439 User.ConversionFunction = Constructor;
1440 User.After.setAsIdentityConversion();
1441 User.After.FromTypePtr
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001442 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001443 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1444 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001445 } else if (CXXConversionDecl *Conversion
1446 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1447 // C++ [over.ics.user]p1:
1448 //
1449 // [...] If the user-defined conversion is specified by a
1450 // conversion function (12.3.2), the initial standard
1451 // conversion sequence converts the source type to the
1452 // implicit object parameter of the conversion function.
1453 User.Before = Best->Conversions[0].Standard;
1454 User.ConversionFunction = Conversion;
1455
1456 // C++ [over.ics.user]p2:
1457 // The second standard conversion sequence converts the
1458 // result of the user-defined conversion to the target type
1459 // for the sequence. Since an implicit conversion sequence
1460 // is an initialization, the special rules for
1461 // initialization by user-defined conversion apply when
1462 // selecting the best user-defined conversion for a
1463 // user-defined conversion sequence (see 13.3.3 and
1464 // 13.3.3.1).
1465 User.After = Best->FinalConversion;
1466 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001467 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001468 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001469 return false;
1470 }
1471
1472 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001473 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001474 // No conversion here! We're done.
1475 return false;
1476
1477 case OR_Ambiguous:
1478 // FIXME: See C++ [over.best.ics]p10 for the handling of
1479 // ambiguous conversion sequences.
1480 return false;
1481 }
1482
1483 return false;
1484}
1485
Douglas Gregord2baafd2008-10-21 16:13:35 +00001486/// CompareImplicitConversionSequences - Compare two implicit
1487/// conversion sequences to determine whether one is better than the
1488/// other or if they are indistinguishable (C++ 13.3.3.2).
1489ImplicitConversionSequence::CompareKind
1490Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1491 const ImplicitConversionSequence& ICS2)
1492{
1493 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1494 // conversion sequences (as defined in 13.3.3.1)
1495 // -- a standard conversion sequence (13.3.3.1.1) is a better
1496 // conversion sequence than a user-defined conversion sequence or
1497 // an ellipsis conversion sequence, and
1498 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1499 // conversion sequence than an ellipsis conversion sequence
1500 // (13.3.3.1.3).
1501 //
1502 if (ICS1.ConversionKind < ICS2.ConversionKind)
1503 return ImplicitConversionSequence::Better;
1504 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1505 return ImplicitConversionSequence::Worse;
1506
1507 // Two implicit conversion sequences of the same form are
1508 // indistinguishable conversion sequences unless one of the
1509 // following rules apply: (C++ 13.3.3.2p3):
1510 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1511 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1512 else if (ICS1.ConversionKind ==
1513 ImplicitConversionSequence::UserDefinedConversion) {
1514 // User-defined conversion sequence U1 is a better conversion
1515 // sequence than another user-defined conversion sequence U2 if
1516 // they contain the same user-defined conversion function or
1517 // constructor and if the second standard conversion sequence of
1518 // U1 is better than the second standard conversion sequence of
1519 // U2 (C++ 13.3.3.2p3).
1520 if (ICS1.UserDefined.ConversionFunction ==
1521 ICS2.UserDefined.ConversionFunction)
1522 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1523 ICS2.UserDefined.After);
1524 }
1525
1526 return ImplicitConversionSequence::Indistinguishable;
1527}
1528
1529/// CompareStandardConversionSequences - Compare two standard
1530/// conversion sequences to determine whether one is better than the
1531/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1532ImplicitConversionSequence::CompareKind
1533Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1534 const StandardConversionSequence& SCS2)
1535{
1536 // Standard conversion sequence S1 is a better conversion sequence
1537 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1538
1539 // -- S1 is a proper subsequence of S2 (comparing the conversion
1540 // sequences in the canonical form defined by 13.3.3.1.1,
1541 // excluding any Lvalue Transformation; the identity conversion
1542 // sequence is considered to be a subsequence of any
1543 // non-identity conversion sequence) or, if not that,
1544 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1545 // Neither is a proper subsequence of the other. Do nothing.
1546 ;
1547 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1548 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1549 (SCS1.Second == ICK_Identity &&
1550 SCS1.Third == ICK_Identity))
1551 // SCS1 is a proper subsequence of SCS2.
1552 return ImplicitConversionSequence::Better;
1553 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1554 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1555 (SCS2.Second == ICK_Identity &&
1556 SCS2.Third == ICK_Identity))
1557 // SCS2 is a proper subsequence of SCS1.
1558 return ImplicitConversionSequence::Worse;
1559
1560 // -- the rank of S1 is better than the rank of S2 (by the rules
1561 // defined below), or, if not that,
1562 ImplicitConversionRank Rank1 = SCS1.getRank();
1563 ImplicitConversionRank Rank2 = SCS2.getRank();
1564 if (Rank1 < Rank2)
1565 return ImplicitConversionSequence::Better;
1566 else if (Rank2 < Rank1)
1567 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001568
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001569 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1570 // are indistinguishable unless one of the following rules
1571 // applies:
1572
1573 // A conversion that is not a conversion of a pointer, or
1574 // pointer to member, to bool is better than another conversion
1575 // that is such a conversion.
1576 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1577 return SCS2.isPointerConversionToBool()
1578 ? ImplicitConversionSequence::Better
1579 : ImplicitConversionSequence::Worse;
1580
Douglas Gregor14046502008-10-23 00:40:37 +00001581 // C++ [over.ics.rank]p4b2:
1582 //
1583 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001584 // conversion of B* to A* is better than conversion of B* to
1585 // void*, and conversion of A* to void* is better than conversion
1586 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001587 bool SCS1ConvertsToVoid
1588 = SCS1.isPointerConversionToVoidPointer(Context);
1589 bool SCS2ConvertsToVoid
1590 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001591 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1592 // Exactly one of the conversion sequences is a conversion to
1593 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001594 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1595 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001596 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1597 // Neither conversion sequence converts to a void pointer; compare
1598 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001599 if (ImplicitConversionSequence::CompareKind DerivedCK
1600 = CompareDerivedToBaseConversions(SCS1, SCS2))
1601 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001602 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1603 // Both conversion sequences are conversions to void
1604 // pointers. Compare the source types to determine if there's an
1605 // inheritance relationship in their sources.
1606 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1607 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1608
1609 // Adjust the types we're converting from via the array-to-pointer
1610 // conversion, if we need to.
1611 if (SCS1.First == ICK_Array_To_Pointer)
1612 FromType1 = Context.getArrayDecayedType(FromType1);
1613 if (SCS2.First == ICK_Array_To_Pointer)
1614 FromType2 = Context.getArrayDecayedType(FromType2);
1615
1616 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001617 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001618 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001619 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001620
1621 if (IsDerivedFrom(FromPointee2, FromPointee1))
1622 return ImplicitConversionSequence::Better;
1623 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1624 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001625
1626 // Objective-C++: If one interface is more specific than the
1627 // other, it is the better one.
1628 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1629 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1630 if (FromIface1 && FromIface1) {
1631 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1632 return ImplicitConversionSequence::Better;
1633 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1634 return ImplicitConversionSequence::Worse;
1635 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001636 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001637
1638 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1639 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001640 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001641 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001642 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001643
Douglas Gregor0e343382008-10-29 14:50:44 +00001644 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001645 // C++0x [over.ics.rank]p3b4:
1646 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1647 // implicit object parameter of a non-static member function declared
1648 // without a ref-qualifier, and S1 binds an rvalue reference to an
1649 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001650 // FIXME: We don't know if we're dealing with the implicit object parameter,
1651 // or if the member function in this case has a ref qualifier.
1652 // (Of course, we don't have ref qualifiers yet.)
1653 if (SCS1.RRefBinding != SCS2.RRefBinding)
1654 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1655 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001656
1657 // C++ [over.ics.rank]p3b4:
1658 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1659 // which the references refer are the same type except for
1660 // top-level cv-qualifiers, and the type to which the reference
1661 // initialized by S2 refers is more cv-qualified than the type
1662 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001663 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1664 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001665 T1 = Context.getCanonicalType(T1);
1666 T2 = Context.getCanonicalType(T2);
1667 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1668 if (T2.isMoreQualifiedThan(T1))
1669 return ImplicitConversionSequence::Better;
1670 else if (T1.isMoreQualifiedThan(T2))
1671 return ImplicitConversionSequence::Worse;
1672 }
1673 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001674
1675 return ImplicitConversionSequence::Indistinguishable;
1676}
1677
1678/// CompareQualificationConversions - Compares two standard conversion
1679/// sequences to determine whether they can be ranked based on their
1680/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1681ImplicitConversionSequence::CompareKind
1682Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1683 const StandardConversionSequence& SCS2)
1684{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001685 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001686 // -- S1 and S2 differ only in their qualification conversion and
1687 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1688 // cv-qualification signature of type T1 is a proper subset of
1689 // the cv-qualification signature of type T2, and S1 is not the
1690 // deprecated string literal array-to-pointer conversion (4.2).
1691 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1692 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1693 return ImplicitConversionSequence::Indistinguishable;
1694
1695 // FIXME: the example in the standard doesn't use a qualification
1696 // conversion (!)
1697 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1698 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1699 T1 = Context.getCanonicalType(T1);
1700 T2 = Context.getCanonicalType(T2);
1701
1702 // If the types are the same, we won't learn anything by unwrapped
1703 // them.
1704 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1705 return ImplicitConversionSequence::Indistinguishable;
1706
1707 ImplicitConversionSequence::CompareKind Result
1708 = ImplicitConversionSequence::Indistinguishable;
1709 while (UnwrapSimilarPointerTypes(T1, T2)) {
1710 // Within each iteration of the loop, we check the qualifiers to
1711 // determine if this still looks like a qualification
1712 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001713 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001714 // until there are no more pointers or pointers-to-members left
1715 // to unwrap. This essentially mimics what
1716 // IsQualificationConversion does, but here we're checking for a
1717 // strict subset of qualifiers.
1718 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1719 // The qualifiers are the same, so this doesn't tell us anything
1720 // about how the sequences rank.
1721 ;
1722 else if (T2.isMoreQualifiedThan(T1)) {
1723 // T1 has fewer qualifiers, so it could be the better sequence.
1724 if (Result == ImplicitConversionSequence::Worse)
1725 // Neither has qualifiers that are a subset of the other's
1726 // qualifiers.
1727 return ImplicitConversionSequence::Indistinguishable;
1728
1729 Result = ImplicitConversionSequence::Better;
1730 } else if (T1.isMoreQualifiedThan(T2)) {
1731 // T2 has fewer qualifiers, so it could be the better sequence.
1732 if (Result == ImplicitConversionSequence::Better)
1733 // Neither has qualifiers that are a subset of the other's
1734 // qualifiers.
1735 return ImplicitConversionSequence::Indistinguishable;
1736
1737 Result = ImplicitConversionSequence::Worse;
1738 } else {
1739 // Qualifiers are disjoint.
1740 return ImplicitConversionSequence::Indistinguishable;
1741 }
1742
1743 // If the types after this point are equivalent, we're done.
1744 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1745 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001746 }
1747
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001748 // Check that the winning standard conversion sequence isn't using
1749 // the deprecated string literal array to pointer conversion.
1750 switch (Result) {
1751 case ImplicitConversionSequence::Better:
1752 if (SCS1.Deprecated)
1753 Result = ImplicitConversionSequence::Indistinguishable;
1754 break;
1755
1756 case ImplicitConversionSequence::Indistinguishable:
1757 break;
1758
1759 case ImplicitConversionSequence::Worse:
1760 if (SCS2.Deprecated)
1761 Result = ImplicitConversionSequence::Indistinguishable;
1762 break;
1763 }
1764
1765 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001766}
1767
Douglas Gregor14046502008-10-23 00:40:37 +00001768/// CompareDerivedToBaseConversions - Compares two standard conversion
1769/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001770/// various kinds of derived-to-base conversions (C++
1771/// [over.ics.rank]p4b3). As part of these checks, we also look at
1772/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001773ImplicitConversionSequence::CompareKind
1774Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1775 const StandardConversionSequence& SCS2) {
1776 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1777 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1778 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1779 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1780
1781 // Adjust the types we're converting from via the array-to-pointer
1782 // conversion, if we need to.
1783 if (SCS1.First == ICK_Array_To_Pointer)
1784 FromType1 = Context.getArrayDecayedType(FromType1);
1785 if (SCS2.First == ICK_Array_To_Pointer)
1786 FromType2 = Context.getArrayDecayedType(FromType2);
1787
1788 // Canonicalize all of the types.
1789 FromType1 = Context.getCanonicalType(FromType1);
1790 ToType1 = Context.getCanonicalType(ToType1);
1791 FromType2 = Context.getCanonicalType(FromType2);
1792 ToType2 = Context.getCanonicalType(ToType2);
1793
Douglas Gregor0e343382008-10-29 14:50:44 +00001794 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001795 //
1796 // If class B is derived directly or indirectly from class A and
1797 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001798 //
1799 // For Objective-C, we let A, B, and C also be Objective-C
1800 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001801
1802 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001803 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001804 SCS2.Second == ICK_Pointer_Conversion &&
1805 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1806 FromType1->isPointerType() && FromType2->isPointerType() &&
1807 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001808 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001809 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001810 QualType ToPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001811 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001812 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001813 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001814 QualType ToPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001815 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001816
1817 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1818 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1819 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1820 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1821
Douglas Gregor0e343382008-10-29 14:50:44 +00001822 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001823 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1824 if (IsDerivedFrom(ToPointee1, ToPointee2))
1825 return ImplicitConversionSequence::Better;
1826 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1827 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001828
1829 if (ToIface1 && ToIface2) {
1830 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1831 return ImplicitConversionSequence::Better;
1832 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1833 return ImplicitConversionSequence::Worse;
1834 }
Douglas Gregor14046502008-10-23 00:40:37 +00001835 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001836
1837 // -- conversion of B* to A* is better than conversion of C* to A*,
1838 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1839 if (IsDerivedFrom(FromPointee2, FromPointee1))
1840 return ImplicitConversionSequence::Better;
1841 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1842 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001843
1844 if (FromIface1 && FromIface2) {
1845 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1846 return ImplicitConversionSequence::Better;
1847 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1848 return ImplicitConversionSequence::Worse;
1849 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001850 }
Douglas Gregor14046502008-10-23 00:40:37 +00001851 }
1852
Douglas Gregor0e343382008-10-29 14:50:44 +00001853 // Compare based on reference bindings.
1854 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1855 SCS1.Second == ICK_Derived_To_Base) {
1856 // -- binding of an expression of type C to a reference of type
1857 // B& is better than binding an expression of type C to a
1858 // reference of type A&,
1859 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1860 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1861 if (IsDerivedFrom(ToType1, ToType2))
1862 return ImplicitConversionSequence::Better;
1863 else if (IsDerivedFrom(ToType2, ToType1))
1864 return ImplicitConversionSequence::Worse;
1865 }
1866
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001867 // -- binding of an expression of type B to a reference of type
1868 // A& is better than binding an expression of type C to a
1869 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001870 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1871 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1872 if (IsDerivedFrom(FromType2, FromType1))
1873 return ImplicitConversionSequence::Better;
1874 else if (IsDerivedFrom(FromType1, FromType2))
1875 return ImplicitConversionSequence::Worse;
1876 }
1877 }
1878
1879
1880 // FIXME: conversion of A::* to B::* is better than conversion of
1881 // A::* to C::*,
1882
1883 // FIXME: conversion of B::* to C::* is better than conversion of
1884 // A::* to C::*, and
1885
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001886 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1887 SCS1.Second == ICK_Derived_To_Base) {
1888 // -- conversion of C to B is better than conversion of C to A,
1889 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1890 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1891 if (IsDerivedFrom(ToType1, ToType2))
1892 return ImplicitConversionSequence::Better;
1893 else if (IsDerivedFrom(ToType2, ToType1))
1894 return ImplicitConversionSequence::Worse;
1895 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001896
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001897 // -- conversion of B to A is better than conversion of C to A.
1898 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1899 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1900 if (IsDerivedFrom(FromType2, FromType1))
1901 return ImplicitConversionSequence::Better;
1902 else if (IsDerivedFrom(FromType1, FromType2))
1903 return ImplicitConversionSequence::Worse;
1904 }
1905 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001906
Douglas Gregor14046502008-10-23 00:40:37 +00001907 return ImplicitConversionSequence::Indistinguishable;
1908}
1909
Douglas Gregor81c29152008-10-29 00:13:59 +00001910/// TryCopyInitialization - Try to copy-initialize a value of type
1911/// ToType from the expression From. Return the implicit conversion
1912/// sequence required to pass this argument, which may be a bad
1913/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001914/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001915/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1916/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001917ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001918Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001919 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001920 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001921 ImplicitConversionSequence ICS;
Sebastian Redla55834a2009-04-12 17:16:29 +00001922 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1923 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001924 return ICS;
1925 } else {
Sebastian Redla55834a2009-04-12 17:16:29 +00001926 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1927 ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001928 }
1929}
1930
Sebastian Redla55834a2009-04-12 17:16:29 +00001931/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1932/// the expression @p From. Returns true (and emits a diagnostic) if there was
1933/// an error, returns false if the initialization succeeded. Elidable should
1934/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1935/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001936bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001937 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001938 if (!getLangOptions().CPlusPlus) {
1939 // In C, argument passing is the same as performing an assignment.
1940 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001941
Douglas Gregor81c29152008-10-29 00:13:59 +00001942 AssignConvertType ConvTy =
1943 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001944 if (ConvTy != Compatible &&
1945 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1946 ConvTy = Compatible;
1947
Douglas Gregor81c29152008-10-29 00:13:59 +00001948 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1949 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001950 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001951
Chris Lattner271d4c22008-11-24 05:29:24 +00001952 if (ToType->isReferenceType())
1953 return CheckReferenceInit(From, ToType);
1954
Sebastian Redla55834a2009-04-12 17:16:29 +00001955 if (!PerformImplicitConversion(From, ToType, Flavor,
1956 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001957 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001958
Chris Lattner271d4c22008-11-24 05:29:24 +00001959 return Diag(From->getSourceRange().getBegin(),
1960 diag::err_typecheck_convert_incompatible)
1961 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001962}
1963
Douglas Gregor5ed15042008-11-18 23:14:02 +00001964/// TryObjectArgumentInitialization - Try to initialize the object
1965/// parameter of the given member function (@c Method) from the
1966/// expression @p From.
1967ImplicitConversionSequence
1968Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1969 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1970 unsigned MethodQuals = Method->getTypeQualifiers();
1971 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1972
1973 // Set up the conversion sequence as a "bad" conversion, to allow us
1974 // to exit early.
1975 ImplicitConversionSequence ICS;
1976 ICS.Standard.setAsIdentityConversion();
1977 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1978
1979 // We need to have an object of class type.
1980 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001981 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001982 FromType = PT->getPointeeType();
1983
1984 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00001985
1986 // The implicit object parmeter is has the type "reference to cv X",
1987 // where X is the class of which the function is a member
1988 // (C++ [over.match.funcs]p4). However, when finding an implicit
1989 // conversion sequence for the argument, we are not allowed to
1990 // create temporaries or perform user-defined conversions
1991 // (C++ [over.match.funcs]p5). We perform a simplified version of
1992 // reference binding here, that allows class rvalues to bind to
1993 // non-constant references.
1994
1995 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1996 // with the implicit object parameter (C++ [over.match.funcs]p5).
1997 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1998 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1999 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2000 return ICS;
2001
2002 // Check that we have either the same type or a derived type. It
2003 // affects the conversion rank.
2004 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2005 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2006 ICS.Standard.Second = ICK_Identity;
2007 else if (IsDerivedFrom(FromType, ClassType))
2008 ICS.Standard.Second = ICK_Derived_To_Base;
2009 else
2010 return ICS;
2011
2012 // Success. Mark this as a reference binding.
2013 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2014 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2015 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2016 ICS.Standard.ReferenceBinding = true;
2017 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00002018 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002019 return ICS;
2020}
2021
2022/// PerformObjectArgumentInitialization - Perform initialization of
2023/// the implicit object parameter for the given Method with the given
2024/// expression.
2025bool
2026Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002027 QualType FromRecordType, DestType;
2028 QualType ImplicitParamRecordType =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002029 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002030
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002031 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002032 FromRecordType = PT->getPointeeType();
2033 DestType = Method->getThisType(Context);
2034 } else {
2035 FromRecordType = From->getType();
2036 DestType = ImplicitParamRecordType;
2037 }
2038
Douglas Gregor5ed15042008-11-18 23:14:02 +00002039 ImplicitConversionSequence ICS
2040 = TryObjectArgumentInitialization(From, Method);
2041 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2042 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002043 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002044 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2045
Douglas Gregor5ed15042008-11-18 23:14:02 +00002046 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002047 CheckDerivedToBaseConversion(FromRecordType,
2048 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002049 From->getSourceRange().getBegin(),
2050 From->getSourceRange()))
2051 return true;
2052
Anders Carlssone25b6cd2009-08-07 18:45:49 +00002053 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2054 /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002055 return false;
2056}
2057
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002058/// TryContextuallyConvertToBool - Attempt to contextually convert the
2059/// expression From to bool (C++0x [conv]p3).
2060ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2061 return TryImplicitConversion(From, Context.BoolTy, false, true);
2062}
2063
2064/// PerformContextuallyConvertToBool - Perform a contextual conversion
2065/// of the expression From to bool (C++0x [conv]p3).
2066bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2067 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2068 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2069 return false;
2070
2071 return Diag(From->getSourceRange().getBegin(),
2072 diag::err_typecheck_bool_condition)
2073 << From->getType() << From->getSourceRange();
2074}
2075
Douglas Gregord2baafd2008-10-21 16:13:35 +00002076/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002077/// candidate functions, using the given function call arguments. If
2078/// @p SuppressUserConversions, then don't allow user-defined
2079/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002080/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2081/// hacky way to implement the overloading rules for elidable copy
2082/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002083void
2084Sema::AddOverloadCandidate(FunctionDecl *Function,
2085 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002086 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002087 bool SuppressUserConversions,
2088 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002089{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002090 const FunctionProtoType* Proto
2091 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002092 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002093 assert(!isa<CXXConversionDecl>(Function) &&
2094 "Use AddConversionCandidate for conversion functions");
Douglas Gregorb60eb752009-06-25 22:08:12 +00002095 assert(!Function->getDescribedFunctionTemplate() &&
2096 "Use AddTemplateOverloadCandidate for function templates");
2097
Douglas Gregor3257fb52008-12-22 05:46:06 +00002098 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002099 if (!isa<CXXConstructorDecl>(Method)) {
2100 // If we get here, it's because we're calling a member function
2101 // that is named without a member access expression (e.g.,
2102 // "this->f") that was either written explicitly or created
2103 // implicitly. This can happen with a qualified call to a member
2104 // function, e.g., X::f(). We use a NULL object as the implied
2105 // object argument (C++ [over.call.func]p3).
2106 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2107 SuppressUserConversions, ForceRValue);
2108 return;
2109 }
2110 // We treat a constructor like a non-member function, since its object
2111 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002112 }
2113
2114
Douglas Gregord2baafd2008-10-21 16:13:35 +00002115 // Add this candidate
2116 CandidateSet.push_back(OverloadCandidate());
2117 OverloadCandidate& Candidate = CandidateSet.back();
2118 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002119 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002120 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002121 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002122
2123 unsigned NumArgsInProto = Proto->getNumArgs();
2124
2125 // (C++ 13.3.2p2): A candidate function having fewer than m
2126 // parameters is viable only if it has an ellipsis in its parameter
2127 // list (8.3.5).
2128 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2129 Candidate.Viable = false;
2130 return;
2131 }
2132
2133 // (C++ 13.3.2p2): A candidate function having more than m parameters
2134 // is viable only if the (m+1)st parameter has a default argument
2135 // (8.3.6). For the purposes of overload resolution, the
2136 // parameter list is truncated on the right, so that there are
2137 // exactly m parameters.
2138 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2139 if (NumArgs < MinRequiredArgs) {
2140 // Not enough arguments.
2141 Candidate.Viable = false;
2142 return;
2143 }
2144
2145 // Determine the implicit conversion sequences for each of the
2146 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002147 Candidate.Conversions.resize(NumArgs);
2148 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2149 if (ArgIdx < NumArgsInProto) {
2150 // (C++ 13.3.2p3): for F to be a viable function, there shall
2151 // exist for each argument an implicit conversion sequence
2152 // (13.3.3.1) that converts that argument to the corresponding
2153 // parameter of F.
2154 QualType ParamType = Proto->getArgType(ArgIdx);
2155 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002156 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002157 SuppressUserConversions, ForceRValue);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002158 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002159 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002160 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002161 break;
2162 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002163 } else {
2164 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2165 // argument for which there is no corresponding parameter is
2166 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2167 Candidate.Conversions[ArgIdx].ConversionKind
2168 = ImplicitConversionSequence::EllipsisConversion;
2169 }
2170 }
2171}
2172
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002173/// \brief Add all of the function declarations in the given function set to
2174/// the overload canddiate set.
2175void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2176 Expr **Args, unsigned NumArgs,
2177 OverloadCandidateSet& CandidateSet,
2178 bool SuppressUserConversions) {
2179 for (FunctionSet::const_iterator F = Functions.begin(),
2180 FEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00002181 F != FEnd; ++F) {
2182 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2183 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2184 SuppressUserConversions);
2185 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002186 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2187 /*FIXME: explicit args */false, 0, 0,
2188 Args, NumArgs, CandidateSet,
Douglas Gregor993a0602009-06-27 21:05:07 +00002189 SuppressUserConversions);
2190 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002191}
2192
Douglas Gregor5ed15042008-11-18 23:14:02 +00002193/// AddMethodCandidate - Adds the given C++ member function to the set
2194/// of candidate functions, using the given function call arguments
2195/// and the object argument (@c Object). For example, in a call
2196/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2197/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2198/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002199/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2200/// a slightly hacky way to implement the overloading rules for elidable copy
2201/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002202void
2203Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2204 Expr **Args, unsigned NumArgs,
2205 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002206 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002207{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002208 const FunctionProtoType* Proto
2209 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002210 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002211 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002212 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002213 assert(!isa<CXXConstructorDecl>(Method) &&
2214 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002215
2216 // Add this candidate
2217 CandidateSet.push_back(OverloadCandidate());
2218 OverloadCandidate& Candidate = CandidateSet.back();
2219 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002220 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002221 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002222
2223 unsigned NumArgsInProto = Proto->getNumArgs();
2224
2225 // (C++ 13.3.2p2): A candidate function having fewer than m
2226 // parameters is viable only if it has an ellipsis in its parameter
2227 // list (8.3.5).
2228 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2229 Candidate.Viable = false;
2230 return;
2231 }
2232
2233 // (C++ 13.3.2p2): A candidate function having more than m parameters
2234 // is viable only if the (m+1)st parameter has a default argument
2235 // (8.3.6). For the purposes of overload resolution, the
2236 // parameter list is truncated on the right, so that there are
2237 // exactly m parameters.
2238 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2239 if (NumArgs < MinRequiredArgs) {
2240 // Not enough arguments.
2241 Candidate.Viable = false;
2242 return;
2243 }
2244
2245 Candidate.Viable = true;
2246 Candidate.Conversions.resize(NumArgs + 1);
2247
Douglas Gregor3257fb52008-12-22 05:46:06 +00002248 if (Method->isStatic() || !Object)
2249 // The implicit object argument is ignored.
2250 Candidate.IgnoreObjectArgument = true;
2251 else {
2252 // Determine the implicit conversion sequence for the object
2253 // parameter.
2254 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2255 if (Candidate.Conversions[0].ConversionKind
2256 == ImplicitConversionSequence::BadConversion) {
2257 Candidate.Viable = false;
2258 return;
2259 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002260 }
2261
2262 // Determine the implicit conversion sequences for each of the
2263 // arguments.
2264 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2265 if (ArgIdx < NumArgsInProto) {
2266 // (C++ 13.3.2p3): for F to be a viable function, there shall
2267 // exist for each argument an implicit conversion sequence
2268 // (13.3.3.1) that converts that argument to the corresponding
2269 // parameter of F.
2270 QualType ParamType = Proto->getArgType(ArgIdx);
2271 Candidate.Conversions[ArgIdx + 1]
2272 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002273 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002274 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2275 == ImplicitConversionSequence::BadConversion) {
2276 Candidate.Viable = false;
2277 break;
2278 }
2279 } else {
2280 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2281 // argument for which there is no corresponding parameter is
2282 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2283 Candidate.Conversions[ArgIdx + 1].ConversionKind
2284 = ImplicitConversionSequence::EllipsisConversion;
2285 }
2286 }
2287}
2288
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002289/// \brief Add a C++ member function template as a candidate to the candidate
2290/// set, using template argument deduction to produce an appropriate member
2291/// function template specialization.
2292void
2293Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2294 bool HasExplicitTemplateArgs,
2295 const TemplateArgument *ExplicitTemplateArgs,
2296 unsigned NumExplicitTemplateArgs,
2297 Expr *Object, Expr **Args, unsigned NumArgs,
2298 OverloadCandidateSet& CandidateSet,
2299 bool SuppressUserConversions,
2300 bool ForceRValue) {
2301 // C++ [over.match.funcs]p7:
2302 // In each case where a candidate is a function template, candidate
2303 // function template specializations are generated using template argument
2304 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2305 // candidate functions in the usual way.113) A given name can refer to one
2306 // or more function templates and also to a set of overloaded non-template
2307 // functions. In such a case, the candidate functions generated from each
2308 // function template are combined with the set of non-template candidate
2309 // functions.
2310 TemplateDeductionInfo Info(Context);
2311 FunctionDecl *Specialization = 0;
2312 if (TemplateDeductionResult Result
2313 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2314 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2315 Args, NumArgs, Specialization, Info)) {
2316 // FIXME: Record what happened with template argument deduction, so
2317 // that we can give the user a beautiful diagnostic.
2318 (void)Result;
2319 return;
2320 }
2321
2322 // Add the function template specialization produced by template argument
2323 // deduction as a candidate.
2324 assert(Specialization && "Missing member function template specialization?");
2325 assert(isa<CXXMethodDecl>(Specialization) &&
2326 "Specialization is not a member function?");
2327 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2328 CandidateSet, SuppressUserConversions, ForceRValue);
2329}
2330
Douglas Gregor8c860df2009-08-21 23:19:43 +00002331/// \brief Add a C++ function template specialization as a candidate
2332/// in the candidate set, using template argument deduction to produce
2333/// an appropriate function template specialization.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002334void
2335Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002336 bool HasExplicitTemplateArgs,
2337 const TemplateArgument *ExplicitTemplateArgs,
2338 unsigned NumExplicitTemplateArgs,
Douglas Gregorb60eb752009-06-25 22:08:12 +00002339 Expr **Args, unsigned NumArgs,
2340 OverloadCandidateSet& CandidateSet,
2341 bool SuppressUserConversions,
2342 bool ForceRValue) {
2343 // C++ [over.match.funcs]p7:
2344 // In each case where a candidate is a function template, candidate
2345 // function template specializations are generated using template argument
2346 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2347 // candidate functions in the usual way.113) A given name can refer to one
2348 // or more function templates and also to a set of overloaded non-template
2349 // functions. In such a case, the candidate functions generated from each
2350 // function template are combined with the set of non-template candidate
2351 // functions.
2352 TemplateDeductionInfo Info(Context);
2353 FunctionDecl *Specialization = 0;
2354 if (TemplateDeductionResult Result
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002355 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2356 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2357 Args, NumArgs, Specialization, Info)) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00002358 // FIXME: Record what happened with template argument deduction, so
2359 // that we can give the user a beautiful diagnostic.
2360 (void)Result;
2361 return;
2362 }
2363
2364 // Add the function template specialization produced by template argument
2365 // deduction as a candidate.
2366 assert(Specialization && "Missing function template specialization?");
2367 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2368 SuppressUserConversions, ForceRValue);
2369}
2370
Douglas Gregor60714f92008-11-07 22:36:19 +00002371/// AddConversionCandidate - Add a C++ conversion function as a
2372/// candidate in the candidate set (C++ [over.match.conv],
2373/// C++ [over.match.copy]). From is the expression we're converting from,
2374/// and ToType is the type that we're eventually trying to convert to
2375/// (which may or may not be the same type as the type that the
2376/// conversion function produces).
2377void
2378Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2379 Expr *From, QualType ToType,
2380 OverloadCandidateSet& CandidateSet) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002381 assert(!Conversion->getDescribedFunctionTemplate() &&
2382 "Conversion function templates use AddTemplateConversionCandidate");
2383
Douglas Gregor60714f92008-11-07 22:36:19 +00002384 // Add this candidate
2385 CandidateSet.push_back(OverloadCandidate());
2386 OverloadCandidate& Candidate = CandidateSet.back();
2387 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002388 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002389 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002390 Candidate.FinalConversion.setAsIdentityConversion();
2391 Candidate.FinalConversion.FromTypePtr
2392 = Conversion->getConversionType().getAsOpaquePtr();
2393 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2394
Douglas Gregor5ed15042008-11-18 23:14:02 +00002395 // Determine the implicit conversion sequence for the implicit
2396 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002397 Candidate.Viable = true;
2398 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002399 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002400
Douglas Gregor60714f92008-11-07 22:36:19 +00002401 if (Candidate.Conversions[0].ConversionKind
2402 == ImplicitConversionSequence::BadConversion) {
2403 Candidate.Viable = false;
2404 return;
2405 }
2406
2407 // To determine what the conversion from the result of calling the
2408 // conversion function to the type we're eventually trying to
2409 // convert to (ToType), we need to synthesize a call to the
2410 // conversion function and attempt copy initialization from it. This
2411 // makes sure that we get the right semantics with respect to
2412 // lvalues/rvalues and the type. Fortunately, we can allocate this
2413 // call on the stack and we don't need its arguments to be
2414 // well-formed.
2415 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2416 SourceLocation());
2417 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002418 CastExpr::CK_Unknown,
Douglas Gregor70d26122008-11-12 17:17:38 +00002419 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002420
2421 // Note that it is safe to allocate CallExpr on the stack here because
2422 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2423 // allocator).
2424 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002425 Conversion->getConversionType().getNonReferenceType(),
2426 SourceLocation());
2427 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2428 switch (ICS.ConversionKind) {
2429 case ImplicitConversionSequence::StandardConversion:
2430 Candidate.FinalConversion = ICS.Standard;
2431 break;
2432
2433 case ImplicitConversionSequence::BadConversion:
2434 Candidate.Viable = false;
2435 break;
2436
2437 default:
2438 assert(false &&
2439 "Can only end up with a standard conversion sequence or failure");
2440 }
2441}
2442
Douglas Gregor8c860df2009-08-21 23:19:43 +00002443/// \brief Adds a conversion function template specialization
2444/// candidate to the overload set, using template argument deduction
2445/// to deduce the template arguments of the conversion function
2446/// template from the type that we are converting to (C++
2447/// [temp.deduct.conv]).
2448void
2449Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2450 Expr *From, QualType ToType,
2451 OverloadCandidateSet &CandidateSet) {
2452 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2453 "Only conversion function templates permitted here");
2454
2455 TemplateDeductionInfo Info(Context);
2456 CXXConversionDecl *Specialization = 0;
2457 if (TemplateDeductionResult Result
2458 = DeduceTemplateArguments(FunctionTemplate, ToType,
2459 Specialization, Info)) {
2460 // FIXME: Record what happened with template argument deduction, so
2461 // that we can give the user a beautiful diagnostic.
2462 (void)Result;
2463 return;
2464 }
2465
2466 // Add the conversion function template specialization produced by
2467 // template argument deduction as a candidate.
2468 assert(Specialization && "Missing function template specialization?");
2469 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2470}
2471
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002472/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2473/// converts the given @c Object to a function pointer via the
2474/// conversion function @c Conversion, and then attempts to call it
2475/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2476/// the type of function that we'll eventually be calling.
2477void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002478 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002479 Expr *Object, Expr **Args, unsigned NumArgs,
2480 OverloadCandidateSet& CandidateSet) {
2481 CandidateSet.push_back(OverloadCandidate());
2482 OverloadCandidate& Candidate = CandidateSet.back();
2483 Candidate.Function = 0;
2484 Candidate.Surrogate = Conversion;
2485 Candidate.Viable = true;
2486 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002487 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002488 Candidate.Conversions.resize(NumArgs + 1);
2489
2490 // Determine the implicit conversion sequence for the implicit
2491 // object parameter.
2492 ImplicitConversionSequence ObjectInit
2493 = TryObjectArgumentInitialization(Object, Conversion);
2494 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2495 Candidate.Viable = false;
2496 return;
2497 }
2498
2499 // The first conversion is actually a user-defined conversion whose
2500 // first conversion is ObjectInit's standard conversion (which is
2501 // effectively a reference binding). Record it as such.
2502 Candidate.Conversions[0].ConversionKind
2503 = ImplicitConversionSequence::UserDefinedConversion;
2504 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2505 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2506 Candidate.Conversions[0].UserDefined.After
2507 = Candidate.Conversions[0].UserDefined.Before;
2508 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2509
2510 // Find the
2511 unsigned NumArgsInProto = Proto->getNumArgs();
2512
2513 // (C++ 13.3.2p2): A candidate function having fewer than m
2514 // parameters is viable only if it has an ellipsis in its parameter
2515 // list (8.3.5).
2516 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2517 Candidate.Viable = false;
2518 return;
2519 }
2520
2521 // Function types don't have any default arguments, so just check if
2522 // we have enough arguments.
2523 if (NumArgs < NumArgsInProto) {
2524 // Not enough arguments.
2525 Candidate.Viable = false;
2526 return;
2527 }
2528
2529 // Determine the implicit conversion sequences for each of the
2530 // arguments.
2531 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2532 if (ArgIdx < NumArgsInProto) {
2533 // (C++ 13.3.2p3): for F to be a viable function, there shall
2534 // exist for each argument an implicit conversion sequence
2535 // (13.3.3.1) that converts that argument to the corresponding
2536 // parameter of F.
2537 QualType ParamType = Proto->getArgType(ArgIdx);
2538 Candidate.Conversions[ArgIdx + 1]
2539 = TryCopyInitialization(Args[ArgIdx], ParamType,
2540 /*SuppressUserConversions=*/false);
2541 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2542 == ImplicitConversionSequence::BadConversion) {
2543 Candidate.Viable = false;
2544 break;
2545 }
2546 } else {
2547 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2548 // argument for which there is no corresponding parameter is
2549 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2550 Candidate.Conversions[ArgIdx + 1].ConversionKind
2551 = ImplicitConversionSequence::EllipsisConversion;
2552 }
2553 }
2554}
2555
Mike Stumpe127ae32009-05-16 07:39:55 +00002556// FIXME: This will eventually be removed, once we've migrated all of the
2557// operator overloading logic over to the scheme used by binary operators, which
2558// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002559void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002560 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002561 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002562 OverloadCandidateSet& CandidateSet,
2563 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002564
2565 FunctionSet Functions;
2566
2567 QualType T1 = Args[0]->getType();
2568 QualType T2;
2569 if (NumArgs > 1)
2570 T2 = Args[1]->getType();
2571
2572 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002573 if (S)
2574 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002575 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2576 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2577 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2578 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2579}
2580
2581/// \brief Add overload candidates for overloaded operators that are
2582/// member functions.
2583///
2584/// Add the overloaded operator candidates that are member functions
2585/// for the operator Op that was used in an operator expression such
2586/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2587/// CandidateSet will store the added overload candidates. (C++
2588/// [over.match.oper]).
2589void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2590 SourceLocation OpLoc,
2591 Expr **Args, unsigned NumArgs,
2592 OverloadCandidateSet& CandidateSet,
2593 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002594 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2595
2596 // C++ [over.match.oper]p3:
2597 // For a unary operator @ with an operand of a type whose
2598 // cv-unqualified version is T1, and for a binary operator @ with
2599 // a left operand of a type whose cv-unqualified version is T1 and
2600 // a right operand of a type whose cv-unqualified version is T2,
2601 // three sets of candidate functions, designated member
2602 // candidates, non-member candidates and built-in candidates, are
2603 // constructed as follows:
2604 QualType T1 = Args[0]->getType();
2605 QualType T2;
2606 if (NumArgs > 1)
2607 T2 = Args[1]->getType();
2608
2609 // -- If T1 is a class type, the set of member candidates is the
2610 // result of the qualified lookup of T1::operator@
2611 // (13.3.1.1.1); otherwise, the set of member candidates is
2612 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002613 // FIXME: Lookup in base classes, too!
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002614 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002615 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002616 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002617 Oper != OperEnd; ++Oper)
2618 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2619 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002620 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002621 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002622}
2623
Douglas Gregor70d26122008-11-12 17:17:38 +00002624/// AddBuiltinCandidate - Add a candidate for a built-in
2625/// operator. ResultTy and ParamTys are the result and parameter types
2626/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002627/// arguments being passed to the candidate. IsAssignmentOperator
2628/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002629/// operator. NumContextualBoolArguments is the number of arguments
2630/// (at the beginning of the argument list) that will be contextually
2631/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002632void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2633 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002634 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002635 bool IsAssignmentOperator,
2636 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002637 // Add this candidate
2638 CandidateSet.push_back(OverloadCandidate());
2639 OverloadCandidate& Candidate = CandidateSet.back();
2640 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002641 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002642 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002643 Candidate.BuiltinTypes.ResultTy = ResultTy;
2644 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2645 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2646
2647 // Determine the implicit conversion sequences for each of the
2648 // arguments.
2649 Candidate.Viable = true;
2650 Candidate.Conversions.resize(NumArgs);
2651 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002652 // C++ [over.match.oper]p4:
2653 // For the built-in assignment operators, conversions of the
2654 // left operand are restricted as follows:
2655 // -- no temporaries are introduced to hold the left operand, and
2656 // -- no user-defined conversions are applied to the left
2657 // operand to achieve a type match with the left-most
2658 // parameter of a built-in candidate.
2659 //
2660 // We block these conversions by turning off user-defined
2661 // conversions, since that is the only way that initialization of
2662 // a reference to a non-class type can occur from something that
2663 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002664 if (ArgIdx < NumContextualBoolArguments) {
2665 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2666 "Contextual conversion to bool requires bool type");
2667 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2668 } else {
2669 Candidate.Conversions[ArgIdx]
2670 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2671 ArgIdx == 0 && IsAssignmentOperator);
2672 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002673 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002674 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002675 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002676 break;
2677 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002678 }
2679}
2680
2681/// BuiltinCandidateTypeSet - A set of types that will be used for the
2682/// candidate operator functions for built-in operators (C++
2683/// [over.built]). The types are separated into pointer types and
2684/// enumeration types.
2685class BuiltinCandidateTypeSet {
2686 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002687 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002688
2689 /// PointerTypes - The set of pointer types that will be used in the
2690 /// built-in candidates.
2691 TypeSet PointerTypes;
2692
Sebastian Redl674d1b72009-04-19 21:53:20 +00002693 /// MemberPointerTypes - The set of member pointer types that will be
2694 /// used in the built-in candidates.
2695 TypeSet MemberPointerTypes;
2696
Douglas Gregor70d26122008-11-12 17:17:38 +00002697 /// EnumerationTypes - The set of enumeration types that will be
2698 /// used in the built-in candidates.
2699 TypeSet EnumerationTypes;
2700
2701 /// Context - The AST context in which we will build the type sets.
2702 ASTContext &Context;
2703
Sebastian Redl674d1b72009-04-19 21:53:20 +00002704 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2705 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002706
2707public:
2708 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002709 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002710
2711 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2712
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002713 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2714 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002715
2716 /// pointer_begin - First pointer type found;
2717 iterator pointer_begin() { return PointerTypes.begin(); }
2718
Sebastian Redl674d1b72009-04-19 21:53:20 +00002719 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002720 iterator pointer_end() { return PointerTypes.end(); }
2721
Sebastian Redl674d1b72009-04-19 21:53:20 +00002722 /// member_pointer_begin - First member pointer type found;
2723 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2724
2725 /// member_pointer_end - Past the last member pointer type found;
2726 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2727
Douglas Gregor70d26122008-11-12 17:17:38 +00002728 /// enumeration_begin - First enumeration type found;
2729 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2730
Sebastian Redl674d1b72009-04-19 21:53:20 +00002731 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002732 iterator enumeration_end() { return EnumerationTypes.end(); }
2733};
2734
Sebastian Redl674d1b72009-04-19 21:53:20 +00002735/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002736/// the set of pointer types along with any more-qualified variants of
2737/// that type. For example, if @p Ty is "int const *", this routine
2738/// will add "int const *", "int const volatile *", "int const
2739/// restrict *", and "int const volatile restrict *" to the set of
2740/// pointer types. Returns true if the add of @p Ty itself succeeded,
2741/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002742bool
2743BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002744 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002745 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002746 return false;
2747
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002748 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002749 QualType PointeeTy = PointerTy->getPointeeType();
2750 // FIXME: Optimize this so that we don't keep trying to add the same types.
2751
Mike Stumpe127ae32009-05-16 07:39:55 +00002752 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2753 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002754 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002755 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002756 (Context.getPointerType(PointeeTy.withConst()));
2757 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002758 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002759 (Context.getPointerType(PointeeTy.withVolatile()));
2760 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002761 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002762 (Context.getPointerType(PointeeTy.withRestrict()));
2763 }
2764
2765 return true;
2766}
2767
Sebastian Redl674d1b72009-04-19 21:53:20 +00002768/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2769/// to the set of pointer types along with any more-qualified variants of
2770/// that type. For example, if @p Ty is "int const *", this routine
2771/// will add "int const *", "int const volatile *", "int const
2772/// restrict *", and "int const volatile restrict *" to the set of
2773/// pointer types. Returns true if the add of @p Ty itself succeeded,
2774/// false otherwise.
2775bool
2776BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2777 QualType Ty) {
2778 // Insert this type.
2779 if (!MemberPointerTypes.insert(Ty))
2780 return false;
2781
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002782 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl674d1b72009-04-19 21:53:20 +00002783 QualType PointeeTy = PointerTy->getPointeeType();
2784 const Type *ClassTy = PointerTy->getClass();
2785 // FIXME: Optimize this so that we don't keep trying to add the same types.
2786
2787 if (!PointeeTy.isConstQualified())
2788 AddMemberPointerWithMoreQualifiedTypeVariants
2789 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2790 if (!PointeeTy.isVolatileQualified())
2791 AddMemberPointerWithMoreQualifiedTypeVariants
2792 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2793 if (!PointeeTy.isRestrictQualified())
2794 AddMemberPointerWithMoreQualifiedTypeVariants
2795 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2796 }
2797
2798 return true;
2799}
2800
Douglas Gregor70d26122008-11-12 17:17:38 +00002801/// AddTypesConvertedFrom - Add each of the types to which the type @p
2802/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002803/// primarily interested in pointer types and enumeration types. We also
2804/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002805/// AllowUserConversions is true if we should look at the conversion
2806/// functions of a class type, and AllowExplicitConversions if we
2807/// should also include the explicit conversion functions of a class
2808/// type.
2809void
2810BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2811 bool AllowUserConversions,
2812 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002813 // Only deal with canonical types.
2814 Ty = Context.getCanonicalType(Ty);
2815
2816 // Look through reference types; they aren't part of the type of an
2817 // expression for the purposes of conversions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002818 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregor70d26122008-11-12 17:17:38 +00002819 Ty = RefTy->getPointeeType();
2820
2821 // We don't care about qualifiers on the type.
2822 Ty = Ty.getUnqualifiedType();
2823
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002824 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002825 QualType PointeeTy = PointerTy->getPointeeType();
2826
2827 // Insert our type, and its more-qualified variants, into the set
2828 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002829 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002830 return;
2831
2832 // Add 'cv void*' to our set of types.
2833 if (!Ty->isVoidType()) {
2834 QualType QualVoid
2835 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002836 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002837 }
2838
2839 // If this is a pointer to a class type, add pointers to its bases
2840 // (with the same level of cv-qualification as the original
2841 // derived class, of course).
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002842 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002843 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2844 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2845 Base != ClassDecl->bases_end(); ++Base) {
2846 QualType BaseTy = Context.getCanonicalType(Base->getType());
2847 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2848
2849 // Add the pointer type, recursively, so that we get all of
2850 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002851 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002852 }
2853 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002854 } else if (Ty->isMemberPointerType()) {
2855 // Member pointers are far easier, since the pointee can't be converted.
2856 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2857 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002858 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002859 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002860 } else if (AllowUserConversions) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002861 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002862 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2863 // FIXME: Visit conversion functions in the base classes, too.
2864 OverloadedFunctionDecl *Conversions
2865 = ClassDecl->getConversionFunctions();
2866 for (OverloadedFunctionDecl::function_iterator Func
2867 = Conversions->function_begin();
2868 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002869 CXXConversionDecl *Conv;
2870 FunctionTemplateDecl *ConvTemplate;
2871 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2872
2873 // Skip conversion function templates; they don't tell us anything
2874 // about which builtin types we can convert to.
2875 if (ConvTemplate)
2876 continue;
2877
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002878 if (AllowExplicitConversions || !Conv->isExplicit())
2879 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002880 }
2881 }
2882 }
2883}
2884
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002885/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2886/// operator overloads to the candidate set (C++ [over.built]), based
2887/// on the operator @p Op and the arguments given. For example, if the
2888/// operator is a binary '+', this routine might add "int
2889/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002890void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002891Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2892 Expr **Args, unsigned NumArgs,
2893 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002894 // The set of "promoted arithmetic types", which are the arithmetic
2895 // types are that preserved by promotion (C++ [over.built]p2). Note
2896 // that the first few of these types are the promoted integral
2897 // types; these types need to be first.
2898 // FIXME: What about complex?
2899 const unsigned FirstIntegralType = 0;
2900 const unsigned LastIntegralType = 13;
2901 const unsigned FirstPromotedIntegralType = 7,
2902 LastPromotedIntegralType = 13;
2903 const unsigned FirstPromotedArithmeticType = 7,
2904 LastPromotedArithmeticType = 16;
2905 const unsigned NumArithmeticTypes = 16;
2906 QualType ArithmeticTypes[NumArithmeticTypes] = {
Alisdair Meredith2bcacb62009-07-14 06:30:34 +00002907 Context.BoolTy, Context.CharTy, Context.WCharTy,
2908// Context.Char16Ty, Context.Char32Ty,
Douglas Gregor70d26122008-11-12 17:17:38 +00002909 Context.SignedCharTy, Context.ShortTy,
2910 Context.UnsignedCharTy, Context.UnsignedShortTy,
2911 Context.IntTy, Context.LongTy, Context.LongLongTy,
2912 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2913 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2914 };
2915
2916 // Find all of the types that the arguments can convert to, but only
2917 // if the operator we're looking at has built-in operator candidates
2918 // that make use of these types.
2919 BuiltinCandidateTypeSet CandidateTypes(Context);
2920 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2921 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002922 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002923 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002924 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00002925 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002926 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002927 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2928 true,
2929 (Op == OO_Exclaim ||
2930 Op == OO_AmpAmp ||
2931 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002932 }
2933
2934 bool isComparison = false;
2935 switch (Op) {
2936 case OO_None:
2937 case NUM_OVERLOADED_OPERATORS:
2938 assert(false && "Expected an overloaded operator");
2939 break;
2940
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002941 case OO_Star: // '*' is either unary or binary
2942 if (NumArgs == 1)
2943 goto UnaryStar;
2944 else
2945 goto BinaryStar;
2946 break;
2947
2948 case OO_Plus: // '+' is either unary or binary
2949 if (NumArgs == 1)
2950 goto UnaryPlus;
2951 else
2952 goto BinaryPlus;
2953 break;
2954
2955 case OO_Minus: // '-' is either unary or binary
2956 if (NumArgs == 1)
2957 goto UnaryMinus;
2958 else
2959 goto BinaryMinus;
2960 break;
2961
2962 case OO_Amp: // '&' is either unary or binary
2963 if (NumArgs == 1)
2964 goto UnaryAmp;
2965 else
2966 goto BinaryAmp;
2967
2968 case OO_PlusPlus:
2969 case OO_MinusMinus:
2970 // C++ [over.built]p3:
2971 //
2972 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2973 // is either volatile or empty, there exist candidate operator
2974 // functions of the form
2975 //
2976 // VQ T& operator++(VQ T&);
2977 // T operator++(VQ T&, int);
2978 //
2979 // C++ [over.built]p4:
2980 //
2981 // For every pair (T, VQ), where T is an arithmetic type other
2982 // than bool, and VQ is either volatile or empty, there exist
2983 // candidate operator functions of the form
2984 //
2985 // VQ T& operator--(VQ T&);
2986 // T operator--(VQ T&, int);
2987 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2988 Arith < NumArithmeticTypes; ++Arith) {
2989 QualType ArithTy = ArithmeticTypes[Arith];
2990 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00002991 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002992
2993 // Non-volatile version.
2994 if (NumArgs == 1)
2995 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2996 else
2997 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2998
2999 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003000 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003001 if (NumArgs == 1)
3002 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3003 else
3004 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3005 }
3006
3007 // C++ [over.built]p5:
3008 //
3009 // For every pair (T, VQ), where T is a cv-qualified or
3010 // cv-unqualified object type, and VQ is either volatile or
3011 // empty, there exist candidate operator functions of the form
3012 //
3013 // T*VQ& operator++(T*VQ&);
3014 // T*VQ& operator--(T*VQ&);
3015 // T* operator++(T*VQ&, int);
3016 // T* operator--(T*VQ&, int);
3017 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3018 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3019 // Skip pointer types that aren't pointers to object types.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003020 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003021 continue;
3022
3023 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003024 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003025 };
3026
3027 // Without volatile
3028 if (NumArgs == 1)
3029 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3030 else
3031 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3032
3033 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3034 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00003035 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003036 if (NumArgs == 1)
3037 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3038 else
3039 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3040 }
3041 }
3042 break;
3043
3044 UnaryStar:
3045 // C++ [over.built]p6:
3046 // For every cv-qualified or cv-unqualified object type T, there
3047 // exist candidate operator functions of the form
3048 //
3049 // T& operator*(T*);
3050 //
3051 // C++ [over.built]p7:
3052 // For every function type T, there exist candidate operator
3053 // functions of the form
3054 // T& operator*(T*);
3055 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3056 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3057 QualType ParamTy = *Ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003058 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003059 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003060 &ParamTy, Args, 1, CandidateSet);
3061 }
3062 break;
3063
3064 UnaryPlus:
3065 // C++ [over.built]p8:
3066 // For every type T, there exist candidate operator functions of
3067 // the form
3068 //
3069 // T* operator+(T*);
3070 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3071 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3072 QualType ParamTy = *Ptr;
3073 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3074 }
3075
3076 // Fall through
3077
3078 UnaryMinus:
3079 // C++ [over.built]p9:
3080 // For every promoted arithmetic type T, there exist candidate
3081 // operator functions of the form
3082 //
3083 // T operator+(T);
3084 // T operator-(T);
3085 for (unsigned Arith = FirstPromotedArithmeticType;
3086 Arith < LastPromotedArithmeticType; ++Arith) {
3087 QualType ArithTy = ArithmeticTypes[Arith];
3088 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3089 }
3090 break;
3091
3092 case OO_Tilde:
3093 // C++ [over.built]p10:
3094 // For every promoted integral type T, there exist candidate
3095 // operator functions of the form
3096 //
3097 // T operator~(T);
3098 for (unsigned Int = FirstPromotedIntegralType;
3099 Int < LastPromotedIntegralType; ++Int) {
3100 QualType IntTy = ArithmeticTypes[Int];
3101 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3102 }
3103 break;
3104
Douglas Gregor70d26122008-11-12 17:17:38 +00003105 case OO_New:
3106 case OO_Delete:
3107 case OO_Array_New:
3108 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00003109 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003110 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00003111 break;
3112
3113 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003114 UnaryAmp:
3115 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00003116 // C++ [over.match.oper]p3:
3117 // -- For the operator ',', the unary operator '&', or the
3118 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00003119 break;
3120
3121 case OO_Less:
3122 case OO_Greater:
3123 case OO_LessEqual:
3124 case OO_GreaterEqual:
3125 case OO_EqualEqual:
3126 case OO_ExclaimEqual:
3127 // C++ [over.built]p15:
3128 //
3129 // For every pointer or enumeration type T, there exist
3130 // candidate operator functions of the form
3131 //
3132 // bool operator<(T, T);
3133 // bool operator>(T, T);
3134 // bool operator<=(T, T);
3135 // bool operator>=(T, T);
3136 // bool operator==(T, T);
3137 // bool operator!=(T, T);
3138 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3139 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3140 QualType ParamTypes[2] = { *Ptr, *Ptr };
3141 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3142 }
3143 for (BuiltinCandidateTypeSet::iterator Enum
3144 = CandidateTypes.enumeration_begin();
3145 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3146 QualType ParamTypes[2] = { *Enum, *Enum };
3147 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3148 }
3149
3150 // Fall through.
3151 isComparison = true;
3152
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003153 BinaryPlus:
3154 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003155 if (!isComparison) {
3156 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3157
3158 // C++ [over.built]p13:
3159 //
3160 // For every cv-qualified or cv-unqualified object type T
3161 // there exist candidate operator functions of the form
3162 //
3163 // T* operator+(T*, ptrdiff_t);
3164 // T& operator[](T*, ptrdiff_t); [BELOW]
3165 // T* operator-(T*, ptrdiff_t);
3166 // T* operator+(ptrdiff_t, T*);
3167 // T& operator[](ptrdiff_t, T*); [BELOW]
3168 //
3169 // C++ [over.built]p14:
3170 //
3171 // For every T, where T is a pointer to object type, there
3172 // exist candidate operator functions of the form
3173 //
3174 // ptrdiff_t operator-(T, T);
3175 for (BuiltinCandidateTypeSet::iterator Ptr
3176 = CandidateTypes.pointer_begin();
3177 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3178 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3179
3180 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3181 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3182
3183 if (Op == OO_Plus) {
3184 // T* operator+(ptrdiff_t, T*);
3185 ParamTypes[0] = ParamTypes[1];
3186 ParamTypes[1] = *Ptr;
3187 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3188 } else {
3189 // ptrdiff_t operator-(T, T);
3190 ParamTypes[1] = *Ptr;
3191 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3192 Args, 2, CandidateSet);
3193 }
3194 }
3195 }
3196 // Fall through
3197
Douglas Gregor70d26122008-11-12 17:17:38 +00003198 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003199 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003200 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003201 // C++ [over.built]p12:
3202 //
3203 // For every pair of promoted arithmetic types L and R, there
3204 // exist candidate operator functions of the form
3205 //
3206 // LR operator*(L, R);
3207 // LR operator/(L, R);
3208 // LR operator+(L, R);
3209 // LR operator-(L, R);
3210 // bool operator<(L, R);
3211 // bool operator>(L, R);
3212 // bool operator<=(L, R);
3213 // bool operator>=(L, R);
3214 // bool operator==(L, R);
3215 // bool operator!=(L, R);
3216 //
3217 // where LR is the result of the usual arithmetic conversions
3218 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003219 //
3220 // C++ [over.built]p24:
3221 //
3222 // For every pair of promoted arithmetic types L and R, there exist
3223 // candidate operator functions of the form
3224 //
3225 // LR operator?(bool, L, R);
3226 //
3227 // where LR is the result of the usual arithmetic conversions
3228 // between types L and R.
3229 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003230 for (unsigned Left = FirstPromotedArithmeticType;
3231 Left < LastPromotedArithmeticType; ++Left) {
3232 for (unsigned Right = FirstPromotedArithmeticType;
3233 Right < LastPromotedArithmeticType; ++Right) {
3234 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman6ae7d112009-08-19 07:44:53 +00003235 QualType Result
3236 = isComparison
3237 ? Context.BoolTy
3238 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003239 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3240 }
3241 }
3242 break;
3243
3244 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003245 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003246 case OO_Caret:
3247 case OO_Pipe:
3248 case OO_LessLess:
3249 case OO_GreaterGreater:
3250 // C++ [over.built]p17:
3251 //
3252 // For every pair of promoted integral types L and R, there
3253 // exist candidate operator functions of the form
3254 //
3255 // LR operator%(L, R);
3256 // LR operator&(L, R);
3257 // LR operator^(L, R);
3258 // LR operator|(L, R);
3259 // L operator<<(L, R);
3260 // L operator>>(L, R);
3261 //
3262 // where LR is the result of the usual arithmetic conversions
3263 // between types L and R.
3264 for (unsigned Left = FirstPromotedIntegralType;
3265 Left < LastPromotedIntegralType; ++Left) {
3266 for (unsigned Right = FirstPromotedIntegralType;
3267 Right < LastPromotedIntegralType; ++Right) {
3268 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3269 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3270 ? LandR[0]
Eli Friedman6ae7d112009-08-19 07:44:53 +00003271 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003272 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3273 }
3274 }
3275 break;
3276
3277 case OO_Equal:
3278 // C++ [over.built]p20:
3279 //
3280 // For every pair (T, VQ), where T is an enumeration or
3281 // (FIXME:) pointer to member type and VQ is either volatile or
3282 // empty, there exist candidate operator functions of the form
3283 //
3284 // VQ T& operator=(VQ T&, T);
3285 for (BuiltinCandidateTypeSet::iterator Enum
3286 = CandidateTypes.enumeration_begin();
3287 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3288 QualType ParamTypes[2];
3289
3290 // T& operator=(T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003291 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregor70d26122008-11-12 17:17:38 +00003292 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003293 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003294 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003295
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003296 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3297 // volatile T& operator=(volatile T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003298 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003299 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003300 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003301 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003302 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003303 }
3304 // Fall through.
3305
3306 case OO_PlusEqual:
3307 case OO_MinusEqual:
3308 // C++ [over.built]p19:
3309 //
3310 // For every pair (T, VQ), where T is any type and VQ is either
3311 // volatile or empty, there exist candidate operator functions
3312 // of the form
3313 //
3314 // T*VQ& operator=(T*VQ&, T*);
3315 //
3316 // C++ [over.built]p21:
3317 //
3318 // For every pair (T, VQ), where T is a cv-qualified or
3319 // cv-unqualified object type and VQ is either volatile or
3320 // empty, there exist candidate operator functions of the form
3321 //
3322 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3323 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3324 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3325 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3326 QualType ParamTypes[2];
3327 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3328
3329 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003330 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003331 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3332 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003333
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003334 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3335 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003336 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003337 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3338 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003339 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003340 }
3341 // Fall through.
3342
3343 case OO_StarEqual:
3344 case OO_SlashEqual:
3345 // C++ [over.built]p18:
3346 //
3347 // For every triple (L, VQ, R), where L is an arithmetic type,
3348 // VQ is either volatile or empty, and R is a promoted
3349 // arithmetic type, there exist candidate operator functions of
3350 // the form
3351 //
3352 // VQ L& operator=(VQ L&, R);
3353 // VQ L& operator*=(VQ L&, R);
3354 // VQ L& operator/=(VQ L&, R);
3355 // VQ L& operator+=(VQ L&, R);
3356 // VQ L& operator-=(VQ L&, R);
3357 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3358 for (unsigned Right = FirstPromotedArithmeticType;
3359 Right < LastPromotedArithmeticType; ++Right) {
3360 QualType ParamTypes[2];
3361 ParamTypes[1] = ArithmeticTypes[Right];
3362
3363 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003364 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003365 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3366 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003367
3368 // Add this built-in operator as a candidate (VQ is 'volatile').
3369 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003370 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003371 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3372 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003373 }
3374 }
3375 break;
3376
3377 case OO_PercentEqual:
3378 case OO_LessLessEqual:
3379 case OO_GreaterGreaterEqual:
3380 case OO_AmpEqual:
3381 case OO_CaretEqual:
3382 case OO_PipeEqual:
3383 // C++ [over.built]p22:
3384 //
3385 // For every triple (L, VQ, R), where L is an integral type, VQ
3386 // is either volatile or empty, and R is a promoted integral
3387 // type, there exist candidate operator functions of the form
3388 //
3389 // VQ L& operator%=(VQ L&, R);
3390 // VQ L& operator<<=(VQ L&, R);
3391 // VQ L& operator>>=(VQ L&, R);
3392 // VQ L& operator&=(VQ L&, R);
3393 // VQ L& operator^=(VQ L&, R);
3394 // VQ L& operator|=(VQ L&, R);
3395 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3396 for (unsigned Right = FirstPromotedIntegralType;
3397 Right < LastPromotedIntegralType; ++Right) {
3398 QualType ParamTypes[2];
3399 ParamTypes[1] = ArithmeticTypes[Right];
3400
3401 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003402 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003403 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3404
3405 // Add this built-in operator as a candidate (VQ is 'volatile').
3406 ParamTypes[0] = ArithmeticTypes[Left];
3407 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003408 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003409 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3410 }
3411 }
3412 break;
3413
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003414 case OO_Exclaim: {
3415 // C++ [over.operator]p23:
3416 //
3417 // There also exist candidate operator functions of the form
3418 //
3419 // bool operator!(bool);
3420 // bool operator&&(bool, bool); [BELOW]
3421 // bool operator||(bool, bool); [BELOW]
3422 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003423 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3424 /*IsAssignmentOperator=*/false,
3425 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003426 break;
3427 }
3428
Douglas Gregor70d26122008-11-12 17:17:38 +00003429 case OO_AmpAmp:
3430 case OO_PipePipe: {
3431 // C++ [over.operator]p23:
3432 //
3433 // There also exist candidate operator functions of the form
3434 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003435 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003436 // bool operator&&(bool, bool);
3437 // bool operator||(bool, bool);
3438 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003439 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3440 /*IsAssignmentOperator=*/false,
3441 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003442 break;
3443 }
3444
3445 case OO_Subscript:
3446 // C++ [over.built]p13:
3447 //
3448 // For every cv-qualified or cv-unqualified object type T there
3449 // exist candidate operator functions of the form
3450 //
3451 // T* operator+(T*, ptrdiff_t); [ABOVE]
3452 // T& operator[](T*, ptrdiff_t);
3453 // T* operator-(T*, ptrdiff_t); [ABOVE]
3454 // T* operator+(ptrdiff_t, T*); [ABOVE]
3455 // T& operator[](ptrdiff_t, T*);
3456 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3457 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3458 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003459 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003460 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003461
3462 // T& operator[](T*, ptrdiff_t)
3463 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3464
3465 // T& operator[](ptrdiff_t, T*);
3466 ParamTypes[0] = ParamTypes[1];
3467 ParamTypes[1] = *Ptr;
3468 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3469 }
3470 break;
3471
3472 case OO_ArrowStar:
3473 // FIXME: No support for pointer-to-members yet.
3474 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003475
3476 case OO_Conditional:
3477 // Note that we don't consider the first argument, since it has been
3478 // contextually converted to bool long ago. The candidates below are
3479 // therefore added as binary.
3480 //
3481 // C++ [over.built]p24:
3482 // For every type T, where T is a pointer or pointer-to-member type,
3483 // there exist candidate operator functions of the form
3484 //
3485 // T operator?(bool, T, T);
3486 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003487 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3488 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3489 QualType ParamTypes[2] = { *Ptr, *Ptr };
3490 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3491 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003492 for (BuiltinCandidateTypeSet::iterator Ptr =
3493 CandidateTypes.member_pointer_begin(),
3494 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3495 QualType ParamTypes[2] = { *Ptr, *Ptr };
3496 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3497 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003498 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003499 }
3500}
3501
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003502/// \brief Add function candidates found via argument-dependent lookup
3503/// to the set of overloading candidates.
3504///
3505/// This routine performs argument-dependent name lookup based on the
3506/// given function name (which may also be an operator name) and adds
3507/// all of the overload candidates found by ADL to the overload
3508/// candidate set (C++ [basic.lookup.argdep]).
3509void
3510Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3511 Expr **Args, unsigned NumArgs,
3512 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003513 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003514
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003515 // Record all of the function candidates that we've already
3516 // added to the overload set, so that we don't add those same
3517 // candidates a second time.
3518 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3519 CandEnd = CandidateSet.end();
3520 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003521 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003522 Functions.insert(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003523 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3524 Functions.insert(FunTmpl);
3525 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003526
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003527 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003528
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003529 // Erase all of the candidates we already knew about.
3530 // FIXME: This is suboptimal. Is there a better way?
3531 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3532 CandEnd = CandidateSet.end();
3533 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003534 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003535 Functions.erase(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003536 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3537 Functions.erase(FunTmpl);
3538 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003539
3540 // For each of the ADL candidates we found, add it to the overload
3541 // set.
3542 for (FunctionSet::iterator Func = Functions.begin(),
3543 FuncEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00003544 Func != FuncEnd; ++Func) {
3545 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3546 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3547 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003548 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3549 /*FIXME: explicit args */false, 0, 0,
3550 Args, NumArgs, CandidateSet);
Douglas Gregor993a0602009-06-27 21:05:07 +00003551 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003552}
3553
Douglas Gregord2baafd2008-10-21 16:13:35 +00003554/// isBetterOverloadCandidate - Determines whether the first overload
3555/// candidate is a better candidate than the second (C++ 13.3.3p1).
3556bool
3557Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3558 const OverloadCandidate& Cand2)
3559{
3560 // Define viable functions to be better candidates than non-viable
3561 // functions.
3562 if (!Cand2.Viable)
3563 return Cand1.Viable;
3564 else if (!Cand1.Viable)
3565 return false;
3566
Douglas Gregor3257fb52008-12-22 05:46:06 +00003567 // C++ [over.match.best]p1:
3568 //
3569 // -- if F is a static member function, ICS1(F) is defined such
3570 // that ICS1(F) is neither better nor worse than ICS1(G) for
3571 // any function G, and, symmetrically, ICS1(G) is neither
3572 // better nor worse than ICS1(F).
3573 unsigned StartArg = 0;
3574 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3575 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003576
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003577 // C++ [over.match.best]p1:
3578 // A viable function F1 is defined to be a better function than another
3579 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3580 // conversion sequence than ICSi(F2), and then...
Douglas Gregord2baafd2008-10-21 16:13:35 +00003581 unsigned NumArgs = Cand1.Conversions.size();
3582 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3583 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003584 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003585 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3586 Cand2.Conversions[ArgIdx])) {
3587 case ImplicitConversionSequence::Better:
3588 // Cand1 has a better conversion sequence.
3589 HasBetterConversion = true;
3590 break;
3591
3592 case ImplicitConversionSequence::Worse:
3593 // Cand1 can't be better than Cand2.
3594 return false;
3595
3596 case ImplicitConversionSequence::Indistinguishable:
3597 // Do nothing.
3598 break;
3599 }
3600 }
3601
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003602 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3603 // ICSj(F2), or, if not that,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003604 if (HasBetterConversion)
3605 return true;
3606
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003607 // - F1 is a non-template function and F2 is a function template
3608 // specialization, or, if not that,
3609 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3610 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3611 return true;
3612
3613 // -- F1 and F2 are function template specializations, and the function
3614 // template for F1 is more specialized than the template for F2
3615 // according to the partial ordering rules described in 14.5.5.2, or,
3616 // if not that,
Douglas Gregorf8e51672009-08-02 23:46:29 +00003617 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3618 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor8c860df2009-08-21 23:19:43 +00003619 if (FunctionTemplateDecl *BetterTemplate
3620 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3621 Cand2.Function->getPrimaryTemplate(),
3622 true))
3623 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003624
Douglas Gregor60714f92008-11-07 22:36:19 +00003625 // -- the context is an initialization by user-defined conversion
3626 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3627 // from the return type of F1 to the destination type (i.e.,
3628 // the type of the entity being initialized) is a better
3629 // conversion sequence than the standard conversion sequence
3630 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003631 if (Cand1.Function && Cand2.Function &&
3632 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003633 isa<CXXConversionDecl>(Cand2.Function)) {
3634 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3635 Cand2.FinalConversion)) {
3636 case ImplicitConversionSequence::Better:
3637 // Cand1 has a better conversion sequence.
3638 return true;
3639
3640 case ImplicitConversionSequence::Worse:
3641 // Cand1 can't be better than Cand2.
3642 return false;
3643
3644 case ImplicitConversionSequence::Indistinguishable:
3645 // Do nothing
3646 break;
3647 }
3648 }
3649
Douglas Gregord2baafd2008-10-21 16:13:35 +00003650 return false;
3651}
3652
Douglas Gregor98189262009-06-19 23:52:42 +00003653/// \brief Computes the best viable function (C++ 13.3.3)
3654/// within an overload candidate set.
3655///
3656/// \param CandidateSet the set of candidate functions.
3657///
3658/// \param Loc the location of the function name (or operator symbol) for
3659/// which overload resolution occurs.
3660///
3661/// \param Best f overload resolution was successful or found a deleted
3662/// function, Best points to the candidate function found.
3663///
3664/// \returns The result of overload resolution.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003665Sema::OverloadingResult
3666Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003667 SourceLocation Loc,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003668 OverloadCandidateSet::iterator& Best)
3669{
3670 // Find the best viable function.
3671 Best = CandidateSet.end();
3672 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3673 Cand != CandidateSet.end(); ++Cand) {
3674 if (Cand->Viable) {
3675 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3676 Best = Cand;
3677 }
3678 }
3679
3680 // If we didn't find any viable functions, abort.
3681 if (Best == CandidateSet.end())
3682 return OR_No_Viable_Function;
3683
3684 // Make sure that this function is better than every other viable
3685 // function. If not, we have an ambiguity.
3686 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3687 Cand != CandidateSet.end(); ++Cand) {
3688 if (Cand->Viable &&
3689 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003690 !isBetterOverloadCandidate(*Best, *Cand)) {
3691 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003692 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003693 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003694 }
3695
3696 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003697 if (Best->Function &&
3698 (Best->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003699 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003700 return OR_Deleted;
3701
Douglas Gregor98189262009-06-19 23:52:42 +00003702 // C++ [basic.def.odr]p2:
3703 // An overloaded function is used if it is selected by overload resolution
3704 // when referred to from a potentially-evaluated expression. [Note: this
3705 // covers calls to named functions (5.2.2), operator overloading
3706 // (clause 13), user-defined conversions (12.3.2), allocation function for
3707 // placement new (5.3.4), as well as non-default initialization (8.5).
3708 if (Best->Function)
3709 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003710 return OR_Success;
3711}
3712
3713/// PrintOverloadCandidates - When overload resolution fails, prints
3714/// diagnostic messages containing the candidates in the candidate
3715/// set. If OnlyViable is true, only viable candidates will be printed.
3716void
3717Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3718 bool OnlyViable)
3719{
3720 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3721 LastCand = CandidateSet.end();
3722 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003723 if (Cand->Viable || !OnlyViable) {
3724 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003725 if (Cand->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003726 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003727 // Deleted or "unavailable" function.
3728 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3729 << Cand->Function->isDeleted();
3730 } else {
3731 // Normal function
3732 // FIXME: Give a better reason!
3733 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3734 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003735 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003736 // Desugar the type of the surrogate down to a function type,
3737 // retaining as many typedefs as possible while still showing
3738 // the function type (and, therefore, its parameter types).
3739 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003740 bool isLValueReference = false;
3741 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003742 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003743 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003744 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003745 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003746 isLValueReference = true;
3747 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003748 FnType->getAs<RValueReferenceType>()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003749 FnType = FnTypeRef->getPointeeType();
3750 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003751 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003752 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003753 FnType = FnTypePtr->getPointeeType();
3754 isPointer = true;
3755 }
3756 // Desugar down to a function type.
3757 FnType = QualType(FnType->getAsFunctionType(), 0);
3758 // Reconstruct the pointer/reference as appropriate.
3759 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003760 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3761 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003762
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003763 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003764 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003765 } else {
3766 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003767 // FIXME: Do we want the error message to point at the operator?
3768 // (built-ins won't have a location)
Douglas Gregor70d26122008-11-12 17:17:38 +00003769 QualType FnType
3770 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3771 Cand->BuiltinTypes.ParamTypes,
3772 Cand->Conversions.size(),
3773 false, 0);
3774
Chris Lattner4bfd2232008-11-24 06:25:27 +00003775 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003776 }
3777 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003778 }
3779}
3780
Douglas Gregor45014fd2008-11-10 20:40:00 +00003781/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3782/// an overloaded function (C++ [over.over]), where @p From is an
3783/// expression with overloaded function type and @p ToType is the type
3784/// we're trying to resolve to. For example:
3785///
3786/// @code
3787/// int f(double);
3788/// int f(int);
3789///
3790/// int (*pfd)(double) = f; // selects f(double)
3791/// @endcode
3792///
3793/// This routine returns the resulting FunctionDecl if it could be
3794/// resolved, and NULL otherwise. When @p Complain is true, this
3795/// routine will emit diagnostics if there is an error.
3796FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003797Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003798 bool Complain) {
3799 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003800 bool IsMember = false;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003801 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003802 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003803 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003804 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003805 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003806 ToType->getAs<MemberPointerType>()) {
Sebastian Redl7434fc32009-02-04 21:23:32 +00003807 FunctionType = MemTypePtr->getPointeeType();
3808 IsMember = true;
3809 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003810
3811 // We only look at pointers or references to functions.
Douglas Gregor72bb4992009-07-09 17:16:51 +00003812 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor62f78762009-07-08 20:55:45 +00003813 if (!FunctionType->isFunctionType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003814 return 0;
3815
3816 // Find the actual overloaded function declaration.
3817 OverloadedFunctionDecl *Ovl = 0;
3818
3819 // C++ [over.over]p1:
3820 // [...] [Note: any redundant set of parentheses surrounding the
3821 // overloaded function name is ignored (5.1). ]
3822 Expr *OvlExpr = From->IgnoreParens();
3823
3824 // C++ [over.over]p1:
3825 // [...] The overloaded function name can be preceded by the &
3826 // operator.
3827 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3828 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3829 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3830 }
3831
3832 // Try to dig out the overloaded function.
Douglas Gregor62f78762009-07-08 20:55:45 +00003833 FunctionTemplateDecl *FunctionTemplate = 0;
3834 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003835 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor62f78762009-07-08 20:55:45 +00003836 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3837 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003838
Douglas Gregor62f78762009-07-08 20:55:45 +00003839 // If there's no overloaded function declaration or function template,
3840 // we're done.
3841 if (!Ovl && !FunctionTemplate)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003842 return 0;
3843
Douglas Gregor62f78762009-07-08 20:55:45 +00003844 OverloadIterator Fun;
3845 if (Ovl)
3846 Fun = Ovl;
3847 else
3848 Fun = FunctionTemplate;
3849
Douglas Gregor45014fd2008-11-10 20:40:00 +00003850 // Look through all of the overloaded functions, searching for one
3851 // whose type matches exactly.
Douglas Gregora142a052009-07-08 23:33:52 +00003852 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3853
3854 bool FoundNonTemplateFunction = false;
Douglas Gregor62f78762009-07-08 20:55:45 +00003855 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003856 // C++ [over.over]p3:
3857 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003858 // targets of type "pointer-to-function" or "reference-to-function."
3859 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003860 // type "pointer-to-member-function."
3861 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor62f78762009-07-08 20:55:45 +00003862
3863 if (FunctionTemplateDecl *FunctionTemplate
3864 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003865 if (CXXMethodDecl *Method
3866 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3867 // Skip non-static function templates when converting to pointer, and
3868 // static when converting to member pointer.
3869 if (Method->isStatic() == IsMember)
3870 continue;
3871 } else if (IsMember)
3872 continue;
3873
3874 // C++ [over.over]p2:
3875 // If the name is a function template, template argument deduction is
3876 // done (14.8.2.2), and if the argument deduction succeeds, the
3877 // resulting template argument list is used to generate a single
3878 // function template specialization, which is added to the set of
3879 // overloaded functions considered.
Douglas Gregor62f78762009-07-08 20:55:45 +00003880 FunctionDecl *Specialization = 0;
3881 TemplateDeductionInfo Info(Context);
3882 if (TemplateDeductionResult Result
3883 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3884 /*FIXME:*/0, /*FIXME:*/0,
3885 FunctionType, Specialization, Info)) {
3886 // FIXME: make a note of the failed deduction for diagnostics.
3887 (void)Result;
3888 } else {
3889 assert(FunctionType
3890 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregora142a052009-07-08 23:33:52 +00003891 Matches.insert(
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003892 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor62f78762009-07-08 20:55:45 +00003893 }
3894 }
3895
Sebastian Redl7434fc32009-02-04 21:23:32 +00003896 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3897 // Skip non-static functions when converting to pointer, and static
3898 // when converting to member pointer.
3899 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003900 continue;
Douglas Gregora142a052009-07-08 23:33:52 +00003901 } else if (IsMember)
Sebastian Redl7434fc32009-02-04 21:23:32 +00003902 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003903
Douglas Gregorb60eb752009-06-25 22:08:12 +00003904 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003905 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003906 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregora142a052009-07-08 23:33:52 +00003907 FoundNonTemplateFunction = true;
3908 }
Douglas Gregor62f78762009-07-08 20:55:45 +00003909 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003910 }
3911
Douglas Gregora142a052009-07-08 23:33:52 +00003912 // If there were 0 or 1 matches, we're done.
3913 if (Matches.empty())
3914 return 0;
3915 else if (Matches.size() == 1)
3916 return *Matches.begin();
3917
3918 // C++ [over.over]p4:
3919 // If more than one function is selected, [...]
3920 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor8c860df2009-08-21 23:19:43 +00003921 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregora142a052009-07-08 23:33:52 +00003922 if (FoundNonTemplateFunction) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003923 // [...] any function template specializations in the set are
3924 // eliminated if the set also contains a non-template function, [...]
3925 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregora142a052009-07-08 23:33:52 +00003926 if ((*M)->getPrimaryTemplate() == 0)
3927 RemainingMatches.push_back(*M);
3928 } else {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003929 // [...] and any given function template specialization F1 is
3930 // eliminated if the set contains a second function template
3931 // specialization whose function template is more specialized
3932 // than the function template of F1 according to the partial
3933 // ordering rules of 14.5.5.2.
3934
3935 // The algorithm specified above is quadratic. We instead use a
3936 // two-pass algorithm (similar to the one used to identify the
3937 // best viable function in an overload set) that identifies the
3938 // best function template (if it exists).
3939 MatchIter Best = Matches.begin();
3940 MatchIter M = Best, MEnd = Matches.end();
3941 // Find the most specialized function.
3942 for (++M; M != MEnd; ++M)
3943 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
3944 (*Best)->getPrimaryTemplate(),
3945 false)
3946 == (*M)->getPrimaryTemplate())
3947 Best = M;
3948
3949 // Determine whether this function template is more specialized
3950 // that all of the others.
3951 bool Ambiguous = false;
3952 for (M = Matches.begin(); M != MEnd; ++M) {
3953 if (M != Best &&
3954 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
3955 (*Best)->getPrimaryTemplate(),
3956 false)
3957 != (*Best)->getPrimaryTemplate()) {
3958 Ambiguous = true;
3959 break;
3960 }
3961 }
3962
3963 // If one function template was more specialized than all of the
3964 // others, return it.
3965 if (!Ambiguous)
3966 return *Best;
3967
3968 // We could not find a most-specialized function template, which
3969 // is equivalent to having a set of function templates with more
3970 // than one such template. So, we place all of the function
3971 // templates into the set of remaining matches and produce a
3972 // diagnostic below. FIXME: we could perform the quadratic
3973 // algorithm here, pruning the result set to limit the number of
3974 // candidates output later.
3975 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregora142a052009-07-08 23:33:52 +00003976 }
3977
3978 // [...] After such eliminations, if any, there shall remain exactly one
3979 // selected function.
3980 if (RemainingMatches.size() == 1)
3981 return RemainingMatches.front();
3982
3983 // FIXME: We should probably return the same thing that BestViableFunction
3984 // returns (even if we issue the diagnostics here).
3985 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
3986 << RemainingMatches[0]->getDeclName();
3987 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
3988 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor45014fd2008-11-10 20:40:00 +00003989 return 0;
3990}
3991
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003992/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003993/// (which eventually refers to the declaration Func) and the call
3994/// arguments Args/NumArgs, attempt to resolve the function call down
3995/// to a specific function. If overload resolution succeeds, returns
3996/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003997/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003998/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003999FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004000 DeclarationName UnqualifiedName,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004001 bool HasExplicitTemplateArgs,
4002 const TemplateArgument *ExplicitTemplateArgs,
4003 unsigned NumExplicitTemplateArgs,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004004 SourceLocation LParenLoc,
4005 Expr **Args, unsigned NumArgs,
4006 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004007 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004008 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004009 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004010
4011 // Add the functions denoted by Callee to the set of candidate
4012 // functions. While we're doing so, track whether argument-dependent
4013 // lookup still applies, per:
4014 //
4015 // C++0x [basic.lookup.argdep]p3:
4016 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4017 // and let Y be the lookup set produced by argument dependent
4018 // lookup (defined as follows). If X contains
4019 //
4020 // -- a declaration of a class member, or
4021 //
4022 // -- a block-scope function declaration that is not a
4023 // using-declaration, or
4024 //
4025 // -- a declaration that is neither a function or a function
4026 // template
4027 //
4028 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004029 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004030 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4031 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4032 FuncEnd = Ovl->function_end();
4033 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00004034 DeclContext *Ctx = 0;
4035 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004036 if (HasExplicitTemplateArgs)
4037 continue;
4038
Douglas Gregorb60eb752009-06-25 22:08:12 +00004039 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4040 Ctx = FunDecl->getDeclContext();
4041 } else {
4042 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004043 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4044 ExplicitTemplateArgs,
4045 NumExplicitTemplateArgs,
4046 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004047 Ctx = FunTmpl->getDeclContext();
4048 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004049
Douglas Gregorb60eb752009-06-25 22:08:12 +00004050
4051 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004052 ArgumentDependentLookup = false;
4053 }
4054 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004055 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004056 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4057
4058 if (Func->getDeclContext()->isRecord() ||
4059 Func->getDeclContext()->isFunctionOrMethod())
4060 ArgumentDependentLookup = false;
Douglas Gregorb60eb752009-06-25 22:08:12 +00004061 } else if (FunctionTemplateDecl *FuncTemplate
4062 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004063 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4064 ExplicitTemplateArgs,
4065 NumExplicitTemplateArgs,
4066 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004067
4068 if (FuncTemplate->getDeclContext()->isRecord())
4069 ArgumentDependentLookup = false;
4070 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004071
4072 if (Callee)
4073 UnqualifiedName = Callee->getDeclName();
4074
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004075 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004076 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004077 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004078 CandidateSet);
4079
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004080 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004081 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004082 case OR_Success:
4083 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004084
4085 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00004086 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004087 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004088 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004089 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4090 break;
4091
4092 case OR_Ambiguous:
4093 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004094 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004095 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4096 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004097
4098 case OR_Deleted:
4099 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4100 << Best->Function->isDeleted()
4101 << UnqualifiedName
4102 << Fn->getSourceRange();
4103 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4104 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004105 }
4106
4107 // Overload resolution failed. Destroy all of the subexpressions and
4108 // return NULL.
4109 Fn->Destroy(Context);
4110 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4111 Args[Arg]->Destroy(Context);
4112 return 0;
4113}
4114
Douglas Gregorc78182d2009-03-13 23:49:33 +00004115/// \brief Create a unary operation that may resolve to an overloaded
4116/// operator.
4117///
4118/// \param OpLoc The location of the operator itself (e.g., '*').
4119///
4120/// \param OpcIn The UnaryOperator::Opcode that describes this
4121/// operator.
4122///
4123/// \param Functions The set of non-member functions that will be
4124/// considered by overload resolution. The caller needs to build this
4125/// set based on the context using, e.g.,
4126/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4127/// set should not contain any member functions; those will be added
4128/// by CreateOverloadedUnaryOp().
4129///
4130/// \param input The input argument.
4131Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4132 unsigned OpcIn,
4133 FunctionSet &Functions,
4134 ExprArg input) {
4135 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4136 Expr *Input = (Expr *)input.get();
4137
4138 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4139 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4140 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4141
4142 Expr *Args[2] = { Input, 0 };
4143 unsigned NumArgs = 1;
4144
4145 // For post-increment and post-decrement, add the implicit '0' as
4146 // the second argument, so that we know this is a post-increment or
4147 // post-decrement.
4148 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4149 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4150 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4151 SourceLocation());
4152 NumArgs = 2;
4153 }
4154
4155 if (Input->isTypeDependent()) {
4156 OverloadedFunctionDecl *Overloads
4157 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4158 for (FunctionSet::iterator Func = Functions.begin(),
4159 FuncEnd = Functions.end();
4160 Func != FuncEnd; ++Func)
4161 Overloads->addOverload(*Func);
4162
4163 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4164 OpLoc, false, false);
4165
4166 input.release();
4167 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4168 &Args[0], NumArgs,
4169 Context.DependentTy,
4170 OpLoc));
4171 }
4172
4173 // Build an empty overload set.
4174 OverloadCandidateSet CandidateSet;
4175
4176 // Add the candidates from the given function set.
4177 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4178
4179 // Add operator candidates that are member functions.
4180 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4181
4182 // Add builtin operator candidates.
4183 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4184
4185 // Perform overload resolution.
4186 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004187 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004188 case OR_Success: {
4189 // We found a built-in operator or an overloaded operator.
4190 FunctionDecl *FnDecl = Best->Function;
4191
4192 if (FnDecl) {
4193 // We matched an overloaded operator. Build a call to that
4194 // operator.
4195
4196 // Convert the arguments.
4197 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4198 if (PerformObjectArgumentInitialization(Input, Method))
4199 return ExprError();
4200 } else {
4201 // Convert the arguments.
4202 if (PerformCopyInitialization(Input,
4203 FnDecl->getParamDecl(0)->getType(),
4204 "passing"))
4205 return ExprError();
4206 }
4207
4208 // Determine the result type
4209 QualType ResultTy
4210 = FnDecl->getType()->getAsFunctionType()->getResultType();
4211 ResultTy = ResultTy.getNonReferenceType();
4212
4213 // Build the actual expression node.
4214 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4215 SourceLocation());
4216 UsualUnaryConversions(FnExpr);
4217
4218 input.release();
Anders Carlsson16497742009-08-16 04:11:06 +00004219
4220 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4221 &Input, 1, ResultTy, OpLoc);
4222 return MaybeBindToTemporary(CE);
Douglas Gregorc78182d2009-03-13 23:49:33 +00004223 } else {
4224 // We matched a built-in operator. Convert the arguments, then
4225 // break out so that we will build the appropriate built-in
4226 // operator node.
4227 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4228 Best->Conversions[0], "passing"))
4229 return ExprError();
4230
4231 break;
4232 }
4233 }
4234
4235 case OR_No_Viable_Function:
4236 // No viable function; fall through to handling this as a
4237 // built-in operator, which will produce an error message for us.
4238 break;
4239
4240 case OR_Ambiguous:
4241 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4242 << UnaryOperator::getOpcodeStr(Opc)
4243 << Input->getSourceRange();
4244 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4245 return ExprError();
4246
4247 case OR_Deleted:
4248 Diag(OpLoc, diag::err_ovl_deleted_oper)
4249 << Best->Function->isDeleted()
4250 << UnaryOperator::getOpcodeStr(Opc)
4251 << Input->getSourceRange();
4252 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4253 return ExprError();
4254 }
4255
4256 // Either we found no viable overloaded operator or we matched a
4257 // built-in operator. In either case, fall through to trying to
4258 // build a built-in operation.
4259 input.release();
4260 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4261}
4262
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004263/// \brief Create a binary operation that may resolve to an overloaded
4264/// operator.
4265///
4266/// \param OpLoc The location of the operator itself (e.g., '+').
4267///
4268/// \param OpcIn The BinaryOperator::Opcode that describes this
4269/// operator.
4270///
4271/// \param Functions The set of non-member functions that will be
4272/// considered by overload resolution. The caller needs to build this
4273/// set based on the context using, e.g.,
4274/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4275/// set should not contain any member functions; those will be added
4276/// by CreateOverloadedBinOp().
4277///
4278/// \param LHS Left-hand argument.
4279/// \param RHS Right-hand argument.
4280Sema::OwningExprResult
4281Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4282 unsigned OpcIn,
4283 FunctionSet &Functions,
4284 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004285 Expr *Args[2] = { LHS, RHS };
4286
4287 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4288 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4289 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4290
4291 // If either side is type-dependent, create an appropriate dependent
4292 // expression.
4293 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
4294 // .* cannot be overloaded.
4295 if (Opc == BinaryOperator::PtrMemD)
4296 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
4297 Context.DependentTy, OpLoc));
4298
4299 OverloadedFunctionDecl *Overloads
4300 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4301 for (FunctionSet::iterator Func = Functions.begin(),
4302 FuncEnd = Functions.end();
4303 Func != FuncEnd; ++Func)
4304 Overloads->addOverload(*Func);
4305
4306 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4307 OpLoc, false, false);
4308
4309 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4310 Args, 2,
4311 Context.DependentTy,
4312 OpLoc));
4313 }
4314
4315 // If this is the .* operator, which is not overloadable, just
4316 // create a built-in binary operator.
4317 if (Opc == BinaryOperator::PtrMemD)
4318 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4319
4320 // If this is one of the assignment operators, we only perform
4321 // overload resolution if the left-hand side is a class or
4322 // enumeration type (C++ [expr.ass]p3).
4323 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4324 !LHS->getType()->isOverloadableType())
4325 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4326
Douglas Gregorc78182d2009-03-13 23:49:33 +00004327 // Build an empty overload set.
4328 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004329
4330 // Add the candidates from the given function set.
4331 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4332
4333 // Add operator candidates that are member functions.
4334 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4335
4336 // Add builtin operator candidates.
4337 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4338
4339 // Perform overload resolution.
4340 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004341 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004342 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004343 // We found a built-in operator or an overloaded operator.
4344 FunctionDecl *FnDecl = Best->Function;
4345
4346 if (FnDecl) {
4347 // We matched an overloaded operator. Build a call to that
4348 // operator.
4349
4350 // Convert the arguments.
4351 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4352 if (PerformObjectArgumentInitialization(LHS, Method) ||
4353 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
4354 "passing"))
4355 return ExprError();
4356 } else {
4357 // Convert the arguments.
4358 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
4359 "passing") ||
4360 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
4361 "passing"))
4362 return ExprError();
4363 }
4364
4365 // Determine the result type
4366 QualType ResultTy
4367 = FnDecl->getType()->getAsFunctionType()->getResultType();
4368 ResultTy = ResultTy.getNonReferenceType();
4369
4370 // Build the actual expression node.
4371 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argiris Kirtzidiscca21b82009-07-14 03:19:38 +00004372 OpLoc);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004373 UsualUnaryConversions(FnExpr);
4374
Anders Carlsson16497742009-08-16 04:11:06 +00004375 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4376 Args, 2, ResultTy, OpLoc);
4377 return MaybeBindToTemporary(CE);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004378 } else {
4379 // We matched a built-in operator. Convert the arguments, then
4380 // break out so that we will build the appropriate built-in
4381 // operator node.
4382 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4383 Best->Conversions[0], "passing") ||
4384 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4385 Best->Conversions[1], "passing"))
4386 return ExprError();
4387
4388 break;
4389 }
4390 }
4391
4392 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004393 // For class as left operand for assignment or compound assigment operator
4394 // do not fall through to handling in built-in, but report that no overloaded
4395 // assignment operator found
4396 if (LHS->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4397 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4398 << BinaryOperator::getOpcodeStr(Opc)
4399 << LHS->getSourceRange() << RHS->getSourceRange();
4400 return ExprError();
4401 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004402 // No viable function; fall through to handling this as a
4403 // built-in operator, which will produce an error message for us.
4404 break;
4405
4406 case OR_Ambiguous:
4407 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4408 << BinaryOperator::getOpcodeStr(Opc)
4409 << LHS->getSourceRange() << RHS->getSourceRange();
4410 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4411 return ExprError();
4412
4413 case OR_Deleted:
4414 Diag(OpLoc, diag::err_ovl_deleted_oper)
4415 << Best->Function->isDeleted()
4416 << BinaryOperator::getOpcodeStr(Opc)
4417 << LHS->getSourceRange() << RHS->getSourceRange();
4418 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4419 return ExprError();
4420 }
4421
4422 // Either we found no viable overloaded operator or we matched a
4423 // built-in operator. In either case, try to build a built-in
4424 // operation.
4425 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4426}
4427
Douglas Gregor3257fb52008-12-22 05:46:06 +00004428/// BuildCallToMemberFunction - Build a call to a member
4429/// function. MemExpr is the expression that refers to the member
4430/// function (and includes the object parameter), Args/NumArgs are the
4431/// arguments to the function call (not including the object
4432/// parameter). The caller needs to validate that the member
4433/// expression refers to a member function or an overloaded member
4434/// function.
4435Sema::ExprResult
4436Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4437 SourceLocation LParenLoc, Expr **Args,
4438 unsigned NumArgs, SourceLocation *CommaLocs,
4439 SourceLocation RParenLoc) {
4440 // Dig out the member expression. This holds both the object
4441 // argument and the member function we're referring to.
4442 MemberExpr *MemExpr = 0;
4443 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4444 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4445 else
4446 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4447 assert(MemExpr && "Building member call without member expression");
4448
4449 // Extract the object argument.
4450 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004451
Douglas Gregor3257fb52008-12-22 05:46:06 +00004452 CXXMethodDecl *Method = 0;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004453 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4454 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004455 // Add overload candidates
4456 OverloadCandidateSet CandidateSet;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004457 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4458
Douglas Gregor050cabf2009-08-21 18:42:58 +00004459 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4460 Func != FuncEnd; ++Func) {
4461 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4462 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4463 /*SuppressUserConversions=*/false);
4464 else
4465 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4466 /*FIXME:*/false, /*FIXME:*/0,
4467 /*FIXME:*/0, ObjectArg, Args, NumArgs,
4468 CandidateSet,
4469 /*SuppressUsedConversions=*/false);
4470 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004471
Douglas Gregor3257fb52008-12-22 05:46:06 +00004472 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004473 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004474 case OR_Success:
4475 Method = cast<CXXMethodDecl>(Best->Function);
4476 break;
4477
4478 case OR_No_Viable_Function:
4479 Diag(MemExpr->getSourceRange().getBegin(),
4480 diag::err_ovl_no_viable_member_function_in_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;
4485
4486 case OR_Ambiguous:
4487 Diag(MemExpr->getSourceRange().getBegin(),
4488 diag::err_ovl_ambiguous_member_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004489 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004490 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4491 // FIXME: Leaking incoming expressions!
4492 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004493
4494 case OR_Deleted:
4495 Diag(MemExpr->getSourceRange().getBegin(),
4496 diag::err_ovl_deleted_member_call)
4497 << Best->Function->isDeleted()
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004498 << DeclName << MemExprE->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004499 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4500 // FIXME: Leaking incoming expressions!
4501 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004502 }
4503
4504 FixOverloadedFunctionReference(MemExpr, Method);
4505 } else {
4506 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4507 }
4508
4509 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004510 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004511 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4512 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004513 Method->getResultType().getNonReferenceType(),
4514 RParenLoc));
4515
4516 // Convert the object argument (for a non-static member function call).
4517 if (!Method->isStatic() &&
4518 PerformObjectArgumentInitialization(ObjectArg, Method))
4519 return true;
4520 MemExpr->setBase(ObjectArg);
4521
4522 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004523 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004524 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4525 RParenLoc))
4526 return true;
4527
Anders Carlsson7fb13802009-08-16 01:56:34 +00004528 if (CheckFunctionCall(Method, TheCall.get()))
4529 return true;
Anders Carlssonb8ff3402009-08-16 03:42:12 +00004530
4531 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004532}
4533
Douglas Gregor10f3c502008-11-19 21:05:33 +00004534/// BuildCallToObjectOfClassType - Build a call to an object of class
4535/// type (C++ [over.call.object]), which can end up invoking an
4536/// overloaded function call operator (@c operator()) or performing a
4537/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004538Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004539Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4540 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004541 Expr **Args, unsigned NumArgs,
4542 SourceLocation *CommaLocs,
4543 SourceLocation RParenLoc) {
4544 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004545 const RecordType *Record = Object->getType()->getAs<RecordType>();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004546
4547 // C++ [over.call.object]p1:
4548 // If the primary-expression E in the function call syntax
Eli Friedmand5a72f02009-08-05 19:21:58 +00004549 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor10f3c502008-11-19 21:05:33 +00004550 // candidate functions includes at least the function call
4551 // operators of T. The function call operators of T are obtained by
4552 // ordinary lookup of the name operator() in the context of
4553 // (E).operator().
4554 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004555 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004556 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004557 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004558 Oper != OperEnd; ++Oper)
4559 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4560 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004561
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004562 // C++ [over.call.object]p2:
4563 // In addition, for each conversion function declared in T of the
4564 // form
4565 //
4566 // operator conversion-type-id () cv-qualifier;
4567 //
4568 // where cv-qualifier is the same cv-qualification as, or a
4569 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004570 // denotes the type "pointer to function of (P1,...,Pn) returning
4571 // R", or the type "reference to pointer to function of
4572 // (P1,...,Pn) returning R", or the type "reference to function
4573 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004574 // is also considered as a candidate function. Similarly,
4575 // surrogate call functions are added to the set of candidate
4576 // functions for each conversion function declared in an
4577 // accessible base class provided the function is not hidden
4578 // within T by another intervening declaration.
4579 //
4580 // FIXME: Look in base classes for more conversion operators!
4581 OverloadedFunctionDecl *Conversions
4582 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004583 for (OverloadedFunctionDecl::function_iterator
4584 Func = Conversions->function_begin(),
4585 FuncEnd = Conversions->function_end();
4586 Func != FuncEnd; ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00004587 CXXConversionDecl *Conv;
4588 FunctionTemplateDecl *ConvTemplate;
4589 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
4590
4591 // Skip over templated conversion functions; they aren't
4592 // surrogates.
4593 if (ConvTemplate)
4594 continue;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004595
4596 // Strip the reference type (if any) and then the pointer type (if
4597 // any) to get down to what might be a function type.
4598 QualType ConvType = Conv->getConversionType().getNonReferenceType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004599 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004600 ConvType = ConvPtrType->getPointeeType();
4601
Douglas Gregor4fa58902009-02-26 23:50:07 +00004602 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004603 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4604 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004605
4606 // Perform overload resolution.
4607 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004608 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004609 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004610 // Overload resolution succeeded; we'll build the appropriate call
4611 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004612 break;
4613
4614 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004615 Diag(Object->getSourceRange().getBegin(),
4616 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004617 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004618 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004619 break;
4620
4621 case OR_Ambiguous:
4622 Diag(Object->getSourceRange().getBegin(),
4623 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004624 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004625 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4626 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004627
4628 case OR_Deleted:
4629 Diag(Object->getSourceRange().getBegin(),
4630 diag::err_ovl_deleted_object_call)
4631 << Best->Function->isDeleted()
4632 << Object->getType() << Object->getSourceRange();
4633 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4634 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004635 }
4636
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004637 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004638 // We had an error; delete all of the subexpressions and return
4639 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004640 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004641 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004642 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004643 return true;
4644 }
4645
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004646 if (Best->Function == 0) {
4647 // Since there is no function declaration, this is one of the
4648 // surrogate candidates. Dig out the conversion function.
4649 CXXConversionDecl *Conv
4650 = cast<CXXConversionDecl>(
4651 Best->Conversions[0].UserDefined.ConversionFunction);
4652
4653 // We selected one of the surrogate functions that converts the
4654 // object parameter to a function pointer. Perform the conversion
4655 // on the object argument, then let ActOnCallExpr finish the job.
4656 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004657 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004658 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00004659 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00004660 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004661 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4662 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4663 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004664 }
4665
4666 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4667 // that calls this method, using Object for the implicit object
4668 // parameter and passing along the remaining arguments.
4669 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004670 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004671
4672 unsigned NumArgsInProto = Proto->getNumArgs();
4673 unsigned NumArgsToCheck = NumArgs;
4674
4675 // Build the full argument list for the method call (the
4676 // implicit object parameter is placed at the beginning of the
4677 // list).
4678 Expr **MethodArgs;
4679 if (NumArgs < NumArgsInProto) {
4680 NumArgsToCheck = NumArgsInProto;
4681 MethodArgs = new Expr*[NumArgsInProto + 1];
4682 } else {
4683 MethodArgs = new Expr*[NumArgs + 1];
4684 }
4685 MethodArgs[0] = Object;
4686 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4687 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4688
Ted Kremenek0c97e042009-02-07 01:47:29 +00004689 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4690 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004691 UsualUnaryConversions(NewFn);
4692
4693 // Once we've built TheCall, all of the expressions are properly
4694 // owned.
4695 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004696 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004697 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4698 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004699 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004700 delete [] MethodArgs;
4701
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004702 // We may have default arguments. If so, we need to allocate more
4703 // slots in the call for them.
4704 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004705 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004706 else if (NumArgs > NumArgsInProto)
4707 NumArgsToCheck = NumArgsInProto;
4708
Chris Lattner81f00ed2009-04-12 08:11:20 +00004709 bool IsError = false;
4710
Douglas Gregor10f3c502008-11-19 21:05:33 +00004711 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004712 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004713 TheCall->setArg(0, Object);
4714
Chris Lattner81f00ed2009-04-12 08:11:20 +00004715
Douglas Gregor10f3c502008-11-19 21:05:33 +00004716 // Check the argument types.
4717 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004718 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004719 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004720 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004721
4722 // Pass the argument.
4723 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004724 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004725 } else {
Anders Carlsson3d752db2009-08-14 18:30:22 +00004726 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004727 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004728
4729 TheCall->setArg(i + 1, Arg);
4730 }
4731
4732 // If this is a variadic call, handle args passed through "...".
4733 if (Proto->isVariadic()) {
4734 // Promote the arguments (C99 6.5.2.2p7).
4735 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4736 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004737 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004738 TheCall->setArg(i + 1, Arg);
4739 }
4740 }
4741
Chris Lattner81f00ed2009-04-12 08:11:20 +00004742 if (IsError) return true;
4743
Anders Carlsson7fb13802009-08-16 01:56:34 +00004744 if (CheckFunctionCall(Method, TheCall.get()))
4745 return true;
4746
Anders Carlsson422a5fe2009-08-16 03:53:54 +00004747 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004748}
4749
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004750/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4751/// (if one exists), where @c Base is an expression of class type and
4752/// @c Member is the name of the member we're trying to find.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004753Sema::OwningExprResult
4754Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4755 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004756 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4757
4758 // C++ [over.ref]p1:
4759 //
4760 // [...] An expression x->m is interpreted as (x.operator->())->m
4761 // for a class object x of type T if T::operator->() exists and if
4762 // the operator is selected as the best match function by the
4763 // overload resolution mechanism (13.3).
4764 // FIXME: look in base classes.
4765 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4766 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004767 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorda61ad22009-08-06 03:17:00 +00004768
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004769 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004770 for (llvm::tie(Oper, OperEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004771 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004772 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004773 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004774
4775 // Perform overload resolution.
4776 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004777 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004778 case OR_Success:
4779 // Overload resolution succeeded; we'll build the call below.
4780 break;
4781
4782 case OR_No_Viable_Function:
4783 if (CandidateSet.empty())
4784 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004785 << Base->getType() << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004786 else
4787 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004788 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004789 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004790 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004791
4792 case OR_Ambiguous:
4793 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004794 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004795 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004796 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004797
4798 case OR_Deleted:
4799 Diag(OpLoc, diag::err_ovl_deleted_oper)
4800 << Best->Function->isDeleted()
Douglas Gregorda61ad22009-08-06 03:17:00 +00004801 << "operator->" << Base->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004802 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004803 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004804 }
4805
4806 // Convert the object parameter.
4807 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004808 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorda61ad22009-08-06 03:17:00 +00004809 return ExprError();
Douglas Gregor9c690e92008-11-21 03:04:22 +00004810
4811 // No concerns about early exits now.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004812 BaseIn.release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004813
4814 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004815 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4816 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004817 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004818 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004819 Method->getResultType().getNonReferenceType(),
4820 OpLoc);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004821 return Owned(Base);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004822}
4823
Douglas Gregor45014fd2008-11-10 20:40:00 +00004824/// FixOverloadedFunctionReference - E is an expression that refers to
4825/// a C++ overloaded function (possibly with some parentheses and
4826/// perhaps a '&' around it). We have resolved the overloaded function
4827/// to the function declaration Fn, so patch up the expression E to
4828/// refer (possibly indirectly) to Fn.
4829void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4830 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4831 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4832 E->setType(PE->getSubExpr()->getType());
4833 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4834 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4835 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004836 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4837 if (Method->isStatic()) {
4838 // Do nothing: static member functions aren't any different
4839 // from non-member functions.
Mike Stump90fc78e2009-08-04 21:02:39 +00004840 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor3f411962009-02-11 01:18:59 +00004841 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4842 // We have taken the address of a pointer to member
4843 // function. Perform the computation here so that we get the
4844 // appropriate pointer to member type.
4845 DRE->setDecl(Fn);
4846 DRE->setType(Fn->getType());
4847 QualType ClassType
4848 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4849 E->setType(Context.getMemberPointerType(Fn->getType(),
4850 ClassType.getTypePtr()));
4851 return;
4852 }
4853 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004854 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004855 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004856 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor62f78762009-07-08 20:55:45 +00004857 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4858 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4859 "Expected overloaded function or function template");
Douglas Gregor45014fd2008-11-10 20:40:00 +00004860 DR->setDecl(Fn);
4861 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004862 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4863 MemExpr->setMemberDecl(Fn);
4864 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004865 } else {
4866 assert(false && "Invalid reference to overloaded function");
4867 }
4868}
4869
Douglas Gregord2baafd2008-10-21 16:13:35 +00004870} // end namespace clang